v0.2.43 6899695

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.Submit(text)
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); 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			OnSpawned: onSpawnedSwarm,
490		}
491		return reg
492	}
493	injectSwarmSpawn(r.ToolRegistry)
494
495	// Confirmation gate: when --no-yolo is on, the agent must ask
496	// the user before every tool call. In interactive mode the TUI
497	// provides the Confirmer; in print/json/rpc modes there's no
498	// way to prompt, so the gate is constructed with a nil inner
499	// which auto-refuses every call with a helpful reason.
500	var confirmGate *core.ConfirmGate
501	if args.NoYolo {
502		confirmGate = core.NewConfirmGate(nil) // set below for interactive
503	}
504
505	// Capture current args in a closure so BuildAgent can re-resolve
506	// after a successful login (picks up the newly stored credential).
507	wireAgentExt := func(a *core.Agent) *core.Agent {
508		if a == nil {
509			return a
510		}
511		a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
512			// Confirm gate runs FIRST: if the user refused, we don't
513			// waste extension-intercept time or let guards see the call.
514			if confirmGate != nil {
515				ok, reason, _ := confirmGate.Check(call.Name, core.BuildPreview(call.Arguments, 120))
516				if !ok {
517					return false, reason, nil
518				}
519			}
520			r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
521			if r.Block {
522				return false, r.Reason, nil
523			}
524			return true, "", r.ModifiedArgs
525		}
526		a.BeforeTurn = func(step int) (bool, string) {
527			r := extMgr.InterceptTurnStart(ctx, step)
528			return !r.Block, r.Reason
529		}
530		a.BeforeAssistantMessage = func(text string) (bool, string, string) {
531			r := extMgr.InterceptAssistantMessage(ctx, text)
532			if r.Block {
533				return false, r.Reason, ""
534			}
535			return true, "", r.ReplaceText
536		}
537		a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
538		return a
539	}
540
541	buildAgent := func() (*core.Agent, string, string, error) {
542		resolved, err := Resolve(args, true)
543		if err != nil {
544			return nil, "", "", err
545		}
546		resolved.UseSandbox(sharedSandbox)
547		resolved.MergeExtensionTools(extToolAdapter)
548		injectSwarmSpawn(resolved.ToolRegistry)
549		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
550	}
551
552	// Rebuild agent with an explicit provider/model override.
553	buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
554		next := args
555		if providerOverride != "" {
556			next.Provider = providerOverride
557		}
558		if modelOverride != "" {
559			next.Model = modelOverride
560		}
561		resolved, err := Resolve(next, true)
562		if err != nil {
563			return nil, "", "", err
564		}
565		resolved.UseSandbox(sharedSandbox)
566		resolved.MergeExtensionTools(extToolAdapter)
567		injectSwarmSpawn(resolved.ToolRegistry)
568		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
569	}
570
571	// Rebuild agent for the rescue picker after a recoverable failure.
572	// Unlike buildAgentFor, this drops launch-time --api-key and
573	// --base-url overrides because those are typically the cause of the
574	// rescue (a bad key, a typo'd base URL, or a corporate gateway that
575	// only the originally-picked provider needed). Re-resolving without
576	// them lets the rescue retry use env vars / auth.json / provider
577	// defaults the way zot would have without the overrides.
578	buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
579		next := args
580		next.APIKey = ""
581		next.BaseURL = ""
582		if providerOverride != "" {
583			next.Provider = providerOverride
584		}
585		if modelOverride != "" {
586			next.Model = modelOverride
587		}
588		resolved, err := Resolve(next, true)
589		if err != nil {
590			return nil, "", "", err
591		}
592		resolved.UseSandbox(sharedSandbox)
593		resolved.MergeExtensionTools(extToolAdapter)
594		injectSwarmSpawn(resolved.ToolRegistry)
595		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
596	}
597
598	var ag *core.Agent
599	if r.HasCredential() {
600		ag = wireAgentExt(r.NewAgent())
601	}
602
603	// /reload-ext callback: after the manager has respawned every
604	// extension, re-resolve the tool registry (built-ins + freshly-
605	// registered extension tools) and swap it onto the current
606	// agent in-place. The current agent may have been replaced by a
607	// /model swap since spawn, so re-read the live `ag` on each
608	// invocation.
609	extMgr.SetOnReload(func() {
610		current := ag
611		if current == nil {
612			return
613		}
614		resolved, err := Resolve(args, true)
615		if err != nil {
616			return
617		}
618		resolved.UseSandbox(sharedSandbox)
619		resolved.MergeExtensionTools(extToolAdapter)
620		injectSwarmSpawn(resolved.ToolRegistry)
621		current.SetTools(resolved.ToolRegistry)
622	})
623
624	// Fire session_start once we know the manager's running.
625	extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
626
627	var sess *core.Session
628	var sessBaselineMsgs int // messages already on disk when current session opened
629	// persistMu guards sess + sessBaselineMsgs against concurrent access
630	// from the agent loop's per-message persistence hook (runs on the
631	// agent goroutine) and the TUI's session swap / flush callbacks
632	// (run on the TUI goroutine). Without this, a /sessions swap that
633	// races with a finishing turn could double-write or lose messages.
634	var persistMu sync.Mutex
635	if !args.NoSess && ag != nil {
636		sess, _ = openOrCreateSession(args, r, ag, version)
637		if ag != nil {
638			sessBaselineMsgs = len(ag.Messages())
639		}
640	}
641	defer func() {
642		persistMu.Lock()
643		defer persistMu.Unlock()
644		if sess != nil {
645			sess.Close()
646		}
647	}()
648
649	// persistMessage is the per-message hook bound to the agent. It
650	// appends each new transcript message to the live session as soon
651	// as it lands, so a kill / closed terminal / OS crash costs at
652	// most the in-flight turn instead of the whole session. The
653	// baseline counter advances in lock-step so the exit-time flush
654	// doesn't double-write rows already on disk.
655	persistMessage := func(m provider.Message) {
656		persistMu.Lock()
657		defer persistMu.Unlock()
658		if sess == nil {
659			return
660		}
661		if err := sess.AppendMessage(m); err == nil {
662			sessBaselineMsgs++
663		}
664	}
665	persistUsage := func(cum provider.Usage) {
666		persistMu.Lock()
667		defer persistMu.Unlock()
668		if sess == nil {
669			return
670		}
671		_ = sess.AppendUsage(cum, cum)
672	}
673	persistCompaction := func(messages []provider.Message) {
674		persistMu.Lock()
675		defer persistMu.Unlock()
676		if sess == nil {
677			return
678		}
679		if err := sess.AppendCompaction(messages); err == nil {
680			sessBaselineMsgs = len(messages)
681		}
682	}
683	wireAgentPersist := func(a *core.Agent) *core.Agent {
684		if a == nil {
685			return a
686		}
687		a.OnMessageAppended = persistMessage
688		a.OnUsage = persistUsage
689		a.OnTranscriptCompacted = persistCompaction
690		return a
691	}
692	wireAgentPersist(ag)
693
694	// Re-wrap the build closures so any agent constructed by the TUI
695	// (login, /model swap to a different provider) also gets the
696	// persistence hooks. Without this, switching provider would
697	// silently revert to the old in-memory-only behaviour.
698	baseBuildAgent := buildAgent
699	buildAgent = func() (*core.Agent, string, string, error) {
700		a, p, m, err := baseBuildAgent()
701		return wireAgentPersist(a), p, m, err
702	}
703	baseBuildAgentFor := buildAgentFor
704	buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
705		a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
706		return wireAgentPersist(a), p, m, err
707	}
708	baseBuildAgentForRescue := buildAgentForRescue
709	buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
710		a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
711		return wireAgentPersist(a), p, m, err
712	}
713
714	// loadSession replaces the current session with the one at path and
715	// hands its messages to the agent. Used by the /sessions picker.
716	loadSession := func(path string) error {
717		currentAg := ag // captured
718		if currentAg == nil {
719			return fmt.Errorf("no agent running; log in first")
720		}
721		newSess, msgs, err := core.OpenSession(path)
722		if err != nil {
723			return err
724		}
725		fullMsgCount := len(msgs)
726		msgs = trimMessagesForResume(msgs, 100)
727		persistMu.Lock()
728		// Flush any unsaved messages to the old session before swapping.
729		// Per-message persistence keeps sessBaselineMsgs current, so
730		// this is a defensive no-op in the common case; it still
731		// matters for the rare race where a turn just finished and
732		// hadn't fired its hook yet.
733		if sess != nil {
734			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
735			_ = sess.Close()
736		}
737		sess = newSess
738		currentAg.SetMessages(msgs)
739		if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
740			currentAg.SeedCost(cum)
741			currentAg.SeedLastTurnUsage(last)
742		}
743		// The live agent only receives a compact resume window, but
744		// the session file remains intact. Keep the persistence
745		// baseline at the original on-disk message count so future
746		// turns append after the full session instead of duplicating
747		// the hydrated tail.
748		sessBaselineMsgs = fullMsgCount
749		persistMu.Unlock()
750		// Re-scope the swarm dashboard to the new session so /swarm
751		// only shows agents this session spawned. swarmMgr may be nil
752		// here if we haven't reached the construction site yet (it
753		// shouldn't be, since the interactive loop is what triggers
754		// loadSession, but the nil check is cheap insurance).
755		if swarmMgr != nil && newSess != nil {
756			swarmMgr.SetActiveSession(newSess.ID)
757		}
758		return nil
759	}
760
761	// changeCWD switches the running session to a new working directory.
762	// Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
763	// /cd slash command (which itself is only fired by the workspaces
764	// extension's panel-key Enter handler today; the user can type /cd
765	// directly but it's not in autocomplete / help / the README).
766	//
767	// Steps, in order:
768	//   1. resolve + validate the new path (~ expansion, abs/rel)
769	//   2. close the current session, flushing pending messages
770	//   3. mutate captured args.CWD + r.CWD so future buildAgent
771	//      calls bind to the new cwd
772	//   4. re-root the shared sandbox («·«) so /jail follows the
773	//      session into the new cwd instead of widening or silently
774	//      dropping
775	//   5. rebuild the agent via buildAgent() so tools, AGENTS.md
776	//      addendum, system prompt, sessions dir all bind correctly
777	//   6. open a fresh session in the new cwd's bucket
778	//   7. push the new state into the running Interactive
779	//   8. re-scope the swarm dashboard to the freshly-opened session
780	//
781	// The /jail state is preserved verbatim: if the sandbox was locked
782	// to the old cwd, it stays locked, just re-pointed at the new one.
783	changeCWD := func(path string) error {
784		if path == "" {
785			return fmt.Errorf("empty path")
786		}
787		// ~ expansion.
788		if path == "~" || strings.HasPrefix(path, "~/") {
789			home, herr := os.UserHomeDir()
790			if herr != nil || home == "" {
791				return fmt.Errorf("cannot expand ~: %v", herr)
792			}
793			if path == "~" {
794				path = home
795			} else {
796				path = filepath.Join(home, path[2:])
797			}
798		}
799		if !filepath.IsAbs(path) {
800			path = filepath.Join(args.CWD, path)
801		}
802		absPath, err := filepath.Abs(path)
803		if err != nil {
804			return err
805		}
806		info, err := os.Stat(absPath)
807		if err != nil {
808			return err
809		}
810		if !info.IsDir() {
811			return fmt.Errorf("not a directory: %s", absPath)
812		}
813
814		currentAg := ag
815		if currentAg == nil {
816			return fmt.Errorf("no agent running; log in first")
817		}
818
819		// Close the current session before we drop the reference.
820		// Per-message persistence keeps it current already; this is
821		// a defensive flush + final fsync via Close.
822		persistMu.Lock()
823		if sess != nil {
824			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
825			_ = sess.Close()
826			sess = nil
827		}
828		sessBaselineMsgs = 0
829		persistMu.Unlock()
830
831		// Mutate captured state so subsequent agent rebuilds and
832		// session opens see the new cwd.
833		wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
834		args.CWD = absPath
835		r.CWD = absPath
836		if sharedSandbox != nil {
837			sharedSandbox.Root = absPath
838			if wasJailed {
839				sharedSandbox.Lock()
840			} else {
841				sharedSandbox.Unlock()
842			}
843		}
844
845		// Rebuild the agent so tools / AGENTS.md / system prompt
846		// re-bind to the new cwd. buildAgent() reads from args + r.
847		newAg, newProvider, newModel, berr := buildAgent()
848		if berr != nil {
849			return fmt.Errorf("rebuild agent: %v", berr)
850		}
851		ag = newAg
852
853		// Fresh session in the new cwd's bucket. We bypass
854		// openOrCreateSession's --continue / --resume branches
855		// because /cd's semantics are "start fresh here", matching
856		// what relaunching `zot --cwd <path>` would do today.
857		if !args.NoSess {
858			core.PruneEmptySessions(ZotHome(), absPath)
859			newSess, serr := core.NewSession(ZotHome(), absPath, newProvider, newModel, version)
860			if serr != nil {
861				return fmt.Errorf("open session in %s: %v", absPath, serr)
862			}
863			persistMu.Lock()
864			sess = newSess
865			sessBaselineMsgs = 0
866			persistMu.Unlock()
867		}
868
869		// Push the new state into the running Interactive.
870		if iv != nil {
871			iv.ApplyChangedCWD(newAg, newProvider, newModel, absPath)
872		}
873
874		// Re-scope the swarm dashboard to the new session.
875		if swarmMgr != nil && sess != nil {
876			swarmMgr.SetActiveSession(sess.ID)
877		}
878		return nil
879	}
880
881	term := tui.NewProcTerm()
882
883	// Kick off the async update check so the banner can appear when the
884	// http response eventually arrives (usually <1s on cached DNS). Map
885	// agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
886	updateCh := make(chan modes.UpdateInfo, 1)
887	go func() {
888		defer close(updateCh)
889		src := <-CheckForUpdateAsync(ZotHome(), version)
890		updateCh <- modes.UpdateInfo{
891			Current:   src.Current,
892			Latest:    src.Latest,
893			Available: src.Available,
894			URL:       src.URL,
895		}
896	}()
897
898	// Changelog: when the running version differs from the last
899	// version whose release notes the user dismissed, fetch the
900	// release body from GitHub and have the TUI show it once. On
901	// first-ever launch (no prior LastChangelogShown), seed the
902	// stored version silently — don't dump release notes at someone
903	// who just installed.
904	changelogCh := make(chan modes.ChangelogPayload, 1)
905	go func() {
906		defer close(changelogCh)
907		cfg, _ := LoadConfig()
908		if cfg.LastChangelogShown == "" {
909			SeedChangelogVersion(version)
910			return
911		}
912		if !ShouldShowChangelog(version, cfg) {
913			return
914		}
915		info := <-FetchChangelogAsync(version)
916		if info.Body == "" {
917			return
918		}
919		// For dev builds (0.0.0), skip if the latest release was
920		// already shown (stored by the dismiss callback).
921		if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
922			return
923		}
924		changelogCh <- modes.ChangelogPayload{
925			Version: info.Version,
926			Body:    info.Body,
927			URL:     info.URL,
928		}
929	}()
930
931	initialCfg, _ := LoadConfig()
932	theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
933	if themeErr != nil {
934		fmt.Fprintln(os.Stderr, "theme load:", themeErr)
935		if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
936			initialCfg.Theme = ""
937			_ = SaveConfig(initialCfg)
938		}
939	}
940
941	// swarmMgr was constructed and reloaded earlier (before the agent
942	// build, so the auto-swarm tool could capture it). Here we just
943	// scope the dashboard to the active host session so /swarm only
944	// shows agents this session spawned (and any pre-upgrade unscoped
945	// agents — see SnapshotAll docs). Updated again whenever the
946	// user swaps sessions via loadSession below.
947	if sess != nil {
948		swarmMgr.SetActiveSession(sess.ID)
949	}
950	// Best-effort shutdown on interactive exit: stop all running
951	// agents so they don't outlive their parent zot.
952	defer swarmMgr.StopAll()
953
954	iv = modes.NewInteractive(modes.InteractiveConfig{
955		Terminal:                   term,
956		Theme:                      theme,
957		InlineImagesEnabled:        initialCfg.InlineImagesEnabled,
958		AutoSwarmEnabled:           initialCfg.AutoSwarmEnabled,
959		RecursiveFileSuggest:       initialCfg.RecursiveFileSuggest,
960		RespectGitignore:           initialCfg.RespectGitignore,
961		ThemeName:                  initialCfg.Theme,
962		ExtensionThemes:            extMgr.ThemeOptions,
963		AutoSwarmSystemAddendum:    AutoSwarmSystemAddendum,
964		SettingsStore:              configSettingsStore{},
965		Model:                      r.Model,
966		Provider:                   r.Provider,
967		AuthMethod:                 r.AuthMethod,
968		BaseURL:                    r.BaseURL,
969		Reasoning:                  r.Reasoning,
970		SystemPrompt:               r.SystemPrompt,
971		Tools:                      r.ToolRegistry,
972		MaxSteps:                   r.MaxSteps,
973		CWD:                        r.CWD,
974		ZotHome:                    ZotHome(),
975		Version:                    version,
976		UpdateInfoChan:             updateCh,
977		Sandbox:                    sharedSandbox,
978		Agent:                      ag,
979		InitialInput:               args.Prompt,
980		AuthManager:                mgr,
981		BuildAgent:                 buildAgent,
982		SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
983		BuildAgentFor:              buildAgentFor,
984		BuildAgentForRescue:        buildAgentForRescue,
985		LoggedInProviders: func() []string {
986			var out []string
987			seen := map[string]bool{}
988			for _, p := range knownProviders {
989				if _, _, err := ResolveCredential(p, ""); err == nil && !seen[p] {
990					out = append(out, p)
991					seen[p] = true
992				}
993			}
994			// Include custom providers that have credentials stored.
995			for p := range provider.CustomProviders() {
996				if _, _, err := ResolveCredential(p, ""); err == nil && !seen[p] {
997					out = append(out, p)
998					seen[p] = true
999				}
1000			}
1001			// Ollama models are always available (no auth needed).
1002			if !seen["ollama"] {
1003				out = append(out, "ollama")
1004			}
1005			return out
1006		},
1007		LoadSession: loadSession,
1008		ChangeCWD:   changeCWD,
1009		CurrentSessionPath: func() string {
1010			if sess == nil {
1011				return ""
1012			}
1013			return sess.Path
1014		},
1015		FlushSession: func() {
1016			// Append any not-yet-persisted agent messages to the
1017			// current session file, then advance the baseline so
1018			// the final WriteNewTranscript at exit doesn't write
1019			// duplicates. Per-message persistence keeps the on-
1020			// disk file current already, so this is mostly a
1021			// defensive flush — still needed for /session export
1022			// to guarantee the exported bytes include the very
1023			// last in-flight turn.
1024			currentAg := iv.Agent()
1025			if currentAg == nil {
1026				return
1027			}
1028			persistMu.Lock()
1029			defer persistMu.Unlock()
1030			if sess == nil {
1031				return
1032			}
1033			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1034			sessBaselineMsgs = len(currentAg.Messages())
1035		},
1036		Extensions:    extMgr,
1037		Swarm:         swarmMgr,
1038		ChangelogChan: changelogCh,
1039		OnChangelogDismiss: func() {
1040			// For dev builds (0.0.0) store the actual release version
1041			// so the same changelog doesn't show again next launch.
1042			// For real builds, store the binary version.
1043			v := version
1044			if v == "0.0.0" {
1045				if iv != nil && iv.ChangelogVersion() != "" {
1046					v = iv.ChangelogVersion()
1047				}
1048			}
1049			_ = MarkChangelogShown(v)
1050		},
1051		SkillSnapshot: func() []*skills.Skill {
1052			if args.NoSkill {
1053				// --no-skill: nothing for the picker to show.
1054				return nil
1055			}
1056			// Re-discover so the picker reflects edits made during
1057			// the session. Cheap; SKILL.md files are small. Filter
1058			// out built-in skills — they're hidden from user-facing
1059			// surfaces because they're implementation detail; the
1060			// model still sees them through the system-prompt
1061			// manifest and the skill tool.
1062			userHome, _ := os.UserHomeDir()
1063			list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
1064			return skills.VisibleSkills(list)
1065		},
1066		NoYolo:      args.NoYolo,
1067		ConfirmGate: confirmGate,
1068		PersistModel: func(providerName, model string) {
1069			// Update config.json so next launch uses the same pick.
1070			cfg, _ := LoadConfig()
1071			cfg.Provider = providerName
1072			cfg.Model = model
1073			_ = SaveConfig(cfg)
1074			// Update the active session's meta so resume picks this up.
1075			if sess != nil {
1076				_ = sess.UpdateModel(providerName, model)
1077			}
1078		},
1079	})
1080
1081	// Bind the interactive TUI as the Confirmer. We deferred this
1082	// until now because the gate is constructed before the TUI
1083	// (the BeforeToolExecute closure captures it). SetConfirmer
1084	// is mutex-guarded on the gate so this is safe.
1085	if confirmGate != nil {
1086		confirmGate.SetConfirmer(iv)
1087	}
1088
1089	// Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1090	// (closed terminal window, system shutdown, kill) used to lose
1091	// the entire in-memory transcript because the deferred post-Run
1092	// flush below never ran. Per-message persistence above covers
1093	// most of it; this handler writes any in-flight remainder and
1094	// then exits the process so we don't double-paint over a
1095	// broken terminal that the TUI's restore deferreds can no
1096	// longer fix from a signal context.
1097	//
1098	// SIGINT is intentionally NOT handled here — the TUI consumes
1099	// Ctrl+C as a regular key event for cancel/clear semantics, and
1100	// installing a SIGINT notifier here would swallow it.
1101	sigCh := make(chan os.Signal, 1)
1102	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1103	defer signal.Stop(sigCh)
1104	go func() {
1105		_, ok := <-sigCh
1106		if !ok {
1107			return
1108		}
1109		if finalAg := iv.Agent(); finalAg != nil {
1110			persistMu.Lock()
1111			if sess != nil {
1112				writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1113				sessBaselineMsgs = len(finalAg.Messages())
1114				_ = sess.Close()
1115				sess = nil
1116			}
1117			persistMu.Unlock()
1118		}
1119		// Exit cleanly. Re-raising the signal would skip os.Exit's
1120		// at-exit hooks; explicit exit is fine because we've already
1121		// flushed the only at-risk state (the session file).
1122		os.Exit(0)
1123	}()
1124
1125	runErr := iv.Run(ctx)
1126
1127	// Flush final transcript to session (only if we had / ended up with an agent).
1128	if finalAg := iv.Agent(); finalAg != nil {
1129		persistMu.Lock()
1130		if sess != nil {
1131			writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1132			sessBaselineMsgs = len(finalAg.Messages())
1133		}
1134		persistMu.Unlock()
1135	}
1136	return runErr
1137}
1138
1139// openOrCreateSession returns a session for the run. sess may be nil
1140// with a nil error if session persistence is disabled.
1141func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1142	if args.NoSess {
1143		return nil, nil
1144	}
1145	// Sweep meta-only files left over from older zot versions (and from
1146	// any session that crashed before its first AppendMessage). Cheap;
1147	// reads the first few bytes of each file in the cwd's session dir.
1148	core.PruneEmptySessions(ZotHome(), args.CWD)
1149	var (
1150		s    *core.Session
1151		msgs []provider.Message
1152		err  error
1153	)
1154	switch {
1155	case args.Session != "":
1156		s, msgs, err = core.OpenSession(args.Session)
1157		// The swarm-agent child passes a fixed --session path that
1158		// may not exist yet on first Spawn. Treat ENOENT as "create
1159		// a fresh session AT THIS PATH" so the conversation actually
1160		// gets persisted; without this fallback the swarm child runs
1161		// with sess==nil and every Resume re-starts with no memory
1162		// of the prior turns. Other openers (--continue / --resume /
1163		// the picker) never see ENOENT here because they only choose
1164		// paths that already exist on disk.
1165		if err != nil && errors.Is(err, os.ErrNotExist) {
1166			s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1167			msgs = nil
1168		}
1169	case args.Continue:
1170		latest := core.LatestSession(ZotHome(), args.CWD)
1171		if latest != "" {
1172			s, msgs, err = core.OpenSession(latest)
1173		}
1174	case args.Resume:
1175		picked, perr := pickSession(args.CWD)
1176		if perr != nil {
1177			return nil, perr
1178		}
1179		if picked != "" {
1180			s, msgs, err = core.OpenSession(picked)
1181		}
1182	}
1183	if err != nil {
1184		return nil, err
1185	}
1186	if s != nil {
1187		ag.SetMessages(msgs)
1188		if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1189			ag.SeedCost(cum)
1190			ag.SeedLastTurnUsage(last)
1191		}
1192		return s, nil
1193	}
1194	return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
1195}
1196
1197func pickSession(cwd string) (string, error) {
1198	files := core.ListSessions(ZotHome(), cwd)
1199	if len(files) == 0 {
1200		fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1201		return "", nil
1202	}
1203	for i, f := range files {
1204		fmt.Fprintf(os.Stderr, "  %2d) %s\n", i+1, f)
1205	}
1206	fmt.Fprint(os.Stderr, "pick #: ")
1207	rd := bufio.NewReader(os.Stdin)
1208	line, _ := rd.ReadString('\n')
1209	line = strings.TrimSpace(line)
1210	var n int
1211	if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1212		return "", fmt.Errorf("invalid selection")
1213	}
1214	return files[n-1], nil
1215}
1216
1217// WriteNewTranscript appends only messages after index `from` from the
1218// agent's transcript to the session. Used by callers that don't hold
1219// the persistMu (non-interactive print/json modes which run a single
1220// turn under their own goroutine).
1221func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1222	writeNewTranscriptLocked(ag, sess, from)
1223}
1224
1225// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1226// suffix marks that interactive callers must hold persistMu when
1227// invoking it so concurrent appends from the agent loop don't race
1228// with this catch-up flush.
1229func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1230	if sess == nil || ag == nil {
1231		return
1232	}
1233	msgs := ag.Messages()
1234	for i := from; i < len(msgs); i++ {
1235		_ = sess.AppendMessage(msgs[i])
1236	}
1237	cum := ag.Cost()
1238	_ = sess.AppendUsage(cum, cum)
1239}
1240
1241func readAllStdin() (string, error) {
1242	fi, err := os.Stdin.Stat()
1243	if err != nil {
1244		return "", err
1245	}
1246	if (fi.Mode() & os.ModeCharDevice) != 0 {
1247		return "", nil
1248	}
1249	b, err := io.ReadAll(os.Stdin)
1250	return string(b), err
1251}
1252
1253func printModels() {
1254	models := provider.Active()
1255
1256	// Compute column widths from actual data so wide providers (e.g.
1257	// xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1258	// `name` column off-screen. Floors mirror the historical layout so
1259	// short catalogs look the same as before.
1260	provW, idW, srcW := len("provider"), len("model id"), len("source")
1261	for _, m := range models {
1262		if w := len(m.Provider); w > provW {
1263			provW = w
1264		}
1265		if w := len(m.ID); w > idW {
1266			idW = w
1267		}
1268		source := m.Source
1269		if source == "" {
1270			source = "catalog"
1271		}
1272		if m.Speculative {
1273			source = "speculative"
1274		}
1275		if w := len(source); w > srcW {
1276			srcW = w
1277		}
1278	}
1279
1280	header := fmt.Sprintf("%-*s  %-*s  %8s  %8s  %s  %-*s  %s",
1281		provW, "provider",
1282		idW, "model id",
1283		"context", "max-out", "reasoning",
1284		srcW, "source",
1285		"name")
1286	fmt.Println(header)
1287
1288	for _, m := range models {
1289		reason := " "
1290		if m.Reasoning {
1291			reason = "✓"
1292		}
1293		source := m.Source
1294		if source == "" {
1295			source = "catalog"
1296		}
1297		if m.Speculative {
1298			source = "speculative"
1299		}
1300		fmt.Printf("%-*s  %-*s  %8d  %8d     %s      %-*s  %s\n",
1301			provW, m.Provider,
1302			idW, m.ID,
1303			m.ContextWindow, m.MaxOutput,
1304			reason,
1305			srcW, source,
1306			m.DisplayName)
1307	}
1308}

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