v0.3.26 b289bf6

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

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