1package agent
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/signal"
12 "path/filepath"
13 "strings"
14 "sync"
15 "syscall"
16 "time"
17
18 "github.com/patriceckhart/zot/packages/agent/extensions"
19 "github.com/patriceckhart/zot/packages/agent/extproto"
20 "github.com/patriceckhart/zot/packages/agent/modes"
21 "github.com/patriceckhart/zot/packages/agent/skills"
22 "github.com/patriceckhart/zot/packages/agent/swarm"
23 "github.com/patriceckhart/zot/packages/agent/tools"
24 "github.com/patriceckhart/zot/packages/core"
25 "github.com/patriceckhart/zot/packages/provider"
26 "github.com/patriceckhart/zot/packages/provider/auth"
27 "github.com/patriceckhart/zot/packages/tui"
28)
29
30// interactiveExtHooks is a tiny adapter that lets the extension
31// manager call back into the Interactive instance built later in
32// runInteractive. The forward-declared *modes.Interactive is filled
33// in immediately after manager construction.
34type interactiveExtHooks struct {
35 ivPtr **modes.Interactive
36}
37
38func (h *interactiveExtHooks) iv() *modes.Interactive {
39 if h == nil || h.ivPtr == nil {
40 return nil
41 }
42 return *h.ivPtr
43}
44
45func (h *interactiveExtHooks) Notify(extName, level, message string) {
46 if iv := h.iv(); iv != nil {
47 iv.Notify(extName, level, message)
48 }
49}
50func (h *interactiveExtHooks) Submit(text string) {
51 if iv := h.iv(); iv != nil {
52 iv.SubmitOrQueue(text, nil)
53 }
54}
55func (h *interactiveExtHooks) SubmitSlash(text string) {
56 if iv := h.iv(); iv != nil {
57 iv.SubmitSlash(text)
58 }
59}
60func (h *interactiveExtHooks) Insert(text string) {
61 if iv := h.iv(); iv != nil {
62 iv.Insert(text)
63 }
64}
65func (h *interactiveExtHooks) Display(extName, text string) {
66 if iv := h.iv(); iv != nil {
67 iv.Display(extName, text)
68 }
69}
70func (h *interactiveExtHooks) ClearNotes(extName string) {
71 if iv := h.iv(); iv != nil {
72 iv.ClearNotes(extName)
73 }
74}
75func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
76 if iv := h.iv(); iv != nil {
77 iv.OpenPanel(extName, spec)
78 }
79}
80func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
81 if iv := h.iv(); iv != nil {
82 iv.UpdatePanel(extName, panelID, title, lines, footer)
83 }
84}
85func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
86 if iv := h.iv(); iv != nil {
87 iv.ClosePanel(extName, panelID)
88 }
89}
90
91// extToolAdapter bridges *extensions.Manager to the
92// ExtensionToolSource interface declared in build.go (kept narrow to
93// avoid a build->extensions import cycle). One adapter instance per
94// run; used at every Resolve point so re-built agents pick up the
95// same set of extension tools.
96type extToolAdapter struct {
97 mgr *extensions.Manager
98}
99
100func (a *extToolAdapter) Tools() []ExtensionToolInfo {
101 infos := a.mgr.Tools()
102 out := make([]ExtensionToolInfo, len(infos))
103 for i, t := range infos {
104 out[i] = ExtensionToolInfo{
105 Extension: t.Extension,
106 Name: t.Name,
107 Description: t.Description,
108 Schema: t.Schema,
109 Deferred: t.Deferred,
110 }
111 }
112 return out
113}
114
115func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
116 return extensions.NewTool(a.mgr, extensions.ToolInfo{
117 Extension: info.Extension,
118 Name: info.Name,
119 Description: info.Description,
120 Schema: info.Schema,
121 Deferred: info.Deferred,
122 })
123}
124
125// liveInteractiveAgent returns the agent currently owned by the TUI. The
126// fallback is only used before the Interactive has been constructed.
127//
128// Agent rebuilds, such as cross-provider model switches, replace the TUI's
129// agent without replacing the startup pointer held by runInteractive. Session
130// operations must therefore resolve the live agent at the time of the action.
131func liveInteractiveAgent(iv *modes.Interactive, fallback *core.Agent) *core.Agent {
132 if iv != nil {
133 return iv.Agent()
134 }
135 return fallback
136}
137
138func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
139 if keepTail <= 0 || len(msgs) <= keepTail {
140 return provider.RepairOrphanedToolResults(msgs)
141 }
142 var out []provider.Message
143 start := len(msgs) - keepTail
144 // Preserve the synthetic compaction summary when present so an
145 // already-compacted session stays compacted after resume.
146 if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 1 {
147 out = append(out, msgs[0])
148 }
149 // Avoid hydrating a tail that starts with orphan tool_result rows;
150 // provider APIs require those to be paired with an earlier tool_use.
151 for start < len(msgs) && msgs[start].Role == provider.RoleTool {
152 start++
153 }
154 out = append(out, msgs[start:]...)
155 return provider.RepairOrphanedToolResults(out)
156}
157
158// fanoutAgentEvent translates a core.AgentEvent into the wire-format
159// EventFromHost and pushes it through the extension manager. Only
160// the events that have a clear extension-facing meaning are
161// forwarded; internal-only ones (text_delta, tool_progress) are
162// dropped to keep the per-extension stream sane.
163func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
164 if mgr == nil {
165 return
166 }
167 switch e := ev.(type) {
168 case core.EvTurnStart:
169 mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
170 case core.EvToolCall:
171 mgr.EmitEvent(extproto.EventFromHost{
172 Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
173 })
174 case core.EvAssistantMessage:
175 // Concat the visible text portions of the message; binary
176 // blocks (tool_use, etc.) are skipped because subscribers
177 // usually want a string they can grep / display.
178 var text string
179 for _, c := range e.Message.Content {
180 if tb, ok := c.(provider.TextBlock); ok {
181 text += tb.Text
182 }
183 }
184 mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
185 case core.EvTurnEnd:
186 ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
187 if e.Err != nil {
188 ev.Error = e.Err.Error()
189 }
190 mgr.EmitEvent(ev)
191 }
192}
193
194// Run is the top-level entrypoint for the zot binary.
195func Run(rawArgs []string, version string) error {
196 // Apply network configuration before any subcommand can make an HTTP
197 // request. Standard proxy environment variables retain precedence.
198 applyConfiguredHTTPProxy()
199
200 // Subcommand router: `zot bot ...` is handled separately so the
201 // generic flag parser doesn't reject "bot" as a positional arg.
202 if handled, err := runBotCommand(rawArgs, version); handled {
203 return err
204 }
205 if handled, err := runExtCommand(rawArgs, version); handled {
206 return err
207 }
208 if handled, err := runUpdateCommand(rawArgs, version); handled {
209 return err
210 }
211 if handled, err := runSessionsCommand(rawArgs); handled {
212 return err
213 }
214 if handled, err := runZotfileCommand(rawArgs, version); handled {
215 return err
216 }
217 return runWithArgsRaw(rawArgs, version)
218}
219
220func runWithArgsRaw(rawArgs []string, version string) error {
221 // `zot rpc` is shorthand for `zot --rpc` so third-party apps can
222 // spawn the binary with a clean argv. Strip the leading 'rpc'
223 // token and let the rest flow through the normal arg parser.
224 if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
225 rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
226 }
227
228 if fi, err := os.Stdin.Stat(); err == nil {
229 rawArgs = argsForStdin(rawArgs, fi.Mode())
230 }
231 args, err := ParseArgs(rawArgs)
232 if err != nil {
233 PrintHelp(version)
234 return err
235 }
236 if args.Help {
237 printHelp(os.Stdout, version)
238 return nil
239 }
240 if args.Version {
241 fmt.Println("zot", version)
242 return nil
243 }
244 // Model catalog: load any cached discovery data before we inspect
245 // the model list (list-models, print/json, interactive).
246 prepareRuntimeCatalog()
247
248 if args.ListModels {
249 printModels()
250 return nil
251 }
252
253 return runWithArgs(args, version)
254}
255
256func runWithArgs(args Args, version string) error {
257 ctx := context.Background()
258 switch args.Mode {
259 case ModePrint:
260 return runPrintMode(ctx, args, version)
261 case ModeStream:
262 return runStreamMode(ctx, args, version)
263 case ModeJSON:
264 return runJSONMode(ctx, args, version)
265 case ModeRPC:
266 return runRPCMode(ctx, args, version)
267 case ModeSwarmAgent:
268 return runSwarmAgentMode(ctx, args, version)
269 default:
270 return runInteractive(ctx, args, version)
271 }
272}
273
274// ---- print / json modes: require credentials, run single-shot ----
275
276// nonInteractiveExtHooks is the HostHooks impl used by print / json
277// modes. They have no TUI, so notify / display go to stderr and
278// submit / insert are no-ops (the extension can't steer a
279// single-shot run once it's in flight anyway).
280type nonInteractiveExtHooks struct{}
281
282func (nonInteractiveExtHooks) Notify(ext, level, message string) {
283 fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
284}
285func (nonInteractiveExtHooks) Submit(string) {}
286func (nonInteractiveExtHooks) SubmitSlash(string) {}
287func (nonInteractiveExtHooks) Insert(string) {}
288func (nonInteractiveExtHooks) Display(string, string) {}
289func (nonInteractiveExtHooks) ClearNotes(string) {}
290func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec) {}
291func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
292func (nonInteractiveExtHooks) ClosePanel(string, string) {}
293
294// setupNonInteractiveExtensions loads --ext paths and (unless
295// --no-ext) runs discovery. Returns the manager so the caller can
296// wire tools into the resolved registry, and a cleanup closure to
297// defer. Mirrors the interactive-mode setup minus the TUI hooks.
298func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
299 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
300 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
301 fmt.Fprintln(os.Stderr, "extension load:", e)
302 }
303 if !args.NoExt {
304 for _, e := range extMgr.Discover(ctx) {
305 fmt.Fprintln(os.Stderr, "extension load:", e)
306 }
307 }
308 extMgr.WaitForReady(3 * time.Second)
309 r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
310 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
311 return extMgr, func() { extMgr.Stop(2 * time.Second) }
312}
313
314// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
315// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
316// interactive path wires up, so extensions get their normal
317// event-intercept surface in print / json / rpc flows too.
318func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
319 if ag == nil || extMgr == nil {
320 return
321 }
322 ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
323 res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
324 if res.Block {
325 return false, res.Reason, nil
326 }
327 return true, "", res.ModifiedArgs
328 }
329 ag.BeforeTurn = func(step int) (bool, string) {
330 res := extMgr.InterceptTurnStart(ctx, step)
331 return !res.Block, res.Reason
332 }
333 ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
334 res := extMgr.InterceptAssistantMessage(ctx, text)
335 if res.Block {
336 return false, res.Reason, ""
337 }
338 return true, "", res.ReplaceText
339 }
340 ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
341}
342
343type printStats struct {
344 Provider string `json:"provider"`
345 Model string `json:"model"`
346 PromptTokens int `json:"prompt_tokens"`
347 ReasoningTokens *int `json:"reasoning_tokens"`
348 GeneratedOutputTokens int `json:"generated_output_tokens"`
349 ElapsedMS int64 `json:"elapsed_ms"`
350}
351
352func writePrintStats(path, providerID, model string, usage provider.Usage, elapsed time.Duration) error {
353 var reasoning *int
354 generated := usage.OutputTokens
355 if usage.ReasoningTokensKnown {
356 count := usage.ReasoningTokens
357 reasoning = &count
358 generated -= count
359 if generated < 0 {
360 generated = 0
361 }
362 }
363 stats := printStats{
364 Provider: providerID,
365 Model: model,
366 PromptTokens: usage.InputTokens + usage.CacheReadTokens + usage.CacheWriteTokens,
367 ReasoningTokens: reasoning,
368 GeneratedOutputTokens: generated,
369 ElapsedMS: elapsed.Milliseconds(),
370 }
371 data, err := json.MarshalIndent(stats, "", " ")
372 if err != nil {
373 return fmt.Errorf("encode stats: %w", err)
374 }
375 data = append(data, '\n')
376 if err := os.WriteFile(path, data, 0o644); err != nil {
377 return fmt.Errorf("write stats %q: %w", path, err)
378 }
379 return nil
380}
381
382func runPrintMode(ctx context.Context, args Args, version string) error {
383 if args.NoYolo {
384 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
385 }
386 r, err := Resolve(args, true)
387 if err != nil {
388 return err
389 }
390 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
391 defer stopExt()
392
393 ag := r.NewAgent()
394 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
395 sess, _ := openOrCreateSession(args, r, ag, version)
396 defer sess.Close()
397
398 piped, _ := readAllStdin()
399 prompt := combinePromptInput(piped, args.Prompt)
400 if prompt == "" {
401 return fmt.Errorf("print mode requires a prompt (arg or stdin)")
402 }
403
404 start := len(ag.Messages())
405 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, nil, os.Stderr); err != nil {
406 return err
407 }
408 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
409 started := time.Now()
410 usage, err := modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
411 elapsed := time.Since(started)
412 WriteNewTranscript(ag, sess, start)
413 if err != nil {
414 return err
415 }
416 if args.StatsPath != "" {
417 return writePrintStats(args.StatsPath, r.Provider, r.Model, usage, elapsed)
418 }
419 return nil
420}
421
422func runStreamMode(ctx context.Context, args Args, version string) error {
423 if args.NoYolo {
424 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in stream mode (no interactive prompt available); tools will run without confirmation")
425 }
426 r, err := Resolve(args, true)
427 if err != nil {
428 return err
429 }
430 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
431 defer stopExt()
432
433 ag := r.NewAgent()
434 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
435 sess, _ := openOrCreateSession(args, r, ag, version)
436 defer sess.Close()
437
438 piped, _ := readAllStdin()
439 prompt := combinePromptInput(piped, args.Prompt)
440 if prompt == "" {
441 return fmt.Errorf("stream mode requires a prompt (arg or stdin)")
442 }
443
444 start := len(ag.Messages())
445 preSink, finishPre := newStreamTextSink(os.Stdout)
446 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
447 finishPre()
448 return err
449 }
450 finishPre()
451 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
452 err = modes.RunStream(ctx, ag, prompt, nil, os.Stdout)
453 WriteNewTranscript(ag, sess, start)
454 return err
455}
456
457func newStreamTextSink(out io.Writer) (func(core.AgentEvent), func()) {
458 var streamed, wroteText, lastWasNL bool
459 writeText := func(text string) {
460 if text == "" {
461 return
462 }
463 _, _ = fmt.Fprint(out, text)
464 if syncer, ok := out.(interface{ Sync() error }); ok {
465 _ = syncer.Sync()
466 }
467 wroteText = true
468 lastWasNL = strings.HasSuffix(text, "\n")
469 }
470 sink := func(ev core.AgentEvent) {
471 switch e := ev.(type) {
472 case core.EvAssistantStart:
473 streamed = false
474 case core.EvTextDelta:
475 streamed = true
476 writeText(e.Delta)
477 case core.EvAssistantMessage:
478 if streamed {
479 return
480 }
481 var text strings.Builder
482 for _, content := range e.Message.Content {
483 if block, ok := content.(provider.TextBlock); ok {
484 if text.Len() > 0 {
485 text.WriteString("\n")
486 }
487 text.WriteString(block.Text)
488 }
489 }
490 writeText(text.String())
491 }
492 }
493 finish := func() {
494 if wroteText && !lastWasNL {
495 writeText("\n")
496 }
497 }
498 return sink, finish
499}
500
501func runJSONMode(ctx context.Context, args Args, version string) error {
502 if args.NoYolo {
503 fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
504 }
505 r, err := Resolve(args, true)
506 if err != nil {
507 return err
508 }
509 extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
510 defer stopExt()
511
512 ag := r.NewAgent()
513 wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
514 sess, _ := openOrCreateSession(args, r, ag, version)
515 defer sess.Close()
516
517 piped, _ := readAllStdin()
518 prompt := combinePromptInput(piped, args.Prompt)
519 if prompt == "" {
520 return fmt.Errorf("json mode requires a prompt (arg or stdin)")
521 }
522
523 start := len(ag.Messages())
524 enc := json.NewEncoder(os.Stdout)
525 preSink := func(ev core.AgentEvent) {
526 _ = enc.Encode(modes.EventToJSON(ev))
527 }
528 if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
529 _ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
530 return err
531 }
532 reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
533 err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
534 WriteNewTranscript(ag, sess, start)
535 return err
536}
537
538// runZotfileStartupPre runs entry.pre before the main non-interactive prompt.
539// "!command" values execute via BashTool; other values are sent as an agent turn.
540// shellOut receives live shell chunks (typically os.Stderr); sink receives
541// agent events for plain-text pre (stream mode wires a live text sink).
542func runZotfileStartupPre(ctx context.Context, pre, cwd string, sandbox *tools.Sandbox, ag *core.Agent, sink func(core.AgentEvent), shellOut io.Writer) error {
543 pre = strings.TrimSpace(pre)
544 if pre == "" {
545 return nil
546 }
547 if cmd, ok := modes.ShellEscapeCommand(pre); ok {
548 raw, err := json.Marshal(map[string]any{"command": cmd})
549 if err != nil {
550 return err
551 }
552 if shellOut != nil {
553 fmt.Fprintf(shellOut, "$ %s\n", cmd)
554 if f, ok := shellOut.(interface{ Sync() error }); ok {
555 _ = f.Sync()
556 }
557 }
558 progress := func(chunk string) {
559 if shellOut == nil || chunk == "" {
560 return
561 }
562 fmt.Fprint(shellOut, chunk)
563 if f, ok := shellOut.(interface{ Sync() error }); ok {
564 _ = f.Sync()
565 }
566 }
567 bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
568 res, err := bash.Execute(ctx, raw, progress)
569 if err != nil {
570 return fmt.Errorf("zotfile entry.pre: %w", err)
571 }
572 if res.IsError {
573 var sb strings.Builder
574 for _, c := range res.Content {
575 if tb, ok := c.(provider.TextBlock); ok {
576 sb.WriteString(tb.Text)
577 }
578 }
579 msg := strings.TrimSpace(sb.String())
580 if msg == "" {
581 msg = "command failed"
582 }
583 return fmt.Errorf("zotfile entry.pre: %s", msg)
584 }
585 return nil
586 }
587 if ag == nil {
588 return fmt.Errorf("zotfile entry.pre requires an agent for non-shell prompts")
589 }
590 if sink == nil {
591 sink = func(core.AgentEvent) {}
592 }
593 return ag.Prompt(ctx, pre, nil, sink)
594}
595
596// refreshAgentToolsAndPrompt re-resolves tools (including rediscovered
597// skills and currently loaded extension tools) and updates the live
598// agent's registry and system prompt. Used after /reload-ext and after
599// zotfile entry.pre installs new skills or extensions.
600// mutateRegistry, if non-nil, can inject session-specific tools (e.g. swarm_spawn).
601func refreshAgentToolsAndPrompt(args Args, sharedSandbox *tools.Sandbox, extToolAdapter ExtensionToolSource, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry) {
602 if ag == nil {
603 return
604 }
605 resolved, err := Resolve(args, true)
606 if err != nil {
607 return
608 }
609 if sharedSandbox != nil {
610 resolved.UseSandbox(sharedSandbox)
611 }
612 if extToolAdapter != nil {
613 resolved.MergeExtensionTools(extToolAdapter)
614 }
615 reg := resolved.ToolRegistry
616 if mutateRegistry != nil {
617 reg = mutateRegistry(reg)
618 }
619 ag.SetTools(reg)
620 ag.System = resolved.SystemPrompt
621}
622
623// reloadResourcesAfterStartupPre reloads extensions (if any) and
624// refreshes the agent tool registry + system prompt so skills/extensions
625// installed by entry.pre are visible to the following turn.
626func reloadResourcesAfterStartupPre(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent) {
627 if strings.TrimSpace(args.StartupPre) == "" || ag == nil {
628 return
629 }
630 adapter := &extToolAdapter{mgr: extMgr}
631 if extMgr != nil {
632 _ = extMgr.Reload(ctx, 2*time.Second)
633 }
634 refreshAgentToolsAndPrompt(args, sharedSandbox, adapter, ag, nil)
635}
636
637// ---- interactive mode: opens the TUI even without credentials ----
638
639func runInteractive(ctx context.Context, args Args, version string) error {
640 // Resolve WITHOUT requiring credentials.
641 r, err := Resolve(args, false)
642 if err != nil {
643 return err
644 }
645
646 authStore := AuthStoreFor()
647 mgr := auth.NewManager(authStore)
648 defer mgr.Close()
649
650 // Keep the sandbox pointer stable across agent rebuilds (login / model
651 // switch). The Interactive UI toggles the lock via this pointer, and
652 // rebuilt tool instances must share the same one so the lock sticks.
653 sharedSandbox := r.Sandbox
654
655 // Build the extension manager BEFORE the agent so we can fold
656 // extension-defined tools into the registry. Forward-declare iv so
657 // the host hooks adapter can dereference it after construction.
658 var iv *modes.Interactive
659 extHooks := &interactiveExtHooks{ivPtr: &iv}
660 extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
661 var startupExtensionErrors []string
662 // --ext paths first so they win against installed extensions of
663 // the same name (loadOne's first-write-wins semantics).
664 for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
665 startupExtensionErrors = append(startupExtensionErrors, e.Error())
666 }
667 // --no-ext skips the global + project-local discovery scan;
668 // explicit --ext paths above are still honoured so you can run
669 // "only this extension" with --no-ext --ext ./x.
670 if !args.NoExt {
671 for _, e := range extMgr.Discover(ctx) {
672 startupExtensionErrors = append(startupExtensionErrors, e.Error())
673 }
674 }
675 // Wait briefly for extensions to flush their initial register_tool
676 // frames before we build the agent's tool registry. Half a second
677 // is plenty for any extension that's actually well-behaved; ones
678 // that don't send a ready frame eat the full grace and proceed.
679 // 3s is the per-extension grace period for the ready frame.
680 // Native binaries are instant; runtimes like `npx tsx` take ~1.5s
681 // from cold cache. The wait is tight only for extensions that
682 // haven't sent ready by then; ones that signalled earlier release
683 // the wait immediately.
684 extMgr.WaitForReady(3 * time.Second)
685 defer extMgr.Stop(2 * time.Second)
686
687 extToolAdapter := &extToolAdapter{mgr: extMgr}
688 r.MergeExtensionTools(extToolAdapter)
689
690 // Build the swarm supervisor BEFORE the agent so the auto-swarm
691 // tool can reference it during tool-registry construction. State
692 // lives under ZotHome/swarm so per-agent meta/events survive
693 // restarts; the user can hunt orphaned agents down with
694 // `git worktree list` if anything misbehaves.
695 //
696 // swarmMgr is also captured by loadSession / changeCWD closures
697 // further down the function, which is why we keep the variable
698 // in this outer scope rather than scoping it tighter.
699 var swarmMgr *swarm.Swarm
700 swarmMgr = swarm.New(swarm.Config{
701 Root: filepath.Join(ZotHome(), "swarm"),
702 RepoRoot: r.CWD,
703 ResolveCredential: func(ctx context.Context, providerID string) (swarm.Credential, error) {
704 if providerID == "ollama" {
705 return swarm.Credential{Value: "ollama", Method: "apikey"}, nil
706 }
707 credential, method, accountID, err := ResolveCredentialFullContext(ctx, providerID, "")
708 if err != nil {
709 // Providers backed only by a local endpoint do not need a key.
710 // Leave stdin untouched and let the child resolve that endpoint.
711 if !CredentialAvailable(providerID) {
712 return swarm.Credential{}, nil
713 }
714 return swarm.Credential{}, err
715 }
716 return swarm.Credential{Value: credential, Method: method, AccountID: accountID}, nil
717 },
718 })
719 // Pull any previously-spawned agents off disk so the dashboard
720 // shows them as detached and the user can resume / remove them.
721 _, _ = swarmMgr.Reload()
722
723 // onSpawnedSwarm is the OnSpawned callback the swarm_spawn tool
724 // fires after every successful spawn. It hands the agent off to
725 // the running Interactive so the watcher can flush a summary back
726 // into chat when all sub-agents finish. Reads `iv` lazily because
727 // the Interactive is constructed after the agent.
728 onSpawnedSwarm := func(a *swarm.Agent, task string) {
729 if iv != nil {
730 iv.TrackSwarmAgent(a, task)
731 }
732 }
733
734 // Inject the swarm_spawn auto-swarm tool only when /settings ->
735 // auto-swarm is currently enabled. Registering it unconditionally
736 // leaves the model trying to call it (and getting a polite error)
737 // even when the user has switched the feature off. The /settings
738 // toggle live-mutates the running agent's registry separately so
739 // flipping the flag mid-session takes effect on the next turn.
740 injectSwarmSpawn := func(reg core.Registry) core.Registry {
741 if reg == nil {
742 return reg
743 }
744 if !AutoSwarmEnabled() {
745 return reg
746 }
747 reg["swarm_spawn"] = &tools.SwarmSpawnTool{
748 Swarm: swarmMgr,
749 Enabled: AutoSwarmEnabled,
750 DefaultModel: func() string { return r.Model },
751 DefaultProvider: func() string { return r.Provider },
752 OnSpawned: onSpawnedSwarm,
753 }
754 return reg
755 }
756 injectSwarmSpawn(r.ToolRegistry)
757
758 // Confirmation gate: when --no-yolo is on, the agent must ask
759 // the user before every tool call. In interactive mode the TUI
760 // provides the Confirmer; in print/json/rpc modes there's no
761 // way to prompt, so the gate is constructed with a nil inner
762 // which auto-refuses every call with a helpful reason.
763 var confirmGate *core.ConfirmGate
764 if args.NoYolo {
765 confirmGate = core.NewConfirmGate(nil) // set below for interactive
766 }
767
768 // Capture current args in a closure so BuildAgent can re-resolve
769 // after a successful login (picks up the newly stored credential).
770 wireAgentExt := func(a *core.Agent) *core.Agent {
771 if a == nil {
772 return a
773 }
774 a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
775 // Guards run before confirmation because they may rewrite the
776 // arguments. The user must approve the effective call that will
777 // actually execute, not the model's original arguments.
778 r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
779 if r.Block {
780 return false, r.Reason, nil
781 }
782 effectiveArgs := call.Arguments
783 if len(r.ModifiedArgs) > 0 && json.Valid(r.ModifiedArgs) {
784 effectiveArgs = r.ModifiedArgs
785 }
786 if confirmGate != nil {
787 var content strings.Builder
788 if tool, err := a.Tools.Get(call.Name); err == nil {
789 if previewer, ok := tool.(core.ToolPreviewer); ok {
790 preview, err := previewer.Preview(ctx, effectiveArgs)
791 if err != nil {
792 return false, err.Error(), nil
793 }
794 for _, block := range preview.Content {
795 if text, ok := block.(provider.TextBlock); ok {
796 if content.Len() > 0 {
797 content.WriteString("\n")
798 }
799 content.WriteString(text.Text)
800 }
801 }
802 }
803 }
804 ok, reason, _ := confirmGate.CheckToolCall(core.ToolCallConfirmation{
805 ID: call.ID,
806 Name: call.Name,
807 Summary: core.BuildPreview(effectiveArgs, 120),
808 Content: content.String(),
809 })
810 if !ok {
811 return false, reason, nil
812 }
813 }
814 return true, "", r.ModifiedArgs
815 }
816 a.BeforeTurn = func(step int) (bool, string) {
817 r := extMgr.InterceptTurnStart(ctx, step)
818 return !r.Block, r.Reason
819 }
820 a.BeforeAssistantMessage = func(text string) (bool, string, string) {
821 r := extMgr.InterceptAssistantMessage(ctx, text)
822 if r.Block {
823 return false, r.Reason, ""
824 }
825 return true, "", r.ReplaceText
826 }
827 a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
828 return a
829 }
830
831 buildAgent := func() (*core.Agent, string, string, error) {
832 resolved, err := Resolve(args, true)
833 if err != nil {
834 return nil, "", "", err
835 }
836 resolved.UseSandbox(sharedSandbox)
837 resolved.MergeExtensionTools(extToolAdapter)
838 injectSwarmSpawn(resolved.ToolRegistry)
839 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
840 }
841
842 // Rebuild agent with an explicit provider/model override.
843 buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
844 next := args
845 if providerOverride != "" {
846 next.Provider = providerOverride
847 }
848 if modelOverride != "" {
849 next.Model = modelOverride
850 }
851 resolved, err := Resolve(next, true)
852 if err != nil {
853 return nil, "", "", err
854 }
855 resolved.UseSandbox(sharedSandbox)
856 resolved.MergeExtensionTools(extToolAdapter)
857 injectSwarmSpawn(resolved.ToolRegistry)
858 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
859 }
860
861 // Rebuild agent for the rescue picker after a recoverable failure.
862 // Unlike buildAgentFor, this drops launch-time --api-key and
863 // --base-url overrides because those are typically the cause of the
864 // rescue (a bad key, a typo'd base URL, or a corporate gateway that
865 // only the originally-picked provider needed). Re-resolving without
866 // them lets the rescue retry use env vars / auth.json / provider
867 // defaults the way zot would have without the overrides.
868 buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
869 next := args
870 next.APIKey = ""
871 next.BaseURL = ""
872 if providerOverride != "" {
873 next.Provider = providerOverride
874 }
875 if modelOverride != "" {
876 next.Model = modelOverride
877 }
878 resolved, err := Resolve(next, true)
879 if err != nil {
880 return nil, "", "", err
881 }
882 resolved.UseSandbox(sharedSandbox)
883 resolved.MergeExtensionTools(extToolAdapter)
884 injectSwarmSpawn(resolved.ToolRegistry)
885 return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
886 }
887
888 var ag *core.Agent
889 if r.HasCredential() {
890 ag = wireAgentExt(r.NewAgent())
891 }
892
893 // /reload-ext callback: after the manager has respawned every
894 // extension, re-resolve the tool registry (built-ins + freshly-
895 // registered extension tools) and swap it onto the current
896 // agent in-place. The current agent may have been replaced by a
897 // /model swap since spawn, so re-read the live `ag` on each
898 // invocation.
899 extMgr.SetOnReload(func() {
900 current := liveInteractiveAgent(iv, ag)
901 if current == nil {
902 return
903 }
904 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
905 })
906
907 // Fire session_start once we know the manager's running.
908 extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
909
910 var sess *core.Session
911 var sessBaselineMsgs int // messages already on disk when current session opened
912 // persistMu guards sess + sessBaselineMsgs against concurrent access
913 // from the agent loop's per-message persistence hook (runs on the
914 // agent goroutine) and the TUI's session swap / flush callbacks
915 // (run on the TUI goroutine). Without this, a /sessions swap that
916 // races with a finishing turn could double-write or lose messages.
917 var persistMu sync.Mutex
918 if !args.NoSess && ag != nil {
919 sess, _ = openOrCreateSession(args, r, ag, version)
920 if ag != nil {
921 sessBaselineMsgs = len(ag.Messages())
922 }
923 }
924 defer func() {
925 persistMu.Lock()
926 defer persistMu.Unlock()
927 if sess != nil {
928 sess.Close()
929 }
930 }()
931
932 // persistMessage is the per-message hook bound to the agent. It
933 // appends each new transcript message to the live session as soon
934 // as it lands, so a kill / closed terminal / OS crash costs at
935 // most the in-flight turn instead of the whole session. The
936 // baseline counter advances in lock-step so the exit-time flush
937 // doesn't double-write rows already on disk.
938 persistMessage := func(m provider.Message) {
939 persistMu.Lock()
940 defer persistMu.Unlock()
941 if sess == nil {
942 return
943 }
944 if err := sess.AppendMessage(m); err == nil {
945 sessBaselineMsgs++
946 }
947 }
948 persistUsage := func(cum provider.Usage) {
949 persistMu.Lock()
950 defer persistMu.Unlock()
951 if sess == nil {
952 return
953 }
954 _ = sess.AppendUsage(cum, cum)
955 }
956 persistCompaction := func(messages []provider.Message) {
957 persistMu.Lock()
958 defer persistMu.Unlock()
959 if sess == nil {
960 return
961 }
962 if err := sess.AppendCompaction(messages); err == nil {
963 sessBaselineMsgs = len(messages)
964 }
965 }
966 wireAgentPersist := func(a *core.Agent) *core.Agent {
967 if a == nil {
968 return a
969 }
970 a.OnMessageAppended = persistMessage
971 a.OnUsage = persistUsage
972 a.OnTranscriptCompacted = persistCompaction
973 return a
974 }
975 wireAgentPersist(ag)
976
977 // Re-wrap the build closures so any agent constructed by the TUI
978 // (login, /model swap to a different provider) also gets the
979 // persistence hooks. Without this, switching provider would
980 // silently revert to the old in-memory-only behaviour.
981 bindLiveAgentSession := func(a *core.Agent) {
982 persistMu.Lock()
983 s := sess
984 persistMu.Unlock()
985 bindAgentSession(a, s)
986 }
987 baseBuildAgent := buildAgent
988 buildAgent = func() (*core.Agent, string, string, error) {
989 a, p, m, err := baseBuildAgent()
990 a = wireAgentPersist(a)
991 bindLiveAgentSession(a)
992 return a, p, m, err
993 }
994 baseBuildAgentFor := buildAgentFor
995 buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
996 a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
997 a = wireAgentPersist(a)
998 bindLiveAgentSession(a)
999 return a, p, m, err
1000 }
1001 baseBuildAgentForRescue := buildAgentForRescue
1002 buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1003 a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
1004 a = wireAgentPersist(a)
1005 bindLiveAgentSession(a)
1006 return a, p, m, err
1007 }
1008
1009 // loadSession replaces the current session with the one at path and
1010 // hands its messages to the agent. Used by the /sessions picker.
1011 loadSession := func(path string) error {
1012 currentAg := liveInteractiveAgent(iv, ag)
1013 if currentAg == nil {
1014 return fmt.Errorf("no agent running; log in first")
1015 }
1016 newSess, msgs, err := core.OpenSession(path)
1017 if err != nil {
1018 return err
1019 }
1020 fullMsgCount := len(msgs)
1021 msgs = trimMessagesForResume(msgs, 100)
1022 persistMu.Lock()
1023 // Flush any unsaved messages to the old session before swapping.
1024 // Per-message persistence keeps sessBaselineMsgs current, so
1025 // this is a defensive no-op in the common case; it still
1026 // matters for the rare race where a turn just finished and
1027 // hadn't fired its hook yet.
1028 if sess != nil {
1029 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1030 _ = sess.Close()
1031 }
1032 sess = newSess
1033 currentAg.SetMessages(msgs)
1034 bindAgentSession(currentAg, sess)
1035 if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
1036 currentAg.SeedCost(cum)
1037 currentAg.SeedLastTurnUsage(last)
1038 }
1039 // The live agent only receives a compact resume window, but
1040 // the session file remains intact. Keep the persistence
1041 // baseline at the original on-disk message count so future
1042 // turns append after the full session instead of duplicating
1043 // the hydrated tail.
1044 sessBaselineMsgs = fullMsgCount
1045 persistMu.Unlock()
1046 // Re-scope the swarm dashboard to the new session so /swarm
1047 // only shows agents this session spawned. swarmMgr may be nil
1048 // here if we haven't reached the construction site yet (it
1049 // shouldn't be, since the interactive loop is what triggers
1050 // loadSession, but the nil check is cheap insurance).
1051 if swarmMgr != nil && newSess != nil {
1052 swarmMgr.SetActiveSession(newSess.ID)
1053 }
1054 return nil
1055 }
1056
1057 // changeCWD switches the running session to a new working directory.
1058 // Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
1059 // /cd slash command (which itself is only fired by the workspaces
1060 // extension's panel-key Enter handler today; the user can type /cd
1061 // directly but it's not in autocomplete / help / the README).
1062 //
1063 // Steps, in order:
1064 // 1. resolve + validate the new path (~ expansion, abs/rel)
1065 // 2. close the current session, flushing pending messages
1066 // 3. mutate captured args.CWD + r.CWD so future buildAgent
1067 // calls bind to the new cwd
1068 // 4. re-root the shared sandbox («·«) so /jail follows the
1069 // session into the new cwd instead of widening or silently
1070 // dropping
1071 // 5. rebuild the agent via buildAgent() so tools, AGENTS.md
1072 // addendum, system prompt, sessions dir all bind correctly
1073 // 6. open a fresh session in the new cwd's bucket
1074 // 7. push the new state into the running Interactive
1075 // 8. re-scope the swarm dashboard to the freshly-opened session
1076 //
1077 // The /jail state is preserved verbatim: if the sandbox was locked
1078 // to the old cwd, it stays locked, just re-pointed at the new one.
1079 changeCWD := func(path string) error {
1080 if path == "" {
1081 return fmt.Errorf("empty path")
1082 }
1083 // ~ expansion.
1084 if path == "~" || strings.HasPrefix(path, "~/") {
1085 home, herr := os.UserHomeDir()
1086 if herr != nil || home == "" {
1087 return fmt.Errorf("cannot expand ~: %v", herr)
1088 }
1089 if path == "~" {
1090 path = home
1091 } else {
1092 path = filepath.Join(home, path[2:])
1093 }
1094 }
1095 if !filepath.IsAbs(path) {
1096 path = filepath.Join(args.CWD, path)
1097 }
1098 absPath, err := filepath.Abs(path)
1099 if err != nil {
1100 return err
1101 }
1102 info, err := os.Stat(absPath)
1103 if err != nil {
1104 return err
1105 }
1106 if !info.IsDir() {
1107 return fmt.Errorf("not a directory: %s", absPath)
1108 }
1109
1110 currentAg := ag
1111 if currentAg == nil {
1112 return fmt.Errorf("no agent running; log in first")
1113 }
1114
1115 // Close the current session before we drop the reference.
1116 // Per-message persistence keeps it current already; this is
1117 // a defensive flush + final fsync via Close.
1118 persistMu.Lock()
1119 if sess != nil {
1120 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1121 _ = sess.Close()
1122 sess = nil
1123 }
1124 sessBaselineMsgs = 0
1125 persistMu.Unlock()
1126
1127 // Mutate captured state so subsequent agent rebuilds and
1128 // session opens see the new cwd.
1129 wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
1130 args.CWD = absPath
1131 r.CWD = absPath
1132 if args.PermissionSet != nil {
1133 expanded := args.PermissionSet.Expand(absPath, args.AgentDataDir)
1134 args.PermissionSet = &expanded
1135 }
1136 if sharedSandbox != nil {
1137 sharedSandbox.Root = absPath
1138 if wasJailed {
1139 sharedSandbox.Lock()
1140 } else {
1141 sharedSandbox.Unlock()
1142 }
1143 }
1144
1145 // Rebuild the agent so tools / AGENTS.md / system prompt
1146 // re-bind to the new cwd. buildAgent() reads from args + r.
1147 newAg, newProvider, newModel, berr := buildAgent()
1148 if berr != nil {
1149 return fmt.Errorf("rebuild agent: %v", berr)
1150 }
1151 ag = newAg
1152
1153 // Fresh session in the new cwd's bucket. We bypass
1154 // openOrCreateSession's --continue / --resume branches
1155 // because /cd's semantics are "start fresh here", matching
1156 // what relaunching `zot --cwd <path>` would do today.
1157 if !args.NoSess {
1158 newRoot := agentSessionsRoot(ZotHome(), args)
1159 core.PruneEmptySessions(newRoot, absPath)
1160 newSess, serr := core.NewSession(newRoot, absPath, newProvider, newModel, version)
1161 if serr != nil {
1162 return fmt.Errorf("open session in %s: %v", absPath, serr)
1163 }
1164 persistMu.Lock()
1165 sess = newSess
1166 sessBaselineMsgs = 0
1167 persistMu.Unlock()
1168 bindAgentSession(newAg, newSess)
1169 }
1170
1171 // Push the new state into the running Interactive.
1172 if iv != nil {
1173 startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZotHome()))
1174 iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
1175 }
1176
1177 // Re-scope the swarm dashboard to the new session.
1178 if swarmMgr != nil && sess != nil {
1179 swarmMgr.SetActiveSession(sess.ID)
1180 }
1181 return nil
1182 }
1183
1184 term := tui.NewProcTerm()
1185
1186 // Kick off the async update check so the banner can appear when the
1187 // http response eventually arrives (usually <1s on cached DNS). Map
1188 // agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
1189 updateCh := make(chan modes.UpdateInfo, 1)
1190 go func() {
1191 defer close(updateCh)
1192 src := <-CheckForUpdateAsync(ZotHome(), version)
1193 updateCh <- modes.UpdateInfo{
1194 Current: src.Current,
1195 Latest: src.Latest,
1196 Available: src.Available,
1197 URL: src.URL,
1198 }
1199 }()
1200
1201 // Changelog: when the running version differs from the last
1202 // version whose release notes the user dismissed, fetch the
1203 // release body from GitHub and have the TUI show it once. On
1204 // first-ever launch (no prior LastChangelogShown), seed the
1205 // stored version silently — don't dump release notes at someone
1206 // who just installed.
1207 changelogCh := make(chan modes.ChangelogPayload, 1)
1208 go func() {
1209 defer close(changelogCh)
1210 cfg, _ := LoadConfig()
1211 if cfg.LastChangelogShown == "" {
1212 SeedChangelogVersion(version)
1213 return
1214 }
1215 if !ShouldShowChangelog(version, cfg) {
1216 return
1217 }
1218 info := <-FetchChangelogAsync(version)
1219 if info.Body == "" {
1220 return
1221 }
1222 // For dev builds (0.0.0), skip if the latest release was
1223 // already shown (stored by the dismiss callback).
1224 if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
1225 return
1226 }
1227 changelogCh <- modes.ChangelogPayload{
1228 Version: info.Version,
1229 Body: info.Body,
1230 URL: info.URL,
1231 }
1232 }()
1233
1234 initialCfg, _ := LoadConfig()
1235 quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
1236 for idx, s := range initialCfg.QuickModelShortcuts {
1237 quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
1238 }
1239 theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
1240 if themeErr != nil {
1241 fmt.Fprintln(os.Stderr, "theme load:", themeErr)
1242 if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
1243 initialCfg.Theme = ""
1244 _ = SaveConfig(initialCfg)
1245 }
1246 }
1247
1248 // swarmMgr was constructed and reloaded earlier (before the agent
1249 // build, so the auto-swarm tool could capture it). Here we just
1250 // scope the dashboard to the active host session so /swarm only
1251 // shows agents this session spawned (and any pre-upgrade unscoped
1252 // agents — see SnapshotAll docs). Updated again whenever the
1253 // user swaps sessions via loadSession below.
1254 if sess != nil {
1255 swarmMgr.SetActiveSession(sess.ID)
1256 }
1257 // Best-effort shutdown on interactive exit: stop all running
1258 // agents so they don't outlive their parent zot.
1259 defer swarmMgr.StopAll()
1260
1261 var startupSkills []*skills.Skill
1262 if r.SkillTool != nil {
1263 startupSkills = r.SkillTool.Skills()
1264 }
1265
1266 iv = modes.NewInteractive(modes.InteractiveConfig{
1267 Terminal: term,
1268 Theme: theme,
1269 InlineImagesEnabled: initialCfg.InlineImagesEnabled,
1270 AutoSwarmEnabled: initialCfg.AutoSwarmEnabled,
1271 AutoCompactThreshold: initialCfg.AutoCompactThreshold,
1272 JailByDefault: initialCfg.JailByDefault,
1273 OpenRouterServerToolsEnabled: initialCfg.OpenRouterServerToolsEnabled,
1274 NoTools: args.NoTools,
1275 QuickModelShortcuts: quickModelShortcuts,
1276 RecursiveFileSuggest: initialCfg.RecursiveFileSuggest,
1277 RespectGitignore: initialCfg.RespectGitignore,
1278 CompactMode: initialCfg.CompactMode,
1279 TUIInputStyle: initialCfg.TUIInputStyle,
1280 TUIStatusPosition: initialCfg.TUIStatusPosition,
1281 TUIWorkingPosition: initialCfg.TUIWorkingPosition,
1282 ThemeName: initialCfg.Theme,
1283 FlatTools: initialCfg.FlatToolRender(),
1284 CompactUser: initialCfg.CompactUserInput(),
1285 ExtensionThemes: extMgr.ThemeOptions,
1286 AutoSwarmSystemAddendum: AutoSwarmSystemAddendum,
1287 SettingsStore: configSettingsStore{},
1288 Model: r.Model,
1289 Provider: r.Provider,
1290 AuthMethod: r.AuthMethod,
1291 BaseURL: r.BaseURL,
1292 Reasoning: r.Reasoning,
1293 SystemPrompt: r.SystemPrompt,
1294 Tools: r.ToolRegistry,
1295 MaxSteps: r.MaxSteps,
1296 CWD: r.CWD,
1297 StartupAgentName: args.AgentName,
1298 StartupContextPaths: instructionContextPaths(r.ContextFiles),
1299 StartupExtensionNames: startupExtensionNames(extMgr.All()),
1300 StartupExtensionErrors: startupExtensionErrors,
1301 StartupSkillNames: startupSkillNames(startupSkills),
1302 ShowInstructionsAtStartup: initialCfg.ShowInstructionsAtStartup,
1303 ZotHome: ZotHome(),
1304 SessionsRoot: agentSessionsRoot(ZotHome(), args),
1305 Version: version,
1306 UpdateInfoChan: updateCh,
1307 Sandbox: sharedSandbox,
1308 Agent: ag,
1309 InitialInput: args.Prompt,
1310 StartupPre: args.StartupPre,
1311 OnStartupPreDone: func() {
1312 // entry.pre often installs skills/extensions; rediscover them
1313 // before the user starts a model turn.
1314 current := liveInteractiveAgent(iv, ag)
1315 if extMgr != nil {
1316 _ = extMgr.Reload(context.Background(), 2*time.Second)
1317 }
1318 if current != nil {
1319 refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
1320 }
1321 },
1322 AuthManager: mgr,
1323 LlamaCPPConfig: ResolveLlamaCPPConfig,
1324 RefreshLlamaCPPModels: RefreshLlamaCPPModels,
1325 BuildAgent: buildAgent,
1326 SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
1327 BuildAgentFor: buildAgentFor,
1328 BuildAgentForRescue: buildAgentForRescue,
1329 LoggedInProviders: func() []string {
1330 var out []string
1331 seen := map[string]bool{}
1332 for _, p := range knownProviders {
1333 if CredentialAvailable(p) && !seen[p] {
1334 out = append(out, p)
1335 seen[p] = true
1336 }
1337 }
1338 // Include custom providers that have credentials stored.
1339 for p := range provider.CustomProviders() {
1340 if CredentialAvailable(p) && !seen[p] {
1341 out = append(out, p)
1342 seen[p] = true
1343 }
1344 }
1345 // Ollama models are always available (no auth needed).
1346 if !seen["ollama"] {
1347 out = append(out, "ollama")
1348 }
1349 return out
1350 },
1351 LoadSession: loadSession,
1352 ChangeCWD: changeCWD,
1353 CurrentSessionPath: func() string {
1354 if sess == nil {
1355 return ""
1356 }
1357 return sess.Path
1358 },
1359 FlushSession: func() {
1360 // Append any not-yet-persisted agent messages to the
1361 // current session file, then advance the baseline so
1362 // the final WriteNewTranscript at exit doesn't write
1363 // duplicates. Per-message persistence keeps the on-
1364 // disk file current already, so this is mostly a
1365 // defensive flush — still needed for /session export
1366 // to guarantee the exported bytes include the very
1367 // last in-flight turn.
1368 currentAg := iv.Agent()
1369 if currentAg == nil {
1370 return
1371 }
1372 persistMu.Lock()
1373 defer persistMu.Unlock()
1374 if sess == nil {
1375 return
1376 }
1377 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1378 sessBaselineMsgs = len(currentAg.Messages())
1379 },
1380 Extensions: extMgr,
1381 Swarm: swarmMgr,
1382 ChangelogChan: changelogCh,
1383 OnChangelogDismiss: func() {
1384 // For dev builds (0.0.0) store the actual release version
1385 // so the same changelog doesn't show again next launch.
1386 // For real builds, store the binary version.
1387 v := version
1388 if v == "0.0.0" {
1389 if iv != nil && iv.ChangelogVersion() != "" {
1390 v = iv.ChangelogVersion()
1391 }
1392 }
1393 _ = MarkChangelogShown(v)
1394 },
1395 SkillSnapshot: func() []*skills.Skill {
1396 if args.NoSkill {
1397 // --no-skill: nothing for the picker to show.
1398 return nil
1399 }
1400 // Re-discover so the picker reflects edits made during
1401 // the session. Cheap; SKILL.md files are small. Filter
1402 // out built-in skills — they're hidden from user-facing
1403 // surfaces because they're implementation detail; the
1404 // model still sees them through the system-prompt
1405 // manifest and the skill tool.
1406 userHome, _ := os.UserHomeDir()
1407 list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
1408 return skills.VisibleSkills(list)
1409 },
1410 NoYolo: args.NoYolo,
1411 ConfirmGate: confirmGate,
1412 PersistModel: func(providerName, model string) {
1413 // Update config.json so next launch uses the same pick.
1414 cfg, _ := LoadConfig()
1415 cfg.Provider = providerName
1416 cfg.Model = model
1417 _ = SaveConfig(cfg)
1418 // Update the active session's meta so resume picks this up.
1419 if sess != nil {
1420 _ = sess.UpdateModel(providerName, model)
1421 }
1422 },
1423 })
1424
1425 // Bind the interactive TUI as the Confirmer. We deferred this
1426 // until now because the gate is constructed before the TUI
1427 // (the BeforeToolExecute closure captures it). SetConfirmer
1428 // is mutex-guarded on the gate so this is safe.
1429 if confirmGate != nil {
1430 confirmGate.SetConfirmer(&confirmationEventConfirmer{
1431 inner: iv,
1432 emit: extMgr.EmitEvent,
1433 })
1434 }
1435
1436 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1437 // (closed terminal window, system shutdown, kill) used to lose
1438 // the entire in-memory transcript because the deferred post-Run
1439 // flush below never ran. Per-message persistence above covers
1440 // most of it; this handler writes any in-flight remainder and
1441 // then exits the process so we don't double-paint over a
1442 // broken terminal that the TUI's restore deferreds can no
1443 // longer fix from a signal context.
1444 //
1445 // SIGINT is intentionally NOT handled here — the TUI consumes
1446 // Ctrl+C as a regular key event for cancel/clear semantics, and
1447 // installing a SIGINT notifier here would swallow it.
1448 sigCh := make(chan os.Signal, 1)
1449 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1450 defer signal.Stop(sigCh)
1451 go func() {
1452 _, ok := <-sigCh
1453 if !ok {
1454 return
1455 }
1456 if finalAg := iv.Agent(); finalAg != nil {
1457 persistMu.Lock()
1458 if sess != nil {
1459 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1460 sessBaselineMsgs = len(finalAg.Messages())
1461 _ = sess.Close()
1462 sess = nil
1463 }
1464 persistMu.Unlock()
1465 }
1466 // Exit cleanly. Re-raising the signal would skip os.Exit's
1467 // at-exit hooks; explicit exit is fine because we've already
1468 // flushed the only at-risk state (the session file).
1469 os.Exit(0)
1470 }()
1471
1472 runErr := iv.Run(ctx)
1473
1474 // Flush final transcript to session (only if we had / ended up with an agent).
1475 if finalAg := iv.Agent(); finalAg != nil {
1476 persistMu.Lock()
1477 if sess != nil {
1478 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1479 sessBaselineMsgs = len(finalAg.Messages())
1480 }
1481 persistMu.Unlock()
1482 }
1483 return runErr
1484}
1485
1486func agentSessionsRoot(root string, args Args) string {
1487 if args.AgentName == "" {
1488 return root
1489 }
1490 return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
1491}
1492
1493// openOrCreateSession returns a session for the run. sess may be nil
1494// with a nil error if session persistence is disabled. When a session
1495// exists, its id is bound onto ag so providers can sticky-route.
1496func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1497 if args.NoSess {
1498 return nil, nil
1499 }
1500 // Sweep meta-only files left over from older zot versions (and from
1501 // any session that crashed before its first AppendMessage). Cheap;
1502 // reads the first few bytes of each file in the cwd's session dir.
1503 sessionsRoot := agentSessionsRoot(ZotHome(), args)
1504 core.PruneEmptySessions(sessionsRoot, args.CWD)
1505 var (
1506 s *core.Session
1507 msgs []provider.Message
1508 err error
1509 )
1510 switch {
1511 case args.Session != "":
1512 s, msgs, err = core.OpenSession(args.Session)
1513 // The swarm-agent child passes a fixed --session path that
1514 // may not exist yet on first Spawn. Treat ENOENT as "create
1515 // a fresh session AT THIS PATH" so the conversation actually
1516 // gets persisted; without this fallback the swarm child runs
1517 // with sess==nil and every Resume re-starts with no memory
1518 // of the prior turns. Other openers (--continue / --resume /
1519 // the picker) never see ENOENT here because they only choose
1520 // paths that already exist on disk.
1521 if err != nil && errors.Is(err, os.ErrNotExist) {
1522 s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1523 msgs = nil
1524 }
1525 case args.Continue:
1526 latest := core.LatestSession(sessionsRoot, args.CWD)
1527 if latest != "" {
1528 s, msgs, err = core.OpenSession(latest)
1529 }
1530 case args.Resume:
1531 picked, perr := pickSession(sessionsRoot, args.CWD)
1532 if perr != nil {
1533 return nil, perr
1534 }
1535 if picked != "" {
1536 s, msgs, err = core.OpenSession(picked)
1537 }
1538 }
1539 if err != nil {
1540 return nil, err
1541 }
1542 if s == nil {
1543 s, err = core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1544 if err != nil {
1545 return nil, err
1546 }
1547 } else {
1548 ag.SetMessages(msgs)
1549 if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1550 ag.SeedCost(cum)
1551 ag.SeedLastTurnUsage(last)
1552 }
1553 }
1554 bindAgentSession(ag, s)
1555 return s, nil
1556}
1557
1558func pickSession(root, cwd string) (string, error) {
1559 files := core.ListSessions(root, cwd)
1560 if len(files) == 0 {
1561 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1562 return "", nil
1563 }
1564 for i, f := range files {
1565 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
1566 }
1567 fmt.Fprint(os.Stderr, "pick #: ")
1568 rd := bufio.NewReader(os.Stdin)
1569 line, _ := rd.ReadString('\n')
1570 line = strings.TrimSpace(line)
1571 var n int
1572 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1573 return "", fmt.Errorf("invalid selection")
1574 }
1575 return files[n-1], nil
1576}
1577
1578// WriteNewTranscript appends only messages after index `from` from the
1579// agent's transcript to the session. Used by callers that don't hold
1580// the persistMu (non-interactive print/json modes which run a single
1581// turn under their own goroutine).
1582func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1583 writeNewTranscriptLocked(ag, sess, from)
1584}
1585
1586// bindAgentSession stamps the zot session id onto the agent so providers
1587// that support sticky routing (OpenRouter session_id) can reuse it.
1588// No-op when persistence is disabled.
1589func bindAgentSession(ag *core.Agent, sess *core.Session) {
1590 if ag == nil || sess == nil {
1591 return
1592 }
1593 ag.SessionID = sess.ID
1594}
1595
1596// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1597// suffix marks that interactive callers must hold persistMu when
1598// invoking it so concurrent appends from the agent loop don't race
1599// with this catch-up flush.
1600func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1601 if sess == nil || ag == nil {
1602 return
1603 }
1604 msgs := ag.Messages()
1605 for i := from; i < len(msgs); i++ {
1606 _ = sess.AppendMessage(msgs[i])
1607 }
1608 cum := ag.Cost()
1609 _ = sess.AppendUsage(cum, cum)
1610}
1611
1612func argsForStdin(rawArgs []string, mode os.FileMode) []string {
1613 if mode&os.ModeCharDevice != 0 {
1614 return rawArgs
1615 }
1616 return append([]string{"--print"}, rawArgs...)
1617}
1618
1619func combinePromptInput(stdin, positional string) string {
1620 parts := make([]string, 0, 2)
1621 if stdin = strings.TrimSpace(stdin); stdin != "" {
1622 parts = append(parts, stdin)
1623 }
1624 if positional = strings.TrimSpace(positional); positional != "" {
1625 parts = append(parts, positional)
1626 }
1627 return strings.Join(parts, "\n")
1628}
1629
1630func readAllStdin() (string, error) {
1631 fi, err := os.Stdin.Stat()
1632 if err != nil {
1633 return "", err
1634 }
1635 if (fi.Mode() & os.ModeCharDevice) != 0 {
1636 return "", nil
1637 }
1638 b, err := io.ReadAll(os.Stdin)
1639 return string(b), err
1640}
1641
1642func printModels() {
1643 models := provider.Active()
1644
1645 // Compute column widths from actual data so wide providers (e.g.
1646 // xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1647 // `name` column off-screen. Floors mirror the historical layout so
1648 // short catalogs look the same as before.
1649 provW, idW, srcW := len("provider"), len("model id"), len("source")
1650 for _, m := range models {
1651 if w := len(m.Provider); w > provW {
1652 provW = w
1653 }
1654 if w := len(m.ID); w > idW {
1655 idW = w
1656 }
1657 source := m.Source
1658 if source == "" {
1659 source = "catalog"
1660 }
1661 if m.Speculative {
1662 source = "speculative"
1663 }
1664 if w := len(source); w > srcW {
1665 srcW = w
1666 }
1667 }
1668
1669 header := fmt.Sprintf("%-*s %-*s %8s %8s %s %-*s %s",
1670 provW, "provider",
1671 idW, "model id",
1672 "context", "max-out", "reasoning",
1673 srcW, "source",
1674 "name")
1675 fmt.Println(header)
1676
1677 for _, m := range models {
1678 reason := " "
1679 if m.Reasoning {
1680 reason = "✓"
1681 }
1682 source := m.Source
1683 if source == "" {
1684 source = "catalog"
1685 }
1686 if m.Speculative {
1687 source = "speculative"
1688 }
1689 fmt.Printf("%-*s %-*s %8d %8d %s %-*s %s\n",
1690 provW, m.Provider,
1691 idW, m.ID,
1692 m.ContextWindow, m.MaxOutput,
1693 reason,
1694 srcW, source,
1695 m.DisplayName)
1696 }
1697}