v0.3.12 999d53a

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

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