v0.3.8 210ef98

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			startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZotHome()))
894			iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
895		}
896
897		// Re-scope the swarm dashboard to the new session.
898		if swarmMgr != nil && sess != nil {
899			swarmMgr.SetActiveSession(sess.ID)
900		}
901		return nil
902	}
903
904	term := tui.NewProcTerm()
905
906	// Kick off the async update check so the banner can appear when the
907	// http response eventually arrives (usually <1s on cached DNS). Map
908	// agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
909	updateCh := make(chan modes.UpdateInfo, 1)
910	go func() {
911		defer close(updateCh)
912		src := <-CheckForUpdateAsync(ZotHome(), version)
913		updateCh <- modes.UpdateInfo{
914			Current:   src.Current,
915			Latest:    src.Latest,
916			Available: src.Available,
917			URL:       src.URL,
918		}
919	}()
920
921	// Changelog: when the running version differs from the last
922	// version whose release notes the user dismissed, fetch the
923	// release body from GitHub and have the TUI show it once. On
924	// first-ever launch (no prior LastChangelogShown), seed the
925	// stored version silently — don't dump release notes at someone
926	// who just installed.
927	changelogCh := make(chan modes.ChangelogPayload, 1)
928	go func() {
929		defer close(changelogCh)
930		cfg, _ := LoadConfig()
931		if cfg.LastChangelogShown == "" {
932			SeedChangelogVersion(version)
933			return
934		}
935		if !ShouldShowChangelog(version, cfg) {
936			return
937		}
938		info := <-FetchChangelogAsync(version)
939		if info.Body == "" {
940			return
941		}
942		// For dev builds (0.0.0), skip if the latest release was
943		// already shown (stored by the dismiss callback).
944		if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
945			return
946		}
947		changelogCh <- modes.ChangelogPayload{
948			Version: info.Version,
949			Body:    info.Body,
950			URL:     info.URL,
951		}
952	}()
953
954	initialCfg, _ := LoadConfig()
955	quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
956	for idx, s := range initialCfg.QuickModelShortcuts {
957		quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
958	}
959	theme, _, themeErr := tui.DetectThemeWithCustom(ZotHome(), initialCfg.Theme, 80*time.Millisecond)
960	if themeErr != nil {
961		fmt.Fprintln(os.Stderr, "theme load:", themeErr)
962		if initialCfg.Theme != "" && !tui.ThemeExists(ZotHome(), initialCfg.Theme) {
963			initialCfg.Theme = ""
964			_ = SaveConfig(initialCfg)
965		}
966	}
967
968	// swarmMgr was constructed and reloaded earlier (before the agent
969	// build, so the auto-swarm tool could capture it). Here we just
970	// scope the dashboard to the active host session so /swarm only
971	// shows agents this session spawned (and any pre-upgrade unscoped
972	// agents — see SnapshotAll docs). Updated again whenever the
973	// user swaps sessions via loadSession below.
974	if sess != nil {
975		swarmMgr.SetActiveSession(sess.ID)
976	}
977	// Best-effort shutdown on interactive exit: stop all running
978	// agents so they don't outlive their parent zot.
979	defer swarmMgr.StopAll()
980
981	var startupSkills []*skills.Skill
982	if r.SkillTool != nil {
983		startupSkills = r.SkillTool.Skills()
984	}
985
986	iv = modes.NewInteractive(modes.InteractiveConfig{
987		Terminal:                   term,
988		Theme:                      theme,
989		InlineImagesEnabled:        initialCfg.InlineImagesEnabled,
990		AutoSwarmEnabled:           initialCfg.AutoSwarmEnabled,
991		JailByDefault:              initialCfg.JailByDefault,
992		QuickModelShortcuts:        quickModelShortcuts,
993		RecursiveFileSuggest:       initialCfg.RecursiveFileSuggest,
994		RespectGitignore:           initialCfg.RespectGitignore,
995		CompactMode:                initialCfg.CompactMode,
996		TUIInputStyle:              initialCfg.TUIInputStyle,
997		TUIStatusPosition:          initialCfg.TUIStatusPosition,
998		TUIWorkingPosition:         initialCfg.TUIWorkingPosition,
999		ThemeName:                  initialCfg.Theme,
1000		FlatTools:                  initialCfg.FlatToolRender(),
1001		CompactUser:                initialCfg.CompactUserInput(),
1002		ExtensionThemes:            extMgr.ThemeOptions,
1003		AutoSwarmSystemAddendum:    AutoSwarmSystemAddendum,
1004		SettingsStore:              configSettingsStore{},
1005		Model:                      r.Model,
1006		Provider:                   r.Provider,
1007		AuthMethod:                 r.AuthMethod,
1008		BaseURL:                    r.BaseURL,
1009		Reasoning:                  r.Reasoning,
1010		SystemPrompt:               r.SystemPrompt,
1011		Tools:                      r.ToolRegistry,
1012		MaxSteps:                   r.MaxSteps,
1013		CWD:                        r.CWD,
1014		StartupContextPaths:        instructionContextPaths(r.ContextFiles),
1015		StartupExtensionNames:      startupExtensionNames(extMgr.All()),
1016		StartupSkillNames:          startupSkillNames(startupSkills),
1017		ShowInstructionsAtStartup:  initialCfg.ShowInstructionsAtStartup,
1018		ZotHome:                    ZotHome(),
1019		Version:                    version,
1020		UpdateInfoChan:             updateCh,
1021		Sandbox:                    sharedSandbox,
1022		Agent:                      ag,
1023		InitialInput:               args.Prompt,
1024		AuthManager:                mgr,
1025		LlamaCPPConfig:             ResolveLlamaCPPConfig,
1026		RefreshLlamaCPPModels:      RefreshLlamaCPPModels,
1027		BuildAgent:                 buildAgent,
1028		SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
1029		BuildAgentFor:              buildAgentFor,
1030		BuildAgentForRescue:        buildAgentForRescue,
1031		LoggedInProviders: func() []string {
1032			var out []string
1033			seen := map[string]bool{}
1034			for _, p := range knownProviders {
1035				if CredentialAvailable(p) && !seen[p] {
1036					out = append(out, p)
1037					seen[p] = true
1038				}
1039			}
1040			// Include custom providers that have credentials stored.
1041			for p := range provider.CustomProviders() {
1042				if CredentialAvailable(p) && !seen[p] {
1043					out = append(out, p)
1044					seen[p] = true
1045				}
1046			}
1047			// Ollama models are always available (no auth needed).
1048			if !seen["ollama"] {
1049				out = append(out, "ollama")
1050			}
1051			return out
1052		},
1053		LoadSession: loadSession,
1054		ChangeCWD:   changeCWD,
1055		CurrentSessionPath: func() string {
1056			if sess == nil {
1057				return ""
1058			}
1059			return sess.Path
1060		},
1061		FlushSession: func() {
1062			// Append any not-yet-persisted agent messages to the
1063			// current session file, then advance the baseline so
1064			// the final WriteNewTranscript at exit doesn't write
1065			// duplicates. Per-message persistence keeps the on-
1066			// disk file current already, so this is mostly a
1067			// defensive flush — still needed for /session export
1068			// to guarantee the exported bytes include the very
1069			// last in-flight turn.
1070			currentAg := iv.Agent()
1071			if currentAg == nil {
1072				return
1073			}
1074			persistMu.Lock()
1075			defer persistMu.Unlock()
1076			if sess == nil {
1077				return
1078			}
1079			writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
1080			sessBaselineMsgs = len(currentAg.Messages())
1081		},
1082		Extensions:    extMgr,
1083		Swarm:         swarmMgr,
1084		ChangelogChan: changelogCh,
1085		OnChangelogDismiss: func() {
1086			// For dev builds (0.0.0) store the actual release version
1087			// so the same changelog doesn't show again next launch.
1088			// For real builds, store the binary version.
1089			v := version
1090			if v == "0.0.0" {
1091				if iv != nil && iv.ChangelogVersion() != "" {
1092					v = iv.ChangelogVersion()
1093				}
1094			}
1095			_ = MarkChangelogShown(v)
1096		},
1097		SkillSnapshot: func() []*skills.Skill {
1098			if args.NoSkill {
1099				// --no-skill: nothing for the picker to show.
1100				return nil
1101			}
1102			// Re-discover so the picker reflects edits made during
1103			// the session. Cheap; SKILL.md files are small. Filter
1104			// out built-in skills — they're hidden from user-facing
1105			// surfaces because they're implementation detail; the
1106			// model still sees them through the system-prompt
1107			// manifest and the skill tool.
1108			userHome, _ := os.UserHomeDir()
1109			list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
1110			return skills.VisibleSkills(list)
1111		},
1112		NoYolo:      args.NoYolo,
1113		ConfirmGate: confirmGate,
1114		PersistModel: func(providerName, model string) {
1115			// Update config.json so next launch uses the same pick.
1116			cfg, _ := LoadConfig()
1117			cfg.Provider = providerName
1118			cfg.Model = model
1119			_ = SaveConfig(cfg)
1120			// Update the active session's meta so resume picks this up.
1121			if sess != nil {
1122				_ = sess.UpdateModel(providerName, model)
1123			}
1124		},
1125	})
1126
1127	// Bind the interactive TUI as the Confirmer. We deferred this
1128	// until now because the gate is constructed before the TUI
1129	// (the BeforeToolExecute closure captures it). SetConfirmer
1130	// is mutex-guarded on the gate so this is safe.
1131	if confirmGate != nil {
1132		confirmGate.SetConfirmer(iv)
1133	}
1134
1135	// Signal-driven flush: a SIGTERM / SIGHUP to the zot process
1136	// (closed terminal window, system shutdown, kill) used to lose
1137	// the entire in-memory transcript because the deferred post-Run
1138	// flush below never ran. Per-message persistence above covers
1139	// most of it; this handler writes any in-flight remainder and
1140	// then exits the process so we don't double-paint over a
1141	// broken terminal that the TUI's restore deferreds can no
1142	// longer fix from a signal context.
1143	//
1144	// SIGINT is intentionally NOT handled here — the TUI consumes
1145	// Ctrl+C as a regular key event for cancel/clear semantics, and
1146	// installing a SIGINT notifier here would swallow it.
1147	sigCh := make(chan os.Signal, 1)
1148	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
1149	defer signal.Stop(sigCh)
1150	go func() {
1151		_, ok := <-sigCh
1152		if !ok {
1153			return
1154		}
1155		if finalAg := iv.Agent(); finalAg != nil {
1156			persistMu.Lock()
1157			if sess != nil {
1158				writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1159				sessBaselineMsgs = len(finalAg.Messages())
1160				_ = sess.Close()
1161				sess = nil
1162			}
1163			persistMu.Unlock()
1164		}
1165		// Exit cleanly. Re-raising the signal would skip os.Exit's
1166		// at-exit hooks; explicit exit is fine because we've already
1167		// flushed the only at-risk state (the session file).
1168		os.Exit(0)
1169	}()
1170
1171	runErr := iv.Run(ctx)
1172
1173	// Flush final transcript to session (only if we had / ended up with an agent).
1174	if finalAg := iv.Agent(); finalAg != nil {
1175		persistMu.Lock()
1176		if sess != nil {
1177			writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
1178			sessBaselineMsgs = len(finalAg.Messages())
1179		}
1180		persistMu.Unlock()
1181	}
1182	return runErr
1183}
1184
1185func agentSessionsRoot(root string, args Args) string {
1186	if args.AgentName == "" {
1187		return root
1188	}
1189	return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
1190}
1191
1192// openOrCreateSession returns a session for the run. sess may be nil
1193// with a nil error if session persistence is disabled.
1194func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
1195	if args.NoSess {
1196		return nil, nil
1197	}
1198	// Sweep meta-only files left over from older zot versions (and from
1199	// any session that crashed before its first AppendMessage). Cheap;
1200	// reads the first few bytes of each file in the cwd's session dir.
1201	sessionsRoot := agentSessionsRoot(ZotHome(), args)
1202	core.PruneEmptySessions(sessionsRoot, args.CWD)
1203	var (
1204		s    *core.Session
1205		msgs []provider.Message
1206		err  error
1207	)
1208	switch {
1209	case args.Session != "":
1210		s, msgs, err = core.OpenSession(args.Session)
1211		// The swarm-agent child passes a fixed --session path that
1212		// may not exist yet on first Spawn. Treat ENOENT as "create
1213		// a fresh session AT THIS PATH" so the conversation actually
1214		// gets persisted; without this fallback the swarm child runs
1215		// with sess==nil and every Resume re-starts with no memory
1216		// of the prior turns. Other openers (--continue / --resume /
1217		// the picker) never see ENOENT here because they only choose
1218		// paths that already exist on disk.
1219		if err != nil && errors.Is(err, os.ErrNotExist) {
1220			s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
1221			msgs = nil
1222		}
1223	case args.Continue:
1224		latest := core.LatestSession(sessionsRoot, args.CWD)
1225		if latest != "" {
1226			s, msgs, err = core.OpenSession(latest)
1227		}
1228	case args.Resume:
1229		picked, perr := pickSession(sessionsRoot, args.CWD)
1230		if perr != nil {
1231			return nil, perr
1232		}
1233		if picked != "" {
1234			s, msgs, err = core.OpenSession(picked)
1235		}
1236	}
1237	if err != nil {
1238		return nil, err
1239	}
1240	if s != nil {
1241		ag.SetMessages(msgs)
1242		if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
1243			ag.SeedCost(cum)
1244			ag.SeedLastTurnUsage(last)
1245		}
1246		return s, nil
1247	}
1248	return core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
1249}
1250
1251func pickSession(root, cwd string) (string, error) {
1252	files := core.ListSessions(root, cwd)
1253	if len(files) == 0 {
1254		fmt.Fprintln(os.Stderr, "no sessions for", cwd)
1255		return "", nil
1256	}
1257	for i, f := range files {
1258		fmt.Fprintf(os.Stderr, "  %2d) %s\n", i+1, f)
1259	}
1260	fmt.Fprint(os.Stderr, "pick #: ")
1261	rd := bufio.NewReader(os.Stdin)
1262	line, _ := rd.ReadString('\n')
1263	line = strings.TrimSpace(line)
1264	var n int
1265	if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
1266		return "", fmt.Errorf("invalid selection")
1267	}
1268	return files[n-1], nil
1269}
1270
1271// WriteNewTranscript appends only messages after index `from` from the
1272// agent's transcript to the session. Used by callers that don't hold
1273// the persistMu (non-interactive print/json modes which run a single
1274// turn under their own goroutine).
1275func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
1276	writeNewTranscriptLocked(ag, sess, from)
1277}
1278
1279// writeNewTranscriptLocked is the same as WriteNewTranscript. The
1280// suffix marks that interactive callers must hold persistMu when
1281// invoking it so concurrent appends from the agent loop don't race
1282// with this catch-up flush.
1283func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) {
1284	if sess == nil || ag == nil {
1285		return
1286	}
1287	msgs := ag.Messages()
1288	for i := from; i < len(msgs); i++ {
1289		_ = sess.AppendMessage(msgs[i])
1290	}
1291	cum := ag.Cost()
1292	_ = sess.AppendUsage(cum, cum)
1293}
1294
1295func readAllStdin() (string, error) {
1296	fi, err := os.Stdin.Stat()
1297	if err != nil {
1298		return "", err
1299	}
1300	if (fi.Mode() & os.ModeCharDevice) != 0 {
1301		return "", nil
1302	}
1303	b, err := io.ReadAll(os.Stdin)
1304	return string(b), err
1305}
1306
1307func printModels() {
1308	models := provider.Active()
1309
1310	// Compute column widths from actual data so wide providers (e.g.
1311	// xiaomi-token-plan-sgp) and long bedrock model ids don't force the
1312	// `name` column off-screen. Floors mirror the historical layout so
1313	// short catalogs look the same as before.
1314	provW, idW, srcW := len("provider"), len("model id"), len("source")
1315	for _, m := range models {
1316		if w := len(m.Provider); w > provW {
1317			provW = w
1318		}
1319		if w := len(m.ID); w > idW {
1320			idW = w
1321		}
1322		source := m.Source
1323		if source == "" {
1324			source = "catalog"
1325		}
1326		if m.Speculative {
1327			source = "speculative"
1328		}
1329		if w := len(source); w > srcW {
1330			srcW = w
1331		}
1332	}
1333
1334	header := fmt.Sprintf("%-*s  %-*s  %8s  %8s  %s  %-*s  %s",
1335		provW, "provider",
1336		idW, "model id",
1337		"context", "max-out", "reasoning",
1338		srcW, "source",
1339		"name")
1340	fmt.Println(header)
1341
1342	for _, m := range models {
1343		reason := " "
1344		if m.Reasoning {
1345			reason = "✓"
1346		}
1347		source := m.Source
1348		if source == "" {
1349			source = "catalog"
1350		}
1351		if m.Speculative {
1352			source = "speculative"
1353		}
1354		fmt.Printf("%-*s  %-*s  %8d  %8d     %s      %-*s  %s\n",
1355			provW, m.Provider,
1356			idW, m.ID,
1357			m.ContextWindow, m.MaxOutput,
1358			reason,
1359			srcW, source,
1360			m.DisplayName)
1361	}
1362}

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 477

↑↓ moveenter openesc close