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