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: func() []string {
1441 var out []string
1442 seen := map[string]bool{}
1443 for _, p := range knownProviders {
1444 if CredentialAvailable(p) && !seen[p] {
1445 out = append(out, p)
1446 seen[p] = true
1447 }
1448 }
1449 // Include custom providers that have credentials stored.
1450 for p := range provider.CustomProviders() {
1451 if CredentialAvailable(p) && !seen[p] {
1452 out = append(out, p)
1453 seen[p] = true
1454 }
1455 }
1456 // Ollama models are always available (no auth needed).
1457 if !seen["ollama"] {
1458 out = append(out, "ollama")
1459 }
1460 return out
1461 },
1462 NewSession: newSession,
1463 LoadSession: loadSession,
1464 ChangeCWD: changeCWD,
1465 CurrentSessionPath: func() string {
1466 if sess == nil {
1467 return ""
1468 }
1469 return sess.Path
1470 },
1471 FlushSession: func() {
1472 // Append any not-yet-persisted agent messages to the
1473 // current session file, then advance the baseline so
1474 // the final WriteNewTranscript at exit doesn't write
1475 // duplicates. Per-message persistence keeps the on-
1476 // disk file current already, so this is mostly a
1477 // defensive flush — still needed for /session export
1478 // to guarantee the exported bytes include the very
1479 // last in-flight turn.
1480 currentAg := iv.Agent()
1481 if currentAg == nil {
1482 return
1483 }
1484 persistMu.Lock()
1485 defer persistMu.Unlock()
1486 if sess == nil {
1487 return
1488 }
1489 writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1490 sessBaselineMsgs = len(currentAg.Messages())
1491 },
1492 Extensions: extMgr,
1493 Swarm: swarmMgr,
1494 ChangelogChan: changelogCh,
1495 OnChangelogDismiss: func() {
1496 // For dev builds (0.0.0) store the actual release version
1497 // so the same changelog doesn't show again next launch.
1498 // For real builds, store the binary version.
1499 v := version
1500 if v == "0.0.0" {
1501 if iv != nil && iv.ChangelogVersion() != "" {
1502 v = iv.ChangelogVersion()
1503 }
1504 }
1505 _ = MarkChangelogShown(v)
1506 },
1507 PreloadPinnedSkills: freshSession && !args.NoSkill,
1508 LoadSkillPins: func(cwd string) (skills.Pins, error) {
1509 if args.NoSkill {
1510 return skills.Pins{}, nil
1511 }
1512 return loadSkillPins(cwd)
1513 },
1514 ToggleSkillPin: toggleSkillPin,
1515 SkillSnapshot: func() []*skills.Skill {
1516 return userSkillSnapshot(args)
1517 },
1518 NoYolo: args.NoYolo,
1519 ConfirmGate: confirmGate,
1520 OnReasoningChanged: func(level string) {
1521 r.Reasoning = level
1522 setZotSessionEnvironment(r, sess)
1523 },
1524 PersistModel: func(providerName, model string) {
1525 // Update config.json so next launch uses the same pick.
1526 cfg, _ := LoadConfig()
1527 cfg.Provider = providerName
1528 cfg.Model = model
1529 _ = SaveConfig(cfg)
1530 // Update the active session's meta so resume picks this up.
1531 if sess != nil {
1532 _ = sess.UpdateModel(providerName, model)
1533 }
1534 r.Provider = providerName
1535 r.Model = model
1536 setZotSessionEnvironment(r, sess)
1537 },
1538 })
1539
1540 extMgr.SetToolCaller(extensionToolCaller(extMgr, func() *core.Agent { return liveInteractiveAgent(iv, ag) }))
1541
1542 // Bind the interactive TUI as the Confirmer. We deferred this
1543 // until now because the gate is constructed before the TUI
1544 // (the BeforeToolExecute closure captures it). SetConfirmer
1545 // is mutex-guarded on the gate so this is safe.
1546 if confirmGate != nil {
1547 confirmGate.SetConfirmer(&confirmationEventConfirmer{
1548 inner: iv,
1549 emit: extMgr.EmitEvent,
1550 origin: extMgr.ToolCallOrigin,
1551 })
1552 }
1553
1554 // Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1555 // (closed terminal window, system shutdown, kill) used to lose
1556 // the entire in-memory transcript because the deferred post-Run
1557 // flush below never ran. Per-message persistence above covers
1558 // most of it; this handler writes any in-flight remainder and
1559 // then exits the process so we don't double-paint over a
1560 // broken terminal that the TUI's restore deferreds can no
1561 // longer fix from a signal context.
1562 //
1563 // SIGINT is intentionally NOT handled here — the TUI consumes
1564 // Ctrl+C as a regular key event for cancel/clear semantics, and
1565 // installing a SIGINT notifier here would swallow it.
1566 sigCh := make(chan os.Signal, 1)
1567 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1568 defer signal.Stop(sigCh)
1569 go func() {
1570 _, ok := <-sigCh
1571 if !ok {
1572 return
1573 }
1574 if finalAg := iv.Agent(); finalAg != nil {
1575 persistMu.Lock()
1576 if sess != nil {
1577 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1578 sessBaselineMsgs = len(finalAg.Messages())
1579 _ = sess.Close()
1580 sess = nil
1581 }
1582 persistMu.Unlock()
1583 }
1584 // Exit cleanly. Re-raising the signal would skip os.Exit's
1585 // at-exit hooks; explicit exit is fine because we've already
1586 // flushed the only at-risk state (the session file).
1587 os.Exit(0)
1588 }()
1589
1590 runErr := iv.Run(ctx)
1591
1592 // Flush final transcript to session (only if we had / ended up with an agent).
1593 if finalAg := iv.Agent(); finalAg != nil {
1594 persistMu.Lock()
1595 if sess != nil {
1596 writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1597 sessBaselineMsgs = len(finalAg.Messages())
1598 }
1599 persistMu.Unlock()
1600 }
1601 return runErr
1602}
1603
1604func agentSessionsRoot(root string, args Args) string {
1605 if args.AgentName == "" {
1606 return root
1607 }
1608 return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
1609}
1610
1611// openOrCreateSession returns a session for the run. sess may be nil
1612// with a nil error if session persistence is disabled. When a session
1613// exists, its id is bound onto ag so providers can sticky-route.
1614func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1615 s, _, err := openOrCreateSessionState(args, r, ag, version)
1616 return s, err
1617}
1618
1619// The freshness result distinguishes an empty resumed session from a new one.
1620func openOrCreateSessionState(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, bool, error) {
1621 fresh := true
1622 if args.NoSess {
1623 setZotSessionEnvironment(r, nil)
1624 return nil, fresh, nil
1625 }
1626 // Sweep meta-only files left over from older zot versions (and from
1627 // any session that crashed before its first AppendMessage). Cheap;
1628 // reads the first few bytes of each file in the cwd's session dir.
1629 sessionsRoot := agentSessionsRoot(ZotHome(), args)
1630 core.PruneEmptySessions(sessionsRoot, args.CWD)
1631 var (
1632 s *core.Session
1633 msgs []provider.Message
1634 err error
1635 )
1636 switch {
1637 case args.Session != "":
1638 s, msgs, err = core.OpenSession(args.Session)
1639 fresh = false
1640 // The swarm-agent child passes a fixed --session path that
1641 // may not exist yet on first Spawn. Treat ENOENT as "create
1642 // a fresh session AT THIS PATH" so the conversation actually
1643 // gets persisted; without this fallback the swarm child runs
1644 // with sess==nil and every Resume re-starts with no memory
1645 // of the prior turns. Other openers (--continue / --resume /
1646 // the picker) never see ENOENT here because they only choose
1647 // paths that already exist on disk.
1648 if err != nil && errors.Is(err, os.ErrNotExist) {
1649 s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1650 fresh = true
1651 msgs = nil
1652 }
1653 case args.Continue:
1654 latest := core.LatestSession(sessionsRoot, args.CWD)
1655 if latest != "" {
1656 s, msgs, err = core.OpenSession(latest)
1657 fresh = false
1658 }
1659 case args.Resume:
1660 picked, perr := pickSession(sessionsRoot, args.CWD)
1661 if perr != nil {
1662 return nil, false, perr
1663 }
1664 if picked != "" {
1665 s, msgs, err = core.OpenSession(picked)
1666 fresh = false
1667 }
1668 }
1669 if err != nil {
1670 return nil, false, err
1671 }
1672 if s == nil {
1673 s, err = core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1674 if err != nil {
1675 return nil, false, err
1676 }
1677 } else {
1678 ag.SetMessages(msgs)
1679 if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1680 ag.SeedCost(cum)
1681 ag.SeedLastTurnUsage(last)
1682 }
1683 }
1684 bindAgentSession(ag, s)
1685 setZotSessionEnvironment(r, s)
1686 return s, fresh, nil
1687}
1688
1689// setZotSessionEnvironment publishes the non-secret runtime metadata that
1690// zot's child processes can use for attribution and diagnostics.
1691func setZotSessionEnvironment(r Resolved, sess *core.Session) {
1692 values := map[string]string{
1693 "ZOT_PROVIDER": r.Provider,
1694 "ZOT_MODEL": r.Model,
1695 "ZOT_REASONING_LEVEL": r.Reasoning,
1696 }
1697 if sess != nil {
1698 values["ZOT_SESSION_ID"] = sess.ID
1699 values["ZOT_SESSION_FILE"] = sess.Path
1700 }
1701 for _, name := range []string{"ZOT_SESSION_ID", "ZOT_SESSION_FILE", "ZOT_PROVIDER", "ZOT_MODEL", "ZOT_REASONING_LEVEL"} {
1702 if value := values[name]; value != "" {
1703 _ = os.Setenv(name, value)
1704 } else {
1705 _ = os.Unsetenv(name)
1706 }
1707 }
1708}
1709
1710func pickSession(root, cwd string) (string, error) {
1711 files := core.ListSessions(root, cwd)
1712 if len(files) == 0 {
1713 fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1714 return "", nil
1715 }
1716 for i, f := range files {
1717 fmt.Fprintf(os.Stderr, " %2d) %s\n", i+1, f)
1718 }
1719 fmt.Fprint(os.Stderr, "pick #: ")
1720 rd := bufio.NewReader(os.Stdin)
1721 line, _ := rd.ReadString('\n')
1722 line = strings.TrimSpace(line)
1723 var n int
1724 if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1725 return "", fmt.Errorf("invalid selection")
1726 }
1727 return files[n-1], nil
1728}
1729
1730// rotateInteractiveSession creates the replacement before mutating the live
1731// agent, so a creation failure leaves the current conversation usable.
1732// Callers must hold the interactive persistence mutex.
1733func rotateInteractiveSession(root, cwd, providerName, model, version string, ag *core.Agent, old *core.Session, baseline int) (*core.Session, error) {
1734 if ag == nil {
1735 return nil, fmt.Errorf("no agent running")
1736 }
1737 fresh, err := core.NewSession(root, cwd, providerName, model, version)
1738 if err != nil {
1739 return nil, err
1740 }
1741 if old != nil {
1742 writeNewTranscriptLocked(ag, old, baseline)
1743 _ = old.Close()
1744 }
1745 ag.SetMessages(nil)
1746 ag.DrainQueuedMessages()
1747 ag.SeedCost(provider.Usage{})
1748 ag.SeedLastTurnUsage(provider.Usage{})
1749 bindAgentSession(ag, fresh)
1750 return fresh, nil
1751}
1752
1753// WriteNewTranscript appends only messages after index `from` from the
1754// agent's transcript to the session. Used by callers that don't hold
1755// the persistMu (non-interactive print/json modes which run a single
1756// turn under their own goroutine).
1757func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1758 writeNewTranscriptLocked(ag, sess, from)
1759}
1760
1761// bindAgentSession stamps the zot session id onto the agent so providers
1762// that support sticky routing (OpenRouter session_id) can reuse it.
1763// No-op when persistence is disabled.
1764func bindAgentSession(ag *core.Agent, sess *core.Session) {
1765 if ag == nil || sess == nil {
1766 return
1767 }
1768 ag.SessionID = sess.ID
1769}
1770
1771// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1772// suffix marks that interactive callers must hold persistMu when
1773// invoking it so concurrent appends from the agent loop don't race
1774// with this catch-up flush.
1775func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1776 if sess == nil || ag == nil {
1777 return
1778 }
1779 msgs := ag.Messages()
1780 for i := from; i < len(msgs); i++ {
1781 _ = sess.AppendMessage(msgs[i])
1782 }
1783 cum := ag.Cost()
1784 _ = sess.AppendUsage(cum, cum)
1785}
1786
1787func argsForStdin(rawArgs []string, mode os.FileMode) []string {
1788 if mode&os.ModeCharDevice != 0 {
1789 return rawArgs
1790 }
1791 return append([]string{"--print"}, rawArgs...)
1792}
1793
1794func combinePromptInput(stdin, positional string) string {
1795 parts := make([]string, 0, 2)
1796 if stdin = strings.TrimSpace(stdin); stdin != "" {
1797 parts = append(parts, stdin)
1798 }
1799 if positional = strings.TrimSpace(positional); positional != "" {
1800 parts = append(parts, positional)
1801 }
1802 return strings.Join(parts, "\n")
1803}
1804
1805func readAllStdin() (string, error) {
1806 fi, err := os.Stdin.Stat()
1807 if err != nil {
1808 return "", err
1809 }
1810 if (fi.Mode() & os.ModeCharDevice) != 0 {
1811 return "", nil
1812 }
1813 b, err := io.ReadAll(os.Stdin)
1814 return string(b), err
1815}
1816
1817func printModels() {
1818 models := provider.Active()
1819
1820 // Compute column widths from actual data so wide providers (e.g.
1821 // xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1822 // `name` column off-screen. Floors mirror the historical layout so
1823 // short catalogs look the same as before.
1824 provW, idW, srcW := len("provider"), len("model id"), len("source")
1825 for _, m := range models {
1826 if w := len(m.Provider); w > provW {
1827 provW = w
1828 }
1829 if w := len(m.ID); w > idW {
1830 idW = w
1831 }
1832 source := m.Source
1833 if source == "" {
1834 source = "catalog"
1835 }
1836 if m.Speculative {
1837 source = "speculative"
1838 }
1839 if w := len(source); w > srcW {
1840 srcW = w
1841 }
1842 }
1843
1844 header := fmt.Sprintf("%-*s %-*s %8s %8s %s %-*s %s",
1845 provW, "provider",
1846 idW, "model id",
1847 "context", "max-out", "reasoning",
1848 srcW, "source",
1849 "name")
1850 fmt.Println(header)
1851
1852 for _, m := range models {
1853 reason := " "
1854 if m.Reasoning {
1855 reason = "✓"
1856 }
1857 source := m.Source
1858 if source == "" {
1859 source = "catalog"
1860 }
1861 if m.Speculative {
1862 source = "speculative"
1863 }
1864 fmt.Printf("%-*s %-*s %8d %8d %s %-*s %s\n",
1865 provW, m.Provider,
1866 idW, m.ID,
1867 m.ContextWindow, m.MaxOutput,
1868 reason,
1869 srcW, source,
1870 m.DisplayName)
1871 }
1872}