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