v0.3.2 6af4e0f

cli.go RawHistoryFolder

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

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