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