v0.2.78 cc6b04d

cli.go RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close