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