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