v0.3.92 6d56e22

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) SupportsInteractiveTools() bool { return h.iv() != nil }
76
77func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
78	if iv := h.iv(); iv != nil {
79		iv.OpenPanel(extName, spec)
80	}
81}
82func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
83	if iv := h.iv(); iv != nil {
84		iv.UpdatePanel(extName, panelID, title, lines, footer)
85	}
86}
87func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
88	if iv := h.iv(); iv != nil {
89		iv.ClosePanel(extName, panelID)
90	}
91}
92
93// extToolAdapter bridges *extensions.Manager to the
94// ExtensionToolSource interface declared in build.go (kept narrow to
95// avoid a build->extensions import cycle). One adapter instance per
96// run; used at every Resolve point so re-built agents pick up the
97// same set of extension tools.
98type extToolAdapter struct {
99	mgr *extensions.Manager
100}
101
102func (a *extToolAdapter) Tools() []ExtensionToolInfo {
103	infos := a.mgr.Tools()
104	out := make([]ExtensionToolInfo, len(infos))
105	for i, t := range infos {
106		out[i] = ExtensionToolInfo{
107			Extension:   t.Extension,
108			Name:        t.Name,
109			Description: t.Description,
110			Schema:      t.Schema,
111			Deferred:    t.Deferred,
112			Interactive: t.Interactive,
113		}
114	}
115	return out
116}
117
118func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
119	return extensions.NewTool(a.mgr, extensions.ToolInfo{
120		Extension:   info.Extension,
121		Name:        info.Name,
122		Description: info.Description,
123		Schema:      info.Schema,
124		Deferred:    info.Deferred,
125		Interactive: info.Interactive,
126	})
127}
128
129// liveInteractiveAgent returns the agent currently owned by the TUI. The
130// fallback is only used before the Interactive has been constructed.
131//
132// Agent rebuilds, such as cross-provider model switches, replace the TUI's
133// agent without replacing the startup pointer held by runInteractive. Session
134// operations must therefore resolve the live agent at the time of the action.
135func liveInteractiveAgent(iv *modes.Interactive, fallback *core.Agent) *core.Agent {
136	if iv != nil {
137		return iv.Agent()
138	}
139	return fallback
140}
141
142func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
143	if keepTail <= 0 || len(msgs) <= keepTail {
144		return provider.RepairOrphanedToolResults(msgs)
145	}
146	var out []provider.Message
147	start := len(msgs) - keepTail
148	// Preserve the synthetic compaction summary when present so an
149	// already-compacted session stays compacted after resume.
150	if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 1 {
151		out = append(out, msgs[0])
152	}
153	// Avoid hydrating a tail that starts with orphan tool_result rows;
154	// provider APIs require those to be paired with an earlier tool_use.
155	for start < len(msgs) && msgs[start].Role == provider.RoleTool {
156		start++
157	}
158	out = append(out, msgs[start:]...)
159	return provider.RepairOrphanedToolResults(out)
160}
161
162// fanoutAgentEvent translates a core.AgentEvent into the wire-format
163// EventFromHost and pushes it through the extension manager. Only
164// the events that have a clear extension-facing meaning are
165// forwarded; internal-only ones (text_delta, tool_progress) are
166// dropped to keep the per-extension stream sane.
167func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
168	if mgr == nil {
169		return
170	}
171	switch e := ev.(type) {
172	case core.EvPromptSubmit:
173		mgr.EmitEvent(extproto.EventFromHost{Event: "user_prompt_submit", Text: e.Text, Queued: e.Queued, ImageCount: e.ImageCount})
174	case core.EvToolResult:
175		if e.Executed && e.Status == "blocked" {
176			mgr.EmitEvent(extproto.EventFromHost{Event: "permission_decision", ToolID: e.ID, ToolName: e.Name, Decision: "denied", Source: "policy", Stage: "tool_execution"})
177		}
178		mgr.EmitEvent(extproto.EventFromHost{Event: "tool_result", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args, Status: e.Status, Executed: &e.Executed, Result: extensionEventResult(e.Result)})
179	case core.EvCompact:
180		event := extproto.EventFromHost{Event: e.Type(), CompactionID: e.ID, MessageCount: &e.MessageCount, TokenEstimate: &e.TokenEstimate, Status: e.Status}
181		if e.Err != nil {
182			event.Error = e.Err.Error()
183		}
184		mgr.EmitEvent(event)
185	case core.EvTurnStart:
186		mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
187	case core.EvToolCall:
188		mgr.EmitEvent(extproto.EventFromHost{
189			Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
190		})
191	case core.EvAssistantMessage:
192		// Concat the visible text portions of the message; binary
193		// blocks (tool_use, etc.) are skipped because subscribers
194		// usually want a string they can grep / display.
195		var text string
196		for _, c := range e.Message.Content {
197			if tb, ok := c.(provider.TextBlock); ok {
198				text += tb.Text
199			}
200		}
201		mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
202	case core.EvTurnEnd:
203		ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
204		if e.Err != nil {
205			ev.Error = e.Err.Error()
206		}
207		mgr.EmitEvent(ev)
208	}
209}
210
211// Run is the top-level entrypoint for the zot binary.
212func Run(rawArgs []string, version string) error {
213	// Mark the process and all child processes as running under zot. This
214	// lets shell tools, extensions, and scripts distinguish zot execution
215	// from an ordinary invocation. Clear per-session values because embedded
216	// callers may invoke Run more than once in one process.
217	_ = os.Setenv("AI_AGENT", "zot")
218	_ = os.Setenv("ZOT_AGENT", "1")
219	for _, name := range []string{"ZOT_SESSION_ID", "ZOT_SESSION_FILE", "ZOT_PROVIDER", "ZOT_MODEL", "ZOT_REASONING_LEVEL"} {
220		_ = os.Unsetenv(name)
221	}
222
223	// Apply network configuration before any subcommand can make an HTTP
224	// request. Standard proxy environment variables retain precedence.
225	applyConfiguredHTTPProxy()
226
227	// Subcommand router: `zot bot ...` is handled separately so the
228	// generic flag parser doesn't reject "bot" as a positional arg.
229	if handled, err := runBotCommand(rawArgs, version); handled {
230		return err
231	}
232	if handled, err := runExtCommand(rawArgs, version); handled {
233		return err
234	}
235	if handled, err := runUpdateCommand(rawArgs, version); handled {
236		return err
237	}
238	if handled, err := runSessionsCommand(rawArgs); handled {
239		return err
240	}
241	if handled, err := runZotfileCommand(rawArgs, version); handled {
242		return err
243	}
244	return runWithArgsRaw(rawArgs, version)
245}
246
247func runWithArgsRaw(rawArgs []string, version string) error {
248	// `zot rpc` is shorthand for `zot --rpc` so third-party apps can
249	// spawn the binary with a clean argv. Strip the leading 'rpc'
250	// token and let the rest flow through the normal arg parser.
251	if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
252		rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
253	}
254
255	if fi, err := os.Stdin.Stat(); err == nil {
256		rawArgs = argsForStdin(rawArgs, fi.Mode())
257	}
258	args, err := ParseArgs(rawArgs)
259	if err != nil {
260		PrintHelp(version)
261		return err
262	}
263	if args.Help {
264		printHelp(os.Stdout, version)
265		return nil
266	}
267	if args.Version {
268		fmt.Println("zot", version)
269		return nil
270	}
271	// Model catalog: load any cached discovery data before we inspect
272	// the model list (list-models, print/json, interactive).
273	prepareRuntimeCatalog()
274
275	if args.ListModels {
276		printModels()
277		return nil
278	}
279
280	return runWithArgs(args, version)
281}
282
283func runWithArgs(args Args, version string) error {
284	ctx := context.Background()
285	switch args.Mode {
286	case ModePrint:
287		return runPrintMode(ctx, args, version)
288	case ModeStream:
289		return runStreamMode(ctx, args, version)
290	case ModeJSON:
291		return runJSONMode(ctx, args, version)
292	case ModeRPC:
293		return runRPCMode(ctx, args, version)
294	case ModeSwarmAgent:
295		return runSwarmAgentMode(ctx, args, version)
296	default:
297		return runInteractive(ctx, args, version)
298	}
299}
300
301// ---- print / json modes: require credentials, run single-shot ----
302
303// nonInteractiveExtHooks is the HostHooks impl used by print / json
304// modes. They have no TUI, so notify / display go to stderr and
305// submit / insert are no-ops (the extension can't steer a
306// single-shot run once it's in flight anyway).
307type nonInteractiveExtHooks struct{}
308
309func (nonInteractiveExtHooks) Notify(ext, level, message string) {
310	fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
311}
312func (nonInteractiveExtHooks) Submit(string)                                        {}
313func (nonInteractiveExtHooks) SubmitSlash(string)                                   {}
314func (nonInteractiveExtHooks) Insert(string)                                        {}
315func (nonInteractiveExtHooks) Display(string, string)                               {}
316func (nonInteractiveExtHooks) ClearNotes(string)                                    {}
317func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec)                 {}
318func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
319func (nonInteractiveExtHooks) ClosePanel(string, string)                            {}
320
321// setupNonInteractiveExtensions loads --ext paths and (unless
322// --no-ext) runs discovery. Returns the manager so the caller can
323// wire tools into the resolved registry, and a cleanup closure to
324// defer. Mirrors the interactive-mode setup minus the TUI hooks.
325func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
326	reportSkillDiagnostics(os.Stderr, r.SkillDiagnostics)
327	extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
328	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
329		fmt.Fprintln(os.Stderr, "extension load:", e)
330	}
331	if !args.NoExt {
332		for _, e := range extMgr.Discover(ctx) {
333			fmt.Fprintln(os.Stderr, "extension load:", e)
334		}
335	}
336	extMgr.WaitForReady(3 * time.Second)
337	r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
338	return extMgr, func() { extMgr.Stop(2 * time.Second) }
339}
340
341func reportSkillDiagnostics(w io.Writer, diagnostics []string) {
342	for _, diagnostic := range diagnostics {
343		fmt.Fprintln(w, "skill discovery:", diagnostic)
344	}
345}
346
347// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
348// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
349// interactive path wires up, so extensions get their normal
350// event-intercept surface in print / json / rpc flows too.
351func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
352	if ag == nil || extMgr == nil {
353		return
354	}
355	wireBeforeAgentStart(ag, extMgr, "")
356	ag.BeforeToolExecuteContext = func(ctx context.Context, call provider.ToolCallBlock) (bool, string, json.RawMessage) {
357		res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
358		if res.Block {
359			emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: res.Reason})
360			return false, res.Reason, res.ModifiedArgs
361		}
362		emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Allow: true, Source: "yolo"})
363		return true, "", res.ModifiedArgs
364	}
365	ag.BeforeTurn = func(step int) (bool, string) {
366		res := extMgr.InterceptTurnStart(ctx, step)
367		return !res.Block, res.Reason
368	}
369	ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
370		res := extMgr.InterceptAssistantMessage(ctx, text)
371		if res.Block {
372			return false, res.Reason, ""
373		}
374		return true, "", res.ReplaceText
375	}
376	wireLifecycleEvents(ag, extMgr)
377}
378
379type printStats struct {
380	Provider              string `json:"provider"`
381	Model                 string `json:"model"`
382	PromptTokens          int    `json:"prompt_tokens"`
383	ReasoningTokens       *int   `json:"reasoning_tokens"`
384	GeneratedOutputTokens int    `json:"generated_output_tokens"`
385	ElapsedMS             int64  `json:"elapsed_ms"`
386}
387
388func writePrintStats(path, providerID, model string, usage provider.Usage, elapsed time.Duration) error {
389	var reasoning *int
390	generated := usage.OutputTokens
391	if usage.ReasoningTokensKnown {
392		count := usage.ReasoningTokens
393		reasoning = &count
394		generated -= count
395		if generated < 0 {
396			generated = 0
397		}
398	}
399	stats := printStats{
400		Provider:              providerID,
401		Model:                 model,
402		PromptTokens:          usage.InputTokens + usage.CacheReadTokens + usage.CacheWriteTokens,
403		ReasoningTokens:       reasoning,
404		GeneratedOutputTokens: generated,
405		ElapsedMS:             elapsed.Milliseconds(),
406	}
407	data, err := json.MarshalIndent(stats, "", "  ")
408	if err != nil {
409		return fmt.Errorf("encode stats: %w", err)
410	}
411	data = append(data, '\n')
412	if err := os.WriteFile(path, data, 0o644); err != nil {
413		return fmt.Errorf("write stats %q: %w", path, err)
414	}
415	return nil
416}
417
418func runPrintMode(ctx context.Context, args Args, version string) error {
419	if args.NoYolo {
420		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
421	}
422	r, err := Resolve(args, true)
423	if err != nil {
424		return err
425	}
426	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
427	defer stopExt()
428
429	ag := r.NewAgent()
430	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
431	sess, fresh, _ := openOrCreateSessionState(args, r, ag, version)
432	defer sess.Close()
433
434	piped, _ := readAllStdin()
435	prompt := combinePromptInput(piped, args.Prompt)
436	if prompt == "" {
437		return fmt.Errorf("print mode requires a prompt (arg or stdin)")
438	}
439
440	start := len(ag.Messages())
441	if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, nil, os.Stderr); err != nil {
442		return err
443	}
444	reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
445	prompt = preloadSkillPins(args, fresh, prompt, os.Stderr)
446	started := time.Now()
447	usage, err := modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
448	elapsed := time.Since(started)
449	WriteNewTranscript(ag, sess, start)
450	if err != nil {
451		return err
452	}
453	if args.StatsPath != "" {
454		return writePrintStats(args.StatsPath, r.Provider, r.Model, usage, elapsed)
455	}
456	return nil
457}
458
459func runStreamMode(ctx context.Context, args Args, version string) error {
460	if args.NoYolo {
461		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in stream mode (no interactive prompt available); tools will run without confirmation")
462	}
463	r, err := Resolve(args, true)
464	if err != nil {
465		return err
466	}
467	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
468	defer stopExt()
469
470	ag := r.NewAgent()
471	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
472	sess, fresh, _ := openOrCreateSessionState(args, r, ag, version)
473	defer sess.Close()
474
475	piped, _ := readAllStdin()
476	prompt := combinePromptInput(piped, args.Prompt)
477	if prompt == "" {
478		return fmt.Errorf("stream mode requires a prompt (arg or stdin)")
479	}
480
481	start := len(ag.Messages())
482	preSink, finishPre := newStreamTextSink(os.Stdout)
483	if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
484		finishPre()
485		return err
486	}
487	finishPre()
488	reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
489	prompt = preloadSkillPins(args, fresh, prompt, os.Stderr)
490	err = modes.RunStream(ctx, ag, prompt, nil, os.Stdout)
491	WriteNewTranscript(ag, sess, start)
492	return err
493}
494
495func newStreamTextSink(out io.Writer) (func(core.AgentEvent), func()) {
496	var streamed, wroteText, lastWasNL bool
497	writeText := func(text string) {
498		if text == "" {
499			return
500		}
501		_, _ = fmt.Fprint(out, text)
502		if syncer, ok := out.(interface{ Sync() error }); ok {
503			_ = syncer.Sync()
504		}
505		wroteText = true
506		lastWasNL = strings.HasSuffix(text, "\n")
507	}
508	sink := func(ev core.AgentEvent) {
509		switch e := ev.(type) {
510		case core.EvAssistantStart:
511			streamed = false
512		case core.EvTextDelta:
513			streamed = true
514			writeText(e.Delta)
515		case core.EvAssistantMessage:
516			if streamed {
517				return
518			}
519			var text strings.Builder
520			for _, content := range e.Message.Content {
521				if block, ok := content.(provider.TextBlock); ok {
522					if text.Len() > 0 {
523						text.WriteString("\n")
524					}
525					text.WriteString(block.Text)
526				}
527			}
528			writeText(text.String())
529		}
530	}
531	finish := func() {
532		if wroteText && !lastWasNL {
533			writeText("\n")
534		}
535	}
536	return sink, finish
537}
538
539func runJSONMode(ctx context.Context, args Args, version string) error {
540	if args.NoYolo {
541		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
542	}
543	r, err := Resolve(args, true)
544	if err != nil {
545		return err
546	}
547	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
548	defer stopExt()
549
550	ag := r.NewAgent()
551	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
552	sess, fresh, _ := openOrCreateSessionState(args, r, ag, version)
553	defer sess.Close()
554
555	piped, _ := readAllStdin()
556	prompt := combinePromptInput(piped, args.Prompt)
557	if prompt == "" {
558		return fmt.Errorf("json mode requires a prompt (arg or stdin)")
559	}
560
561	start := len(ag.Messages())
562	enc := json.NewEncoder(os.Stdout)
563	preSink := func(ev core.AgentEvent) {
564		_ = enc.Encode(modes.EventToJSON(ev))
565	}
566	if err := runZotfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
567		_ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
568		return err
569	}
570	reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag)
571	prompt = preloadSkillPins(args, fresh, prompt, os.Stderr)
572	err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
573	WriteNewTranscript(ag, sess, start)
574	return err
575}
576
577// runZotfileStartupPre runs entry.pre before the main non-interactive prompt.
578// "!command" values execute via BashTool; other values are sent as an agent turn.
579// shellOut receives live shell chunks (typically os.Stderr); sink receives
580// agent events for plain-text pre (stream mode wires a live text sink).
581func runZotfileStartupPre(ctx context.Context, pre, cwd string, sandbox *tools.Sandbox, ag *core.Agent, sink func(core.AgentEvent), shellOut io.Writer) error {
582	pre = strings.TrimSpace(pre)
583	if pre == "" {
584		return nil
585	}
586	if cmd, ok := modes.ShellEscapeCommand(pre); ok {
587		raw, err := json.Marshal(map[string]any{"command": cmd})
588		if err != nil {
589			return err
590		}
591		if shellOut != nil {
592			fmt.Fprintf(shellOut, "$ %s\n", cmd)
593			if f, ok := shellOut.(interface{ Sync() error }); ok {
594				_ = f.Sync()
595			}
596		}
597		progress := func(chunk string) {
598			if shellOut == nil || chunk == "" {
599				return
600			}
601			fmt.Fprint(shellOut, chunk)
602			if f, ok := shellOut.(interface{ Sync() error }); ok {
603				_ = f.Sync()
604			}
605		}
606		bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
607		res, err := bash.Execute(ctx, raw, progress)
608		if err != nil {
609			return fmt.Errorf("zotfile entry.pre: %w", err)
610		}
611		if res.IsError {
612			var sb strings.Builder
613			for _, c := range res.Content {
614				if tb, ok := c.(provider.TextBlock); ok {
615					sb.WriteString(tb.Text)
616				}
617			}
618			msg := strings.TrimSpace(sb.String())
619			if msg == "" {
620				msg = "command failed"
621			}
622			return fmt.Errorf("zotfile entry.pre: %s", msg)
623		}
624		return nil
625	}
626	if ag == nil {
627		return fmt.Errorf("zotfile entry.pre requires an agent for non-shell prompts")
628	}
629	if sink == nil {
630		sink = func(core.AgentEvent) {}
631	}
632	return ag.Prompt(ctx, pre, nil, sink)
633}
634
635// refreshAgentToolsAndPrompt re-resolves tools (including rediscovered
636// skills and currently loaded extension tools) and updates the live
637// agent's registry and system prompt. Used after /reload-ext and after
638// zotfile entry.pre installs new skills or extensions.
639// mutateRegistry, if non-nil, can inject session-specific tools (e.g. swarm_spawn).
640func refreshAgentToolsAndPrompt(args Args, sharedSandbox *tools.Sandbox, extToolAdapter ExtensionToolSource, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry) {
641	if ag == nil {
642		return
643	}
644	resolved, err := Resolve(args, true)
645	if err != nil {
646		return
647	}
648	if sharedSandbox != nil {
649		resolved.UseSandbox(sharedSandbox)
650	}
651	if extToolAdapter != nil {
652		resolved.MergeExtensionTools(extToolAdapter)
653	}
654	reg := resolved.ToolRegistry
655	if mutateRegistry != nil {
656		reg = mutateRegistry(reg)
657	}
658	ag.SetTools(reg)
659	ag.SetSystem(resolved.SystemPrompt)
660}
661
662// reloadResourcesAfterStartupPre reloads extensions (if any) and
663// refreshes the agent tool registry + system prompt so skills/extensions
664// installed by entry.pre are visible to the following turn.
665func reloadResourcesAfterStartupPre(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent) {
666	if strings.TrimSpace(args.StartupPre) == "" || ag == nil {
667		return
668	}
669	adapter := &extToolAdapter{mgr: extMgr}
670	if extMgr != nil {
671		_ = extMgr.Reload(ctx, 2*time.Second)
672	}
673	refreshAgentToolsAndPrompt(args, sharedSandbox, adapter, ag, nil)
674}
675
676// ---- interactive mode: opens the TUI even without credentials ----
677
678func runInteractive(ctx context.Context, args Args, version string) error {
679	// Resolve WITHOUT requiring credentials.
680	r, err := Resolve(args, false)
681	if err != nil {
682		return err
683	}
684
685	authStore := AuthStoreFor()
686	mgr := auth.NewManager(authStore)
687	defer mgr.Close()
688
689	// Keep the sandbox pointer stable across agent rebuilds (login / model
690	// switch). The Interactive UI toggles the lock via this pointer, and
691	// rebuilt tool instances must share the same one so the lock sticks.
692	sharedSandbox := r.Sandbox
693
694	// Build the extension manager BEFORE the agent so we can fold
695	// extension-defined tools into the registry. Forward-declare iv so
696	// the host hooks adapter can dereference it after construction.
697	var iv *modes.Interactive
698	extHooks := &interactiveExtHooks{ivPtr: &iv}
699	extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
700	startupExtensionErrors := make([]string, 0, len(r.SkillDiagnostics))
701	for _, diagnostic := range r.SkillDiagnostics {
702		startupExtensionErrors = append(startupExtensionErrors, "skill discovery: "+diagnostic)
703	}
704	// --ext paths first so they win against installed extensions of
705	// the same name (loadOne's first-write-wins semantics).
706	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
707		startupExtensionErrors = append(startupExtensionErrors, e.Error())
708	}
709	// --no-ext skips the global + project-local discovery scan;
710	// explicit --ext paths above are still honoured so you can run
711	// "only this extension" with --no-ext --ext ./x.
712	if !args.NoExt {
713		for _, e := range extMgr.Discover(ctx) {
714			startupExtensionErrors = append(startupExtensionErrors, e.Error())
715		}
716	}
717	// Wait briefly for extensions to flush their initial register_tool
718	// frames before we build the agent's tool registry. Half a second
719	// is plenty for any extension that's actually well-behaved; ones
720	// that don't send a ready frame eat the full grace and proceed.
721	// 3s is the per-extension grace period for the ready frame.
722	// Native binaries are instant; runtimes like `npx tsx` take ~1.5s
723	// from cold cache. The wait is tight only for extensions that
724	// haven't sent ready by then; ones that signalled earlier release
725	// the wait immediately.
726	extMgr.WaitForReady(3 * time.Second)
727	defer extMgr.Stop(2 * time.Second)
728
729	extToolAdapter := &extToolAdapter{mgr: extMgr}
730	r.MergeExtensionTools(extToolAdapter)
731
732	// Build the swarm supervisor BEFORE the agent so the auto-swarm
733	// tool can reference it during tool-registry construction. State
734	// lives under ZotHome/swarm so per-agent meta/events survive
735	// restarts; the user can hunt orphaned agents down with
736	// `git worktree list` if anything misbehaves.
737	//
738	// swarmMgr is also captured by loadSession / changeCWD closures
739	// further down the function, which is why we keep the variable
740	// in this outer scope rather than scoping it tighter.
741	var swarmMgr *swarm.Swarm
742	swarmMgr = swarm.New(swarm.Config{
743		Root:        filepath.Join(ZotHome(), "swarm"),
744		RepoRoot:    r.CWD,
745		OnLifecycle: func(e swarm.LifecycleEvent) { emitSwarmLifecycle(extMgr, e) },
746		ResolveCredential: func(ctx context.Context, providerID string) (swarm.Credential, error) {
747			if providerID == "ollama" {
748				return swarm.Credential{Value: "ollama", Method: "apikey"}, nil
749			}
750			credential, method, accountID, err := ResolveCredentialFullContext(ctx, providerID, "")
751			if err != nil {
752				// Providers backed only by a local endpoint do not need a key.
753				// Leave stdin untouched and let the child resolve that endpoint.
754				if !CredentialAvailable(providerID) {
755					return swarm.Credential{}, nil
756				}
757				return swarm.Credential{}, err
758			}
759			return swarm.Credential{Value: credential, Method: method, AccountID: accountID}, nil
760		},
761	})
762	// Pull any previously-spawned agents off disk so the dashboard
763	// shows them as detached and the user can resume / remove them.
764	_, _ = swarmMgr.Reload()
765
766	// onSpawnedSwarm is the OnSpawned callback the swarm_spawn tool
767	// fires after every successful spawn. It hands the agent off to
768	// the running Interactive so the watcher can flush a summary back
769	// into chat when all sub-agents finish. Reads `iv` lazily because
770	// the Interactive is constructed after the agent.
771	onSpawnedSwarm := func(a *swarm.Agent, task string) {
772		if iv != nil {
773			iv.TrackSwarmAgent(a, task)
774		}
775	}
776
777	// Inject the swarm_spawn auto-swarm tool only when /settings ->
778	// auto-swarm is currently enabled. Registering it unconditionally
779	// leaves the model trying to call it (and getting a polite error)
780	// even when the user has switched the feature off. The /settings
781	// toggle live-mutates the running agent's registry separately so
782	// flipping the flag mid-session takes effect on the next turn.
783	injectSwarmSpawn := func(reg core.Registry) core.Registry {
784		if reg == nil {
785			return reg
786		}
787		if !AutoSwarmEnabled() {
788			return reg
789		}
790		reg["swarm_spawn"] = &tools.SwarmSpawnTool{
791			Swarm:           swarmMgr,
792			Enabled:         AutoSwarmEnabled,
793			DefaultModel:    func() string { return r.Model },
794			DefaultProvider: func() string { return r.Provider },
795			OnSpawned:       onSpawnedSwarm,
796		}
797		return reg
798	}
799	injectSwarmSpawn(r.ToolRegistry)
800
801	// Confirmation gate: when --no-yolo is on, the agent must ask
802	// the user before every tool call. In interactive mode the TUI
803	// provides the Confirmer; in print/json/rpc modes there's no
804	// way to prompt, so the gate is constructed with a nil inner
805	// which auto-refuses every call with a helpful reason.
806	var confirmGate *core.ConfirmGate
807	if args.NoYolo {
808		confirmGate = core.NewConfirmGate(nil) // set below for interactive
809	}
810
811	// Capture current args in a closure so BuildAgent can re-resolve
812	// after a successful login (picks up the newly stored credential).
813	wireAgentExt := func(resolved Resolved) *core.Agent {
814		a := resolved.NewAgent()
815		wireBeforeAgentStart(a, extMgr, resolved.Provider)
816		a.BeforeToolExecuteContext = func(ctx context.Context, call provider.ToolCallBlock) (bool, string, json.RawMessage) {
817			// Guards run before confirmation because they may rewrite the
818			// arguments. The user must approve the effective call that will
819			// actually execute, not the model's original arguments.
820			r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
821			if r.Block {
822				emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: r.Reason})
823				return false, r.Reason, r.ModifiedArgs
824			}
825			effectiveArgs := call.Arguments
826			if len(r.ModifiedArgs) > 0 && json.Valid(r.ModifiedArgs) {
827				effectiveArgs = r.ModifiedArgs
828			}
829			if confirmGate != nil {
830				var content strings.Builder
831				if tool, err := a.Tools.Get(call.Name); err == nil {
832					if previewer, ok := tool.(core.ToolPreviewer); ok {
833						preview, err := previewer.Preview(ctx, effectiveArgs)
834						if err != nil {
835							emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Source: "policy", Reason: err.Error()})
836							return false, err.Error(), effectiveArgs
837						}
838						for _, block := range preview.Content {
839							if text, ok := block.(provider.TextBlock); ok {
840								if content.Len() > 0 {
841									content.WriteString("\n")
842								}
843								content.WriteString(text.Text)
844							}
845						}
846					}
847				}
848				decision := confirmGate.DecideToolCall(core.ToolCallConfirmation{
849					ID:      call.ID,
850					Name:    call.Name,
851					Summary: core.BuildPreview(effectiveArgs, 120),
852					Content: content.String(),
853				})
854				emitPermissionDecision(ctx, extMgr, call, decision)
855				if !decision.Allow {
856					return false, decision.Reason, effectiveArgs
857				}
858			} else {
859				emitPermissionDecision(ctx, extMgr, call, core.ConfirmDecision{Allow: true, Source: "yolo"})
860			}
861			return true, "", r.ModifiedArgs
862		}
863		a.BeforeTurn = func(step int) (bool, string) {
864			r := extMgr.InterceptTurnStart(ctx, step)
865			return !r.Block, r.Reason
866		}
867		a.BeforeAssistantMessage = func(text string) (bool, string, string) {
868			r := extMgr.InterceptAssistantMessage(ctx, text)
869			if r.Block {
870				return false, r.Reason, ""
871			}
872			return true, "", r.ReplaceText
873		}
874		wireLifecycleEvents(a, extMgr)
875		return a
876	}
877
878	buildAgent := func() (*core.Agent, string, string, error) {
879		resolved, err := Resolve(args, true)
880		if err != nil {
881			return nil, "", "", err
882		}
883		resolved.UseSandbox(sharedSandbox)
884		resolved.MergeExtensionTools(extToolAdapter)
885		injectSwarmSpawn(resolved.ToolRegistry)
886		return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
887	}
888
889	// Rebuild agent with an explicit provider/model override.
890	buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
891		next := args
892		if providerOverride != "" {
893			next.Provider = providerOverride
894		}
895		if modelOverride != "" {
896			next.Model = modelOverride
897		}
898		resolved, err := Resolve(next, true)
899		if err != nil {
900			return nil, "", "", err
901		}
902		resolved.UseSandbox(sharedSandbox)
903		resolved.MergeExtensionTools(extToolAdapter)
904		injectSwarmSpawn(resolved.ToolRegistry)
905		return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
906	}
907
908	// Rebuild agent for the rescue picker after a recoverable failure.
909	// Unlike buildAgentFor, this drops launch-time --api-key and
910	// --base-url overrides because those are typically the cause of the
911	// rescue (a bad key, a typo'd base URL, or a corporate gateway that
912	// only the originally-picked provider needed). Re-resolving without
913	// them lets the rescue retry use env vars / auth.json / provider
914	// defaults the way zot would have without the overrides.
915	buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
916		next := args
917		next.APIKey = ""
918		next.BaseURL = ""
919		if providerOverride != "" {
920			next.Provider = providerOverride
921		}
922		if modelOverride != "" {
923			next.Model = modelOverride
924		}
925		resolved, err := Resolve(next, true)
926		if err != nil {
927			return nil, "", "", err
928		}
929		resolved.UseSandbox(sharedSandbox)
930		resolved.MergeExtensionTools(extToolAdapter)
931		injectSwarmSpawn(resolved.ToolRegistry)
932		return wireAgentExt(resolved), resolved.Provider, resolved.Model, nil
933	}
934
935	var ag *core.Agent
936	if r.HasCredential() {
937		ag = wireAgentExt(r)
938	}
939
940	// /reload-ext callback: after the manager has respawned every
941	// extension, re-resolve the tool registry (built-ins + freshly-
942	// registered extension tools) and swap it onto the current
943	// agent in-place. The current agent may have been replaced by a
944	// /model swap since spawn, so re-read the live `ag` on each
945	// invocation.
946	extMgr.SetOnReload(func() {
947		current := liveInteractiveAgent(iv, ag)
948		if current == nil {
949			return
950		}
951		refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
952	})
953
954	var sess *core.Session
955	freshSession := true
956	var sessBaselineMsgs int // messages already on disk when current session opened
957	// persistMu guards sess + sessBaselineMsgs against concurrent access
958	// from the agent loop's per-message persistence hook (runs on the
959	// agent goroutine) and the TUI's session swap / flush callbacks
960	// (run on the TUI goroutine). Without this, a /sessions swap that
961	// races with a finishing turn could double-write or lose messages.
962	var persistMu sync.Mutex
963	if ag != nil {
964		sess, freshSession, _ = openOrCreateSessionState(args, r, ag, version)
965		if ag != nil {
966			sessBaselineMsgs = len(ag.Messages())
967		}
968	}
969	startExtensionSession(extMgr, ag, r.CWD, "")
970	defer func() {
971		persistMu.Lock()
972		defer persistMu.Unlock()
973		if sess != nil {
974			sess.Close()
975		}
976	}()
977
978	// persistMessage is the per-message hook bound to the agent. It
979	// appends each new transcript message to the live session as soon
980	// as it lands, so a kill / closed terminal / OS crash costs at
981	// most the in-flight turn instead of the whole session. The
982	// baseline counter advances in lock-step so the exit-time flush
983	// doesn't double-write rows already on disk.
984	persistMessage := func(m provider.Message) {
985		persistMu.Lock()
986		defer persistMu.Unlock()
987		if sess == nil {
988			return
989		}
990		if err := sess.AppendMessage(m); err == nil {
991			sessBaselineMsgs++
992		}
993	}
994	persistUsage := func(cum provider.Usage) {
995		persistMu.Lock()
996		defer persistMu.Unlock()
997		if sess == nil {
998			return
999		}
1000		_ = sess.AppendUsage(cum, cum)
1001	}
1002	persistCompaction := func(messages []provider.Message) {
1003		persistMu.Lock()
1004		defer persistMu.Unlock()
1005		if sess == nil {
1006			return
1007		}
1008		if err := sess.AppendCompaction(messages); err == nil {
1009			sessBaselineMsgs = len(messages)
1010		}
1011	}
1012	wireAgentPersist := func(a *core.Agent) *core.Agent {
1013		if a == nil {
1014			return a
1015		}
1016		a.OnMessageAppended = persistMessage
1017		a.OnUsage = persistUsage
1018		a.OnTranscriptCompacted = persistCompaction
1019		return a
1020	}
1021	wireAgentPersist(ag)
1022
1023	// Re-wrap the build closures so any agent constructed by the TUI
1024	// (login, /model swap to a different provider) also gets the
1025	// persistence hooks. Without this, switching provider would
1026	// silently revert to the old in-memory-only behaviour.
1027	bindLiveAgentSession := func(a *core.Agent) {
1028		persistMu.Lock()
1029		s := sess
1030		persistMu.Unlock()
1031		bindAgentSession(a, s)
1032	}
1033	baseBuildAgent := buildAgent
1034	buildAgent = func() (*core.Agent, string, string, error) {
1035		a, p, m, err := baseBuildAgent()
1036		a = wireAgentPersist(a)
1037		bindLiveAgentSession(a)
1038		return a, p, m, err
1039	}
1040	baseBuildAgentFor := buildAgentFor
1041	buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1042		a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
1043		a = wireAgentPersist(a)
1044		bindLiveAgentSession(a)
1045		return a, p, m, err
1046	}
1047	baseBuildAgentForRescue := buildAgentForRescue
1048	buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1049		a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
1050		a = wireAgentPersist(a)
1051		bindLiveAgentSession(a)
1052		return a, p, m, err
1053	}
1054
1055	// loadSession replaces the current session with the one at path and
1056	// hands its messages to the agent. Used by the /sessions picker.
1057	loadSession := func(path string) error {
1058		currentAg := liveInteractiveAgent(iv, ag)
1059		if currentAg == nil {
1060			return fmt.Errorf("no agent running; log in first")
1061		}
1062		newSess, msgs, err := core.OpenSession(path)
1063		if err != nil {
1064			return err
1065		}
1066		fullMsgCount := len(msgs)
1067		msgs = trimMessagesForResume(msgs, 100)
1068		persistMu.Lock()
1069		// Flush any unsaved messages to the old session before swapping.
1070		// Per-message persistence keeps sessBaselineMsgs current, so
1071		// this is a defensive no-op in the common case; it still
1072		// matters for the rare race where a turn just finished and
1073		// hadn't fired its hook yet.
1074		if sess != nil {
1075			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1076			_ = sess.Close()
1077		}
1078		sess = newSess
1079		currentAg.SetMessages(msgs)
1080		bindAgentSession(currentAg, sess)
1081		setZotSessionEnvironment(r, sess)
1082		startExtensionSession(extMgr, currentAg, r.CWD, "session_switch")
1083		if cum, last, uerr := core.SessionUsageDetail(path); uerr == nil {
1084			currentAg.SeedCost(cum)
1085			currentAg.SeedLastTurnUsage(last)
1086		}
1087		// The live agent only receives a compact resume window, but
1088		// the session file remains intact. Keep the persistence
1089		// baseline at the original on-disk message count so future
1090		// turns append after the full session instead of duplicating
1091		// the hydrated tail.
1092		sessBaselineMsgs = fullMsgCount
1093		persistMu.Unlock()
1094		if iv != nil {
1095			iv.SetPinnedSkillsPending(false)
1096		}
1097		// Re-scope the swarm dashboard to the new session so /swarm
1098		// only shows agents this session spawned. swarmMgr may be nil
1099		// here if we haven't reached the construction site yet (it
1100		// shouldn't be, since the interactive loop is what triggers
1101		// loadSession, but the nil check is cheap insurance).
1102		if swarmMgr != nil && newSess != nil {
1103			swarmMgr.SetActiveSession(newSess.ID)
1104		}
1105		return nil
1106	}
1107
1108	var newSession func(providerName, model string) error
1109	if !args.NoSess {
1110		newSession = func(providerName, model string) error {
1111			currentAg := liveInteractiveAgent(iv, ag)
1112			if currentAg == nil {
1113				return fmt.Errorf("no agent running; log in first")
1114			}
1115
1116			persistMu.Lock()
1117			newSess, err := rotateInteractiveSession(
1118				agentSessionsRoot(ZotHome(), args), r.CWD, providerName, model, version,
1119				currentAg, sess, sessBaselineMsgs,
1120			)
1121			if err == nil {
1122				sess = newSess
1123				sessBaselineMsgs = 0
1124			}
1125			persistMu.Unlock()
1126			if err != nil {
1127				return err
1128			}
1129
1130			active := r
1131			active.Provider = providerName
1132			active.Model = model
1133			setZotSessionEnvironment(active, newSess)
1134			startExtensionSession(extMgr, currentAg, r.CWD, "session_switch")
1135			if swarmMgr != nil {
1136				swarmMgr.SetActiveSession(newSess.ID)
1137			}
1138			return nil
1139		}
1140	}
1141
1142	// changeCWD switches the running session to a new working directory.
1143	// Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
1144	// /cd slash command (which itself is only fired by the workspaces
1145	// extension's panel-key Enter handler today; the user can type /cd
1146	// directly but it's not in autocomplete / help / the README).
1147	//
1148	// Steps, in order:
1149	//   1. resolve + validate the new path (~ expansion, abs/rel)
1150	//   2. close the current session, flushing pending messages
1151	//   3. mutate captured args.CWD + r.CWD so future buildAgent
1152	//      calls bind to the new cwd
1153	//   4. re-root the shared sandbox («·«) so /jail follows the
1154	//      session into the new cwd instead of widening or silently
1155	//      dropping
1156	//   5. rebuild the agent via buildAgent() so tools, AGENTS.md
1157	//      addendum, system prompt, sessions dir all bind correctly
1158	//   6. open a fresh session in the new cwd's bucket
1159	//   7. push the new state into the running Interactive
1160	//   8. re-scope the swarm dashboard to the freshly-opened session
1161	//
1162	// The /jail state is preserved verbatim: if the sandbox was locked
1163	// to the old cwd, it stays locked, just re-pointed at the new one.
1164	changeCWD := func(path string) error {
1165		if path == "" {
1166			return fmt.Errorf("empty path")
1167		}
1168		// ~ expansion.
1169		if path == "~" || strings.HasPrefix(path, "~/") {
1170			home, herr := os.UserHomeDir()
1171			if herr != nil || home == "" {
1172				return fmt.Errorf("cannot expand ~: %v", herr)
1173			}
1174			if path == "~" {
1175				path = home
1176			} else {
1177				path = filepath.Join(home, path[2:])
1178			}
1179		}
1180		if !filepath.IsAbs(path) {
1181			path = filepath.Join(args.CWD, path)
1182		}
1183		absPath, err := filepath.Abs(path)
1184		if err != nil {
1185			return err
1186		}
1187		info, err := os.Stat(absPath)
1188		if err != nil {
1189			return err
1190		}
1191		if !info.IsDir() {
1192			return fmt.Errorf("not a directory: %s", absPath)
1193		}
1194
1195		currentAg := ag
1196		if currentAg == nil {
1197			return fmt.Errorf("no agent running; log in first")
1198		}
1199
1200		// Close the current session before we drop the reference.
1201		// Per-message persistence keeps it current already; this is
1202		// a defensive flush + final fsync via Close.
1203		persistMu.Lock()
1204		if sess != nil {
1205			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1206			_ = sess.Close()
1207			sess = nil
1208		}
1209		sessBaselineMsgs = 0
1210		persistMu.Unlock()
1211		extMgr.EndSession("cwd_change")
1212
1213		// Mutate captured state so subsequent agent rebuilds and
1214		// session opens see the new cwd.
1215		wasJailed := sharedSandbox != nil && sharedSandbox.Locked()
1216		args.CWD = absPath
1217		r.CWD = absPath
1218		if args.PermissionSet != nil {
1219			expanded := args.PermissionSet.Expand(absPath, args.AgentDataDir)
1220			args.PermissionSet = &expanded
1221		}
1222		if sharedSandbox != nil {
1223			sharedSandbox.Root = absPath
1224			if wasJailed {
1225				sharedSandbox.Lock()
1226			} else {
1227				sharedSandbox.Unlock()
1228			}
1229		}
1230
1231		// Rebuild the agent so tools / AGENTS.md / system prompt
1232		// re-bind to the new cwd. buildAgent() reads from args + r.
1233		newAg, newProvider, newModel, berr := buildAgent()
1234		if berr != nil {
1235			return fmt.Errorf("rebuild agent: %v", berr)
1236		}
1237		ag = newAg
1238
1239		// Fresh session in the new cwd's bucket. We bypass
1240		// openOrCreateSession's --continue / --resume branches
1241		// because /cd's semantics are "start fresh here", matching
1242		// what relaunching `zot --cwd <path>` would do today.
1243		if !args.NoSess {
1244			newRoot := agentSessionsRoot(ZotHome(), args)
1245			core.PruneEmptySessions(newRoot, absPath)
1246			newSess, serr := core.NewSession(newRoot, absPath, newProvider, newModel, version)
1247			if serr != nil {
1248				return fmt.Errorf("open session in %s: %v", absPath, serr)
1249			}
1250			persistMu.Lock()
1251			sess = newSess
1252			sessBaselineMsgs = 0
1253			persistMu.Unlock()
1254			bindAgentSession(newAg, newSess)
1255		}
1256
1257		r.Provider = newProvider
1258		r.Model = newModel
1259		r.Reasoning = newAg.Reasoning
1260		setZotSessionEnvironment(r, sess)
1261		startExtensionSession(extMgr, newAg, absPath, "cwd_change")
1262
1263		// Push the new state into the running Interactive.
1264		if iv != nil {
1265			startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZotHome()))
1266			iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
1267			iv.SetPinnedSkillsPending(true)
1268		}
1269
1270		// Re-scope the swarm dashboard to the new session.
1271		if swarmMgr != nil {
1272			sessionID, _ := extMgr.SessionContext()
1273			swarmMgr.SetActiveSession(sessionID)
1274		}
1275		return nil
1276	}
1277
1278	term := tui.NewProcTerm()
1279
1280	// Kick off the async update check so the banner can appear when the
1281	// http response eventually arrives (usually <1s on cached DNS). Map
1282	// agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
1283	updateCh := make(chan modes.UpdateInfo, 1)
1284	go func() {
1285		defer close(updateCh)
1286		src := <-CheckForUpdateAsync(ZotHome(), version)
1287		updateCh <- modes.UpdateInfo{
1288			Current:   src.Current,
1289			Latest:    src.Latest,
1290			Available: src.Available,
1291			URL:       src.URL,
1292		}
1293	}()
1294
1295	// Changelog: when the running version differs from the last
1296	// version whose release notes the user dismissed, fetch the
1297	// release body from GitHub and have the TUI show it once. On
1298	// first-ever launch (no prior LastChangelogShown), seed the
1299	// stored version silently — don't dump release notes at someone
1300	// who just installed.
1301	changelogCh := make(chan modes.ChangelogPayload, 1)
1302	go func() {
1303		defer close(changelogCh)
1304		cfg, _ := LoadConfig()
1305		if cfg.LastChangelogShown == "" {
1306			SeedChangelogVersion(version)
1307			return
1308		}
1309		if !ShouldShowChangelog(version, cfg) {
1310			return
1311		}
1312		info := <-FetchChangelogAsync(version)
1313		if info.Body == "" {
1314			return
1315		}
1316		// For dev builds (0.0.0), skip if the latest release was
1317		// already shown (stored by the dismiss callback).
1318		if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
1319			return
1320		}
1321		changelogCh <- modes.ChangelogPayload{
1322			Version: info.Version,
1323			Body:    info.Body,
1324			URL:     info.URL,
1325		}
1326	}()
1327
1328	initialCfg, _ := LoadConfig()
1329	quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
1330	for idx, s := range initialCfg.QuickModelShortcuts {
1331		quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
1332	}
1333	theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
1334	if themeErr != nil {
1335		fmt.Fprintln(os.Stderr, "theme load:", themeErr)
1336		if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
1337			initialCfg.Theme = ""
1338			_ = SaveConfig(initialCfg)
1339		}
1340	}
1341
1342	// swarmMgr was constructed and reloaded earlier (before the agent
1343	// build, so the auto-swarm tool could capture it). Here we just
1344	// scope the dashboard to the active host session so /swarm only
1345	// shows agents this session spawned (and any pre-upgrade unscoped
1346	// agents — see SnapshotAll docs). Updated again whenever the
1347	// user swaps sessions via loadSession below.
1348	sessionID, _ := extMgr.SessionContext()
1349	swarmMgr.SetActiveSession(sessionID)
1350	// Best-effort shutdown on interactive exit: stop all running
1351	// agents so they don't outlive their parent zot.
1352	defer func() {
1353		shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
1354		defer cancel()
1355		swarmMgr.Shutdown(shutdownCtx)
1356	}()
1357
1358	var startupSkills []*skills.Skill
1359	if r.SkillTool != nil {
1360		startupSkills = r.SkillTool.Skills()
1361	}
1362
1363	iv = modes.NewInteractive(modes.InteractiveConfig{
1364		Terminal:                      term,
1365		Theme:                         theme,
1366		InlineImagesEnabled:           initialCfg.InlineImagesEnabled,
1367		AutoSwarmEnabled:              initialCfg.AutoSwarmEnabled,
1368		AutoCompactThreshold:          initialCfg.AutoCompactThreshold,
1369		JailByDefault:                 initialCfg.JailByDefault,
1370		PowerShellEnabled:             initialCfg.PowerShellEnabled,
1371		ToolSelectionExplicit:         len(args.Tools) > 0,
1372		OpenRouterServerToolsEnabled:  initialCfg.OpenRouterServerToolsEnabled,
1373		OpenRouterServerToolCallLimit: initialCfg.OpenRouterServerToolCallLimit,
1374		NoTools:                       args.NoTools,
1375		QuickModelShortcuts:           quickModelShortcuts,
1376		Keymap:                        initialCfg.Keymap,
1377		RecursiveFileSuggest:          initialCfg.RecursiveFileSuggest,
1378		FuzzySkillSuggest:             initialCfg.FuzzySkillSuggest,
1379		RespectGitignore:              initialCfg.RespectGitignore,
1380		CompactMode:                   initialCfg.CompactMode,
1381		CollapseToolCall:              initialCfg.CollapseToolCall,
1382		ChatTimestamps:                initialCfg.ChatTimestamps,
1383		ChatTimestampDate:             initialCfg.ChatTimestampDate,
1384		ChatTimestampIntervalMinutes:  initialCfg.ChatTimestampIntervalMinutes,
1385		TUIInputStyle:                 initialCfg.TUIInputStyle,
1386		TUIStatusPosition:             initialCfg.TUIStatusPosition,
1387		TUIWorkingPosition:            initialCfg.TUIWorkingPosition,
1388		ThemeName:                     initialCfg.Theme,
1389		FlatTools:                     initialCfg.FlatToolRender(),
1390		CompactUser:                   initialCfg.CompactUserInput(),
1391		ExtensionThemes:               extMgr.ThemeOptions,
1392		AutoSwarmSystemAddendum:       AutoSwarmSystemAddendum,
1393		SettingsStore:                 configSettingsStore{},
1394		Model:                         r.Model,
1395		Provider:                      r.Provider,
1396		AuthMethod:                    r.AuthMethod,
1397		BaseURL:                       r.BaseURL,
1398		Reasoning:                     r.Reasoning,
1399		SystemPrompt:                  r.SystemPrompt,
1400		Tools:                         r.ToolRegistry,
1401		MaxSteps:                      r.MaxSteps,
1402		CWD:                           r.CWD,
1403		StartupAgentName:              args.AgentName,
1404		StartupContextPaths:           instructionContextPaths(r.ContextFiles),
1405		StartupExtensionNames:         startupExtensionNames(extMgr.All()),
1406		StartupExtensionErrors:        startupExtensionErrors,
1407		StartupSkillNames:             startupSkillNames(startupSkills),
1408		ShowInstructionsAtStartup:     initialCfg.ShowInstructionsAtStartup,
1409		ZotHome:                       ZotHome(),
1410		SessionsRoot:                  agentSessionsRoot(ZotHome(), args),
1411		Version:                       version,
1412		UpdateInfoChan:                updateCh,
1413		Sandbox:                       sharedSandbox,
1414		Agent:                         ag,
1415		InitialInput:                  args.Prompt,
1416		StartupPre:                    args.StartupPre,
1417		OnStartupPreDone: func() {
1418			// entry.pre often installs skills/extensions; rediscover them
1419			// before the user starts a model turn.
1420			current := liveInteractiveAgent(iv, ag)
1421			if extMgr != nil {
1422				_ = extMgr.Reload(context.Background(), 2*time.Second)
1423			}
1424			if current != nil {
1425				refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, injectSwarmSpawn)
1426			}
1427		},
1428		AuthManager:                 mgr,
1429		LlamaCPPConfig:              ResolveLlamaCPPConfig,
1430		RefreshLlamaCPPModels:       RefreshLlamaCPPModels,
1431		RefreshLMStudioModels:       RefreshLMStudioModels,
1432		LMStudioConfigured:          LMStudioConfigured,
1433		RefreshCustomProviderModels: RefreshCustomProviderModels,
1434		CustomDiscoveryConfigured:   CustomDiscoveryConfigured,
1435		BuildAgent:                  buildAgent,
1436		SetKimiCLIFallbackDisabled:  SetKimiCLIFallbackDisabled,
1437		BuildAgentFor:               buildAgentFor,
1438		BuildAgentForRescue:         buildAgentForRescue,
1439		LoggedInProviders: func() []string {
1440			var out []string
1441			seen := map[string]bool{}
1442			for _, p := range knownProviders {
1443				if CredentialAvailable(p) && !seen[p] {
1444					out = append(out, p)
1445					seen[p] = true
1446				}
1447			}
1448			// Include custom providers that have credentials stored.
1449			for p := range provider.CustomProviders() {
1450				if CredentialAvailable(p) && !seen[p] {
1451					out = append(out, p)
1452					seen[p] = true
1453				}
1454			}
1455			// Ollama models are always available (no auth needed).
1456			if !seen["ollama"] {
1457				out = append(out, "ollama")
1458			}
1459			return out
1460		},
1461		NewSession:  newSession,
1462		LoadSession: loadSession,
1463		ChangeCWD:   changeCWD,
1464		CurrentSessionPath: func() string {
1465			if sess == nil {
1466				return ""
1467			}
1468			return sess.Path
1469		},
1470		FlushSession: func() {
1471			// Append any not-yet-persisted agent messages to the
1472			// current session file, then advance the baseline so
1473			// the final WriteNewTranscript at exit doesn't write
1474			// duplicates. Per-message persistence keeps the on-
1475			// disk file current already, so this is mostly a
1476			// defensive flush — still needed for /session export
1477			// to guarantee the exported bytes include the very
1478			// last in-flight turn.
1479			currentAg := iv.Agent()
1480			if currentAg == nil {
1481				return
1482			}
1483			persistMu.Lock()
1484			defer persistMu.Unlock()
1485			if sess == nil {
1486				return
1487			}
1488			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1489			sessBaselineMsgs = len(currentAg.Messages())
1490		},
1491		Extensions:    extMgr,
1492		Swarm:         swarmMgr,
1493		ChangelogChan: changelogCh,
1494		OnChangelogDismiss: func() {
1495			// For dev builds (0.0.0) store the actual release version
1496			// so the same changelog doesn't show again next launch.
1497			// For real builds, store the binary version.
1498			v := version
1499			if v == "0.0.0" {
1500				if iv != nil && iv.ChangelogVersion() != "" {
1501					v = iv.ChangelogVersion()
1502				}
1503			}
1504			_ = MarkChangelogShown(v)
1505		},
1506		PreloadPinnedSkills: freshSession && !args.NoSkill,
1507		LoadSkillPins: func(cwd string) (skills.Pins, error) {
1508			if args.NoSkill {
1509				return skills.Pins{}, nil
1510			}
1511			return loadSkillPins(cwd)
1512		},
1513		ToggleSkillPin: toggleSkillPin,
1514		SkillSnapshot: func() []*skills.Skill {
1515			return userSkillSnapshot(args)
1516		},
1517		NoYolo:      args.NoYolo,
1518		ConfirmGate: confirmGate,
1519		OnReasoningChanged: func(level string) {
1520			r.Reasoning = level
1521			setZotSessionEnvironment(r, sess)
1522		},
1523		PersistModel: func(providerName, model string) {
1524			// Update config.json so next launch uses the same pick.
1525			cfg, _ := LoadConfig()
1526			cfg.Provider = providerName
1527			cfg.Model = model
1528			_ = SaveConfig(cfg)
1529			// Update the active session's meta so resume picks this up.
1530			if sess != nil {
1531				_ = sess.UpdateModel(providerName, model)
1532			}
1533			r.Provider = providerName
1534			r.Model = model
1535			setZotSessionEnvironment(r, sess)
1536		},
1537	})
1538
1539	// Bind the interactive TUI as the Confirmer. We deferred this
1540	// until now because the gate is constructed before the TUI
1541	// (the BeforeToolExecute closure captures it). SetConfirmer
1542	// is mutex-guarded on the gate so this is safe.
1543	if confirmGate != nil {
1544		confirmGate.SetConfirmer(&confirmationEventConfirmer{
1545			inner: iv,
1546			emit:  extMgr.EmitEvent,
1547		})
1548	}
1549
1550	// Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1551	// (closed terminal window, system shutdown, kill) used to lose
1552	// the entire in-memory transcript because the deferred post-Run
1553	// flush below never ran. Per-message persistence above covers
1554	// most of it; this handler writes any in-flight remainder and
1555	// then exits the process so we don't double-paint over a
1556	// broken terminal that the TUI's restore deferreds can no
1557	// longer fix from a signal context.
1558	//
1559	// SIGINT is intentionally NOT handled here — the TUI consumes
1560	// Ctrl+C as a regular key event for cancel/clear semantics, and
1561	// installing a SIGINT notifier here would swallow it.
1562	sigCh := make(chan os.Signal, 1)
1563	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1564	defer signal.Stop(sigCh)
1565	go func() {
1566		_, ok := <-sigCh
1567		if !ok {
1568			return
1569		}
1570		if finalAg := iv.Agent(); finalAg != nil {
1571			persistMu.Lock()
1572			if sess != nil {
1573				writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1574				sessBaselineMsgs = len(finalAg.Messages())
1575				_ = sess.Close()
1576				sess = nil
1577			}
1578			persistMu.Unlock()
1579		}
1580		// Exit cleanly. Re-raising the signal would skip os.Exit's
1581		// at-exit hooks; explicit exit is fine because we've already
1582		// flushed the only at-risk state (the session file).
1583		os.Exit(0)
1584	}()
1585
1586	runErr := iv.Run(ctx)
1587
1588	// Flush final transcript to session (only if we had / ended up with an agent).
1589	if finalAg := iv.Agent(); finalAg != nil {
1590		persistMu.Lock()
1591		if sess != nil {
1592			writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1593			sessBaselineMsgs = len(finalAg.Messages())
1594		}
1595		persistMu.Unlock()
1596	}
1597	return runErr
1598}
1599
1600func agentSessionsRoot(root string, args Args) string {
1601	if args.AgentName == "" {
1602		return root
1603	}
1604	return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
1605}
1606
1607// openOrCreateSession returns a session for the run. sess may be nil
1608// with a nil error if session persistence is disabled. When a session
1609// exists, its id is bound onto ag so providers can sticky-route.
1610func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1611	s, _, err := openOrCreateSessionState(args, r, ag, version)
1612	return s, err
1613}
1614
1615// The freshness result distinguishes an empty resumed session from a new one.
1616func openOrCreateSessionState(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, bool, error) {
1617	fresh := true
1618	if args.NoSess {
1619		setZotSessionEnvironment(r, nil)
1620		return nil, fresh, nil
1621	}
1622	// Sweep meta-only files left over from older zot versions (and from
1623	// any session that crashed before its first AppendMessage). Cheap;
1624	// reads the first few bytes of each file in the cwd's session dir.
1625	sessionsRoot := agentSessionsRoot(ZotHome(), args)
1626	core.PruneEmptySessions(sessionsRoot, args.CWD)
1627	var (
1628		s    *core.Session
1629		msgs []provider.Message
1630		err  error
1631	)
1632	switch {
1633	case args.Session != "":
1634		s, msgs, err = core.OpenSession(args.Session)
1635		fresh = false
1636		// The swarm-agent child passes a fixed --session path that
1637		// may not exist yet on first Spawn. Treat ENOENT as "create
1638		// a fresh session AT THIS PATH" so the conversation actually
1639		// gets persisted; without this fallback the swarm child runs
1640		// with sess==nil and every Resume re-starts with no memory
1641		// of the prior turns. Other openers (--continue / --resume /
1642		// the picker) never see ENOENT here because they only choose
1643		// paths that already exist on disk.
1644		if err != nil && errors.Is(err, os.ErrNotExist) {
1645			s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1646			fresh = true
1647			msgs = nil
1648		}
1649	case args.Continue:
1650		latest := core.LatestSession(sessionsRoot, args.CWD)
1651		if latest != "" {
1652			s, msgs, err = core.OpenSession(latest)
1653			fresh = false
1654		}
1655	case args.Resume:
1656		picked, perr := pickSession(sessionsRoot, args.CWD)
1657		if perr != nil {
1658			return nil, false, perr
1659		}
1660		if picked != "" {
1661			s, msgs, err = core.OpenSession(picked)
1662			fresh = false
1663		}
1664	}
1665	if err != nil {
1666		return nil, false, err
1667	}
1668	if s == nil {
1669		s, err = core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1670		if err != nil {
1671			return nil, false, err
1672		}
1673	} else {
1674		ag.SetMessages(msgs)
1675		if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1676			ag.SeedCost(cum)
1677			ag.SeedLastTurnUsage(last)
1678		}
1679	}
1680	bindAgentSession(ag, s)
1681	setZotSessionEnvironment(r, s)
1682	return s, fresh, nil
1683}
1684
1685// setZotSessionEnvironment publishes the non-secret runtime metadata that
1686// zot's child processes can use for attribution and diagnostics.
1687func setZotSessionEnvironment(r Resolved, sess *core.Session) {
1688	values := map[string]string{
1689		"ZOT_PROVIDER":        r.Provider,
1690		"ZOT_MODEL":           r.Model,
1691		"ZOT_REASONING_LEVEL": r.Reasoning,
1692	}
1693	if sess != nil {
1694		values["ZOT_SESSION_ID"] = sess.ID
1695		values["ZOT_SESSION_FILE"] = sess.Path
1696	}
1697	for _, name := range []string{"ZOT_SESSION_ID", "ZOT_SESSION_FILE", "ZOT_PROVIDER", "ZOT_MODEL", "ZOT_REASONING_LEVEL"} {
1698		if value := values[name]; value != "" {
1699			_ = os.Setenv(name, value)
1700		} else {
1701			_ = os.Unsetenv(name)
1702		}
1703	}
1704}
1705
1706func pickSession(root, cwd string) (string, error) {
1707	files := core.ListSessions(root, cwd)
1708	if len(files) == 0 {
1709		fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1710		return "", nil
1711	}
1712	for i, f := range files {
1713		fmt.Fprintf(os.Stderr, "  %2d) %s\n", i+1, f)
1714	}
1715	fmt.Fprint(os.Stderr, "pick #: ")
1716	rd := bufio.NewReader(os.Stdin)
1717	line, _ := rd.ReadString('\n')
1718	line = strings.TrimSpace(line)
1719	var n int
1720	if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1721		return "", fmt.Errorf("invalid selection")
1722	}
1723	return files[n-1], nil
1724}
1725
1726// rotateInteractiveSession creates the replacement before mutating the live
1727// agent, so a creation failure leaves the current conversation usable.
1728// Callers must hold the interactive persistence mutex.
1729func rotateInteractiveSession(root, cwd, providerName, model, version string, ag *core.Agent, old *core.Session, baseline int) (*core.Session, error) {
1730	if ag == nil {
1731		return nil, fmt.Errorf("no agent running")
1732	}
1733	fresh, err := core.NewSession(root, cwd, providerName, model, version)
1734	if err != nil {
1735		return nil, err
1736	}
1737	if old != nil {
1738		writeNewTranscriptLocked(ag, old, baseline)
1739		_ = old.Close()
1740	}
1741	ag.SetMessages(nil)
1742	ag.DrainQueuedMessages()
1743	ag.SeedCost(provider.Usage{})
1744	ag.SeedLastTurnUsage(provider.Usage{})
1745	bindAgentSession(ag, fresh)
1746	return fresh, nil
1747}
1748
1749// WriteNewTranscript appends only messages after index `from` from the
1750// agent's transcript to the session. Used by callers that don't hold
1751// the persistMu (non-interactive print/json modes which run a single
1752// turn under their own goroutine).
1753func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1754	writeNewTranscriptLocked(ag, sess, from)
1755}
1756
1757// bindAgentSession stamps the zot session id onto the agent so providers
1758// that support sticky routing (OpenRouter session_id) can reuse it.
1759// No-op when persistence is disabled.
1760func bindAgentSession(ag *core.Agent, sess *core.Session) {
1761	if ag == nil || sess == nil {
1762		return
1763	}
1764	ag.SessionID = sess.ID
1765}
1766
1767// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1768// suffix marks that interactive callers must hold persistMu when
1769// invoking it so concurrent appends from the agent loop don't race
1770// with this catch-up flush.
1771func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1772	if sess == nil || ag == nil {
1773		return
1774	}
1775	msgs := ag.Messages()
1776	for i := from; i < len(msgs); i++ {
1777		_ = sess.AppendMessage(msgs[i])
1778	}
1779	cum := ag.Cost()
1780	_ = sess.AppendUsage(cum, cum)
1781}
1782
1783func argsForStdin(rawArgs []string, mode os.FileMode) []string {
1784	if mode&os.ModeCharDevice != 0 {
1785		return rawArgs
1786	}
1787	return append([]string{"--print"}, rawArgs...)
1788}
1789
1790func combinePromptInput(stdin, positional string) string {
1791	parts := make([]string, 0, 2)
1792	if stdin = strings.TrimSpace(stdin); stdin != "" {
1793		parts = append(parts, stdin)
1794	}
1795	if positional = strings.TrimSpace(positional); positional != "" {
1796		parts = append(parts, positional)
1797	}
1798	return strings.Join(parts, "\n")
1799}
1800
1801func readAllStdin() (string, error) {
1802	fi, err := os.Stdin.Stat()
1803	if err != nil {
1804		return "", err
1805	}
1806	if (fi.Mode() & os.ModeCharDevice) != 0 {
1807		return "", nil
1808	}
1809	b, err := io.ReadAll(os.Stdin)
1810	return string(b), err
1811}
1812
1813func printModels() {
1814	models := provider.Active()
1815
1816	// Compute column widths from actual data so wide providers (e.g.
1817	// xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1818	// `name` column off-screen. Floors mirror the historical layout so
1819	// short catalogs look the same as before.
1820	provW, idW, srcW := len("provider"), len("model id"), len("source")
1821	for _, m := range models {
1822		if w := len(m.Provider); w > provW {
1823			provW = w
1824		}
1825		if w := len(m.ID); w > idW {
1826			idW = w
1827		}
1828		source := m.Source
1829		if source == "" {
1830			source = "catalog"
1831		}
1832		if m.Speculative {
1833			source = "speculative"
1834		}
1835		if w := len(source); w > srcW {
1836			srcW = w
1837		}
1838	}
1839
1840	header := fmt.Sprintf("%-*s  %-*s  %8s  %8s  %s  %-*s  %s",
1841		provW, "provider",
1842		idW, "model id",
1843		"context", "max-out", "reasoning",
1844		srcW, "source",
1845		"name")
1846	fmt.Println(header)
1847
1848	for _, m := range models {
1849		reason := " "
1850		if m.Reasoning {
1851			reason = "✓"
1852		}
1853		source := m.Source
1854		if source == "" {
1855			source = "catalog"
1856		}
1857		if m.Speculative {
1858			source = "speculative"
1859		}
1860		fmt.Printf("%-*s  %-*s  %8d  %8d     %s      %-*s  %s\n",
1861			provW, m.Provider,
1862			idW, m.ID,
1863			m.ContextWindow, m.MaxOutput,
1864			reason,
1865			srcW, source,
1866			m.DisplayName)
1867	}
1868}

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