v0.1.18 9afd123

cli.go RawHistoryFolder

1package agent
2
3import (
4	"bufio"
5	"context"
6	"encoding/json"
7	"fmt"
8	"io"
9	"os"
10	"strings"
11	"time"
12
13	"github.com/patriceckhart/zot/internal/agent/extensions"
14	"github.com/patriceckhart/zot/internal/agent/modes"
15	"github.com/patriceckhart/zot/internal/auth"
16	"github.com/patriceckhart/zot/internal/core"
17	"github.com/patriceckhart/zot/internal/extproto"
18	"github.com/patriceckhart/zot/internal/provider"
19	"github.com/patriceckhart/zot/internal/skills"
20	"github.com/patriceckhart/zot/internal/tui"
21)
22
23// interactiveExtHooks is a tiny adapter that lets the extension
24// manager call back into the Interactive instance built later in
25// runInteractive. The forward-declared *modes.Interactive is filled
26// in immediately after manager construction.
27type interactiveExtHooks struct {
28	ivPtr **modes.Interactive
29}
30
31func (h *interactiveExtHooks) iv() *modes.Interactive {
32	if h == nil || h.ivPtr == nil {
33		return nil
34	}
35	return *h.ivPtr
36}
37
38func (h *interactiveExtHooks) Notify(extName, level, message string) {
39	if iv := h.iv(); iv != nil {
40		iv.Notify(extName, level, message)
41	}
42}
43func (h *interactiveExtHooks) Submit(text string) {
44	if iv := h.iv(); iv != nil {
45		iv.Submit(text)
46	}
47}
48func (h *interactiveExtHooks) Insert(text string) {
49	if iv := h.iv(); iv != nil {
50		iv.Insert(text)
51	}
52}
53func (h *interactiveExtHooks) Display(extName, text string) {
54	if iv := h.iv(); iv != nil {
55		iv.Display(extName, text)
56	}
57}
58func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
59	if iv := h.iv(); iv != nil {
60		iv.OpenPanel(extName, spec)
61	}
62}
63func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
64	if iv := h.iv(); iv != nil {
65		iv.UpdatePanel(extName, panelID, title, lines, footer)
66	}
67}
68func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
69	if iv := h.iv(); iv != nil {
70		iv.ClosePanel(extName, panelID)
71	}
72}
73
74// extToolAdapter bridges *extensions.Manager to the
75// ExtensionToolSource interface declared in build.go (kept narrow to
76// avoid a build->extensions import cycle). One adapter instance per
77// run; used at every Resolve point so re-built agents pick up the
78// same set of extension tools.
79type extToolAdapter struct {
80	mgr *extensions.Manager
81}
82
83func (a *extToolAdapter) Tools() []ExtensionToolInfo {
84	infos := a.mgr.Tools()
85	out := make([]ExtensionToolInfo, len(infos))
86	for i, t := range infos {
87		out[i] = ExtensionToolInfo{
88			Extension:   t.Extension,
89			Name:        t.Name,
90			Description: t.Description,
91			Schema:      t.Schema,
92		}
93	}
94	return out
95}
96
97func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
98	return extensions.NewTool(a.mgr, extensions.ToolInfo{
99		Extension:   info.Extension,
100		Name:        info.Name,
101		Description: info.Description,
102		Schema:      info.Schema,
103	})
104}
105
106// fanoutAgentEvent translates a core.AgentEvent into the wire-format
107// EventFromHost and pushes it through the extension manager. Only
108// the events that have a clear extension-facing meaning are
109// forwarded; internal-only ones (text_delta, tool_progress) are
110// dropped to keep the per-extension stream sane.
111func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
112	if mgr == nil {
113		return
114	}
115	switch e := ev.(type) {
116	case core.EvTurnStart:
117		mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
118	case core.EvToolCall:
119		mgr.EmitEvent(extproto.EventFromHost{
120			Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
121		})
122	case core.EvAssistantMessage:
123		// Concat the visible text portions of the message; binary
124		// blocks (tool_use, etc.) are skipped because subscribers
125		// usually want a string they can grep / display.
126		var text string
127		for _, c := range e.Message.Content {
128			if tb, ok := c.(provider.TextBlock); ok {
129				text += tb.Text
130			}
131		}
132		mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
133	case core.EvTurnEnd:
134		ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
135		if e.Err != nil {
136			ev.Error = e.Err.Error()
137		}
138		mgr.EmitEvent(ev)
139	}
140}
141
142// Run is the top-level entrypoint for the zot binary.
143func Run(rawArgs []string, version string) error {
144	// Subcommand router: `zot bot ...` is handled separately so the
145	// generic flag parser doesn't reject "bot" as a positional arg.
146	if handled, err := runBotCommand(rawArgs, version); handled {
147		return err
148	}
149	if handled, err := runExtCommand(rawArgs); handled {
150		return err
151	}
152	// `zot rpc` is shorthand for `zot --rpc` so third-party apps can
153	// spawn the binary with a clean argv. Strip the leading 'rpc'
154	// token and let the rest flow through the normal arg parser.
155	if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
156		rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
157	}
158
159	args, err := ParseArgs(rawArgs)
160	if err != nil {
161		PrintHelp(version)
162		return err
163	}
164	if args.Help {
165		PrintHelp(version)
166		return nil
167	}
168	if args.Version {
169		fmt.Println("zot", version)
170		return nil
171	}
172	// Model catalog: load any cached discovery data before we inspect
173	// the model list (list-models, print/json, interactive).
174	LoadCachedModels()
175	LoadUserModels()
176
177	if args.ListModels {
178		printModels()
179		return nil
180	}
181
182	ctx := context.Background()
183
184	// Kick an async refresh of the live model catalog. The first run of
185	// zot hits the network; subsequent runs within CacheTTL do nothing.
186	RefreshModelsAsync()
187
188	switch args.Mode {
189	case ModePrint:
190		return runPrintMode(ctx, args, version)
191	case ModeJSON:
192		return runJSONMode(ctx, args, version)
193	case ModeRPC:
194		return runRPCMode(ctx, args, version)
195	default:
196		return runInteractive(ctx, args, version)
197	}
198}
199
200// ---- print / json modes: require credentials, run single-shot ----
201
202// nonInteractiveExtHooks is the HostHooks impl used by print / json
203// modes. They have no TUI, so notify / display go to stderr and
204// submit / insert are no-ops (the extension can't steer a
205// single-shot run once it's in flight anyway).
206type nonInteractiveExtHooks struct{}
207
208func (nonInteractiveExtHooks) Notify(ext, level, message string) {
209	fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
210}
211func (nonInteractiveExtHooks) Submit(string)                                        {}
212func (nonInteractiveExtHooks) Insert(string)                                        {}
213func (nonInteractiveExtHooks) Display(string, string)                               {}
214func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec)                 {}
215func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
216func (nonInteractiveExtHooks) ClosePanel(string, string)                            {}
217
218// setupNonInteractiveExtensions loads --ext paths and (unless
219// --no-ext) runs discovery. Returns the manager so the caller can
220// wire tools into the resolved registry, and a cleanup closure to
221// defer. Mirrors the interactive-mode setup minus the TUI hooks.
222func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
223	extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
224	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
225		fmt.Fprintln(os.Stderr, "extension load:", e)
226	}
227	if !args.NoExt {
228		for _, e := range extMgr.Discover(ctx) {
229			fmt.Fprintln(os.Stderr, "extension load:", e)
230		}
231	}
232	extMgr.WaitForReady(3 * time.Second)
233	r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
234	extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
235	return extMgr, func() { extMgr.Stop(2 * time.Second) }
236}
237
238// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
239// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
240// interactive path wires up, so extensions get their normal
241// event-intercept surface in print / json / rpc flows too.
242func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
243	if ag == nil || extMgr == nil {
244		return
245	}
246	ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
247		res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
248		if res.Block {
249			return false, res.Reason, nil
250		}
251		return true, "", res.ModifiedArgs
252	}
253	ag.BeforeTurn = func(step int) (bool, string) {
254		res := extMgr.InterceptTurnStart(ctx, step)
255		return !res.Block, res.Reason
256	}
257	ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
258		res := extMgr.InterceptAssistantMessage(ctx, text)
259		if res.Block {
260			return false, res.Reason, ""
261		}
262		return true, "", res.ReplaceText
263	}
264	ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
265}
266
267func runPrintMode(ctx context.Context, args Args, version string) error {
268	if args.NoYolo {
269		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
270	}
271	r, err := Resolve(args, true)
272	if err != nil {
273		return err
274	}
275	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
276	defer stopExt()
277
278	ag := r.NewAgent()
279	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
280	sess, _ := openOrCreateSession(args, r, ag, version)
281	defer sess.Close()
282
283	prompt := args.Prompt
284	if prompt == "" {
285		piped, _ := readAllStdin()
286		prompt = strings.TrimSpace(piped)
287	}
288	if prompt == "" {
289		return fmt.Errorf("print mode requires a prompt (arg or stdin)")
290	}
291
292	start := len(ag.Messages())
293	err = modes.RunPrint(ctx, ag, prompt, nil, os.Stdout)
294	WriteNewTranscript(ag, sess, start)
295	return err
296}
297
298func runJSONMode(ctx context.Context, args Args, version string) error {
299	if args.NoYolo {
300		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
301	}
302	r, err := Resolve(args, true)
303	if err != nil {
304		return err
305	}
306	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
307	defer stopExt()
308
309	ag := r.NewAgent()
310	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
311	sess, _ := openOrCreateSession(args, r, ag, version)
312	defer sess.Close()
313
314	prompt := args.Prompt
315	if prompt == "" {
316		piped, _ := readAllStdin()
317		prompt = strings.TrimSpace(piped)
318	}
319	if prompt == "" {
320		return fmt.Errorf("json mode requires a prompt (arg or stdin)")
321	}
322
323	start := len(ag.Messages())
324	err = modes.RunJSON(ctx, ag, prompt, nil, os.Stdout)
325	WriteNewTranscript(ag, sess, start)
326	return err
327}
328
329// ---- interactive mode: opens the TUI even without credentials ----
330
331func runInteractive(ctx context.Context, args Args, version string) error {
332	// Resolve WITHOUT requiring credentials.
333	r, err := Resolve(args, false)
334	if err != nil {
335		return err
336	}
337
338	authStore := AuthStoreFor()
339	mgr := auth.NewManager(authStore)
340	defer mgr.Close()
341
342	// Keep the sandbox pointer stable across agent rebuilds (login / model
343	// switch). The Interactive UI toggles the lock via this pointer, and
344	// rebuilt tool instances must share the same one so the lock sticks.
345	sharedSandbox := r.Sandbox
346
347	// Build the extension manager BEFORE the agent so we can fold
348	// extension-defined tools into the registry. Forward-declare iv so
349	// the host hooks adapter can dereference it after construction.
350	var iv *modes.Interactive
351	extHooks := &interactiveExtHooks{ivPtr: &iv}
352	extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
353	// --ext paths first so they win against installed extensions of
354	// the same name (loadOne's first-write-wins semantics).
355	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
356		fmt.Fprintln(os.Stderr, "extension load:", e)
357	}
358	// --no-ext skips the global + project-local discovery scan;
359	// explicit --ext paths above are still honoured so you can run
360	// "only this extension" with --no-ext --ext ./x.
361	if !args.NoExt {
362		for _, e := range extMgr.Discover(ctx) {
363			fmt.Fprintln(os.Stderr, "extension load:", e)
364		}
365	}
366	// Wait briefly for extensions to flush their initial register_tool
367	// frames before we build the agent's tool registry. Half a second
368	// is plenty for any extension that's actually well-behaved; ones
369	// that don't send a ready frame eat the full grace and proceed.
370	// 3s is the per-extension grace period for the ready frame.
371	// Native binaries are instant; runtimes like `npx tsx` take ~1.5s
372	// from cold cache. The wait is tight only for extensions that
373	// haven't sent ready by then; ones that signalled earlier release
374	// the wait immediately.
375	extMgr.WaitForReady(3 * time.Second)
376	defer extMgr.Stop(2 * time.Second)
377
378	extToolAdapter := &extToolAdapter{mgr: extMgr}
379	r.MergeExtensionTools(extToolAdapter)
380
381	// Confirmation gate: when --no-yolo is on, the agent must ask
382	// the user before every tool call. In interactive mode the TUI
383	// provides the Confirmer; in print/json/rpc modes there's no
384	// way to prompt, so the gate is constructed with a nil inner
385	// which auto-refuses every call with a helpful reason.
386	var confirmGate *core.ConfirmGate
387	if args.NoYolo {
388		confirmGate = core.NewConfirmGate(nil) // set below for interactive
389	}
390
391	// Capture current args in a closure so BuildAgent can re-resolve
392	// after a successful login (picks up the newly stored credential).
393	wireAgentExt := func(a *core.Agent) *core.Agent {
394		if a == nil {
395			return a
396		}
397		a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
398			// Confirm gate runs FIRST: if the user refused, we don't
399			// waste extension-intercept time or let guards see the call.
400			if confirmGate != nil {
401				ok, reason, _ := confirmGate.Check(call.Name, core.BuildPreview(call.Arguments, 120))
402				if !ok {
403					return false, reason, nil
404				}
405			}
406			r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
407			if r.Block {
408				return false, r.Reason, nil
409			}
410			return true, "", r.ModifiedArgs
411		}
412		a.BeforeTurn = func(step int) (bool, string) {
413			r := extMgr.InterceptTurnStart(ctx, step)
414			return !r.Block, r.Reason
415		}
416		a.BeforeAssistantMessage = func(text string) (bool, string, string) {
417			r := extMgr.InterceptAssistantMessage(ctx, text)
418			if r.Block {
419				return false, r.Reason, ""
420			}
421			return true, "", r.ReplaceText
422		}
423		a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
424		return a
425	}
426
427	buildAgent := func() (*core.Agent, string, string, error) {
428		resolved, err := Resolve(args, true)
429		if err != nil {
430			return nil, "", "", err
431		}
432		resolved.UseSandbox(sharedSandbox)
433		resolved.MergeExtensionTools(extToolAdapter)
434		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
435	}
436
437	// Rebuild agent with an explicit provider/model override.
438	buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
439		next := args
440		if providerOverride != "" {
441			next.Provider = providerOverride
442		}
443		if modelOverride != "" {
444			next.Model = modelOverride
445		}
446		resolved, err := Resolve(next, true)
447		if err != nil {
448			return nil, "", "", err
449		}
450		resolved.UseSandbox(sharedSandbox)
451		resolved.MergeExtensionTools(extToolAdapter)
452		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
453	}
454
455	var ag *core.Agent
456	if r.HasCredential() {
457		ag = wireAgentExt(r.NewAgent())
458	}
459
460	// /reload-ext callback: after the manager has respawned every
461	// extension, re-resolve the tool registry (built-ins + freshly-
462	// registered extension tools) and swap it onto the current
463	// agent in-place. The current agent may have been replaced by a
464	// /model swap since spawn, so re-read the live `ag` on each
465	// invocation.
466	extMgr.SetOnReload(func() {
467		current := ag
468		if current == nil {
469			return
470		}
471		resolved, err := Resolve(args, true)
472		if err != nil {
473			return
474		}
475		resolved.UseSandbox(sharedSandbox)
476		resolved.MergeExtensionTools(extToolAdapter)
477		current.SetTools(resolved.ToolRegistry)
478	})
479
480	// Fire session_start once we know the manager's running.
481	extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
482
483	var sess *core.Session
484	var sessBaselineMsgs int // messages already on disk when current session opened
485	if !args.NoSess && ag != nil {
486		sess, _ = openOrCreateSession(args, r, ag, version)
487		if ag != nil {
488			sessBaselineMsgs = len(ag.Messages())
489		}
490	}
491	defer func() {
492		if sess != nil {
493			sess.Close()
494		}
495	}()
496
497	// loadSession replaces the current session with the one at path and
498	// hands its messages to the agent. Used by the /sessions picker.
499	loadSession := func(path string) error {
500		currentAg := ag // captured
501		if currentAg == nil {
502			return fmt.Errorf("no agent running; log in first")
503		}
504		newSess, msgs, err := core.OpenSession(path)
505		if err != nil {
506			return err
507		}
508		// Flush any unsaved messages to the old session before swapping.
509		if sess != nil {
510			WriteNewTranscript(currentAg, sess, sessBaselineMsgs)
511			_ = sess.Close()
512		}
513		sess = newSess
514		currentAg.SetMessages(msgs)
515		sessBaselineMsgs = len(msgs)
516		return nil
517	}
518
519	term := tui.NewProcTerm()
520
521	// Kick off the async update check so the banner can appear when the
522	// http response eventually arrives (usually <1s on cached DNS). Map
523	// agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
524	updateCh := make(chan modes.UpdateInfo, 1)
525	go func() {
526		defer close(updateCh)
527		src := <-CheckForUpdateAsync(ZotHome(), version)
528		updateCh <- modes.UpdateInfo{
529			Current:   src.Current,
530			Latest:    src.Latest,
531			Available: src.Available,
532			URL:       src.URL,
533		}
534	}()
535
536	// Changelog: when the running version differs from the last
537	// version whose release notes the user dismissed, fetch the
538	// release body from GitHub and have the TUI show it once. On
539	// first-ever launch (no prior LastChangelogShown), seed the
540	// stored version silently — don't dump release notes at someone
541	// who just installed.
542	changelogCh := make(chan modes.ChangelogPayload, 1)
543	go func() {
544		defer close(changelogCh)
545		cfg, _ := LoadConfig()
546		if cfg.LastChangelogShown == "" {
547			SeedChangelogVersion(version)
548			return
549		}
550		if !ShouldShowChangelog(version, cfg) {
551			return
552		}
553		info := <-FetchChangelogAsync(version)
554		if info.Body == "" {
555			return
556		}
557		// For dev builds (0.0.0), skip if the latest release was
558		// already shown (stored by the dismiss callback).
559		if version == "0.0.0" && info.Version == cfg.LastChangelogShown {
560			return
561		}
562		changelogCh <- modes.ChangelogPayload{
563			Version: info.Version,
564			Body:    info.Body,
565			URL:     info.URL,
566		}
567	}()
568
569	iv = modes.NewInteractive(modes.InteractiveConfig{
570		Terminal:       term,
571		Theme:          tui.Dark,
572		Model:          r.Model,
573		Provider:       r.Provider,
574		AuthMethod:     r.AuthMethod,
575		BaseURL:        r.BaseURL,
576		Reasoning:      r.Reasoning,
577		SystemPrompt:   r.SystemPrompt,
578		Tools:          r.ToolRegistry,
579		MaxSteps:       r.MaxSteps,
580		CWD:            r.CWD,
581		ZotHome:        ZotHome(),
582		Version:        version,
583		UpdateInfoChan: updateCh,
584		Sandbox:        sharedSandbox,
585		Agent:          ag,
586		InitialInput:   args.Prompt,
587		AuthManager:    mgr,
588		BuildAgent:     buildAgent,
589		BuildAgentFor:  buildAgentFor,
590		LoggedInProviders: func() []string {
591			var out []string
592			for _, p := range []string{"anthropic", "openai"} {
593				if _, _, err := ResolveCredential(p, ""); err == nil {
594					out = append(out, p)
595				}
596			}
597			// Ollama models are always available (no auth needed).
598			out = append(out, "ollama")
599			return out
600		},
601		LoadSession: loadSession,
602		CurrentSessionPath: func() string {
603			if sess == nil {
604				return ""
605			}
606			return sess.Path
607		},
608		FlushSession: func() {
609			// Append any not-yet-persisted agent messages to the
610			// current session file, then advance the baseline so
611			// the final WriteNewTranscript at exit doesn't write
612			// duplicates. Called by /session export so the
613			// exported bytes include everything the user has
614			// said in the running TUI, not just whatever got
615			// flushed at startup.
616			if sess == nil {
617				return
618			}
619			currentAg := iv.Agent()
620			if currentAg == nil {
621				return
622			}
623			WriteNewTranscript(currentAg, sess, sessBaselineMsgs)
624			sessBaselineMsgs = len(currentAg.Messages())
625		},
626		Extensions:    extMgr,
627		ChangelogChan: changelogCh,
628		OnChangelogDismiss: func() {
629			// For dev builds (0.0.0) store the actual release version
630			// so the same changelog doesn't show again next launch.
631			// For real builds, store the binary version.
632			v := version
633			if v == "0.0.0" {
634				if iv != nil && iv.ChangelogVersion() != "" {
635					v = iv.ChangelogVersion()
636				}
637			}
638			_ = MarkChangelogShown(v)
639		},
640		SkillSnapshot: func() []*skills.Skill {
641			if args.NoSkill {
642				// --no-skill: nothing for the picker to show.
643				return nil
644			}
645			// Re-discover so the picker reflects edits made during
646			// the session. Cheap; SKILL.md files are small. Filter
647			// out built-in skills — they're hidden from user-facing
648			// surfaces because they're implementation detail; the
649			// model still sees them through the system-prompt
650			// manifest and the skill tool. User skills only appear
651			// when --with-skills is set; without it the picker shows
652			// nothing but the model still has the built-ins.
653			userHome, _ := os.UserHomeDir()
654			list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
655			return skills.VisibleSkills(list)
656		},
657		NoYolo:      args.NoYolo,
658		ConfirmGate: confirmGate,
659		PersistModel: func(providerName, model string) {
660			// Update config.json so next launch uses the same pick.
661			cfg, _ := LoadConfig()
662			cfg.Provider = providerName
663			cfg.Model = model
664			_ = SaveConfig(cfg)
665			// Update the active session's meta so resume picks this up.
666			if sess != nil {
667				_ = sess.UpdateModel(providerName, model)
668			}
669		},
670	})
671
672	// Bind the interactive TUI as the Confirmer. We deferred this
673	// until now because the gate is constructed before the TUI
674	// (the BeforeToolExecute closure captures it). SetConfirmer
675	// is mutex-guarded on the gate so this is safe.
676	if confirmGate != nil {
677		confirmGate.SetConfirmer(iv)
678	}
679
680	runErr := iv.Run(ctx)
681
682	// Flush final transcript to session (only if we had / ended up with an agent).
683	if finalAg := iv.Agent(); finalAg != nil && sess != nil {
684		WriteNewTranscript(finalAg, sess, sessBaselineMsgs)
685	}
686	return runErr
687}
688
689// openOrCreateSession returns a session for the run. sess may be nil
690// with a nil error if session persistence is disabled.
691func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
692	if args.NoSess {
693		return nil, nil
694	}
695	// Sweep meta-only files left over from older zot versions (and from
696	// any session that crashed before its first AppendMessage). Cheap;
697	// reads the first few bytes of each file in the cwd's session dir.
698	core.PruneEmptySessions(ZotHome(), args.CWD)
699	var (
700		s    *core.Session
701		msgs []provider.Message
702		err  error
703	)
704	switch {
705	case args.Session != "":
706		s, msgs, err = core.OpenSession(args.Session)
707	case args.Continue:
708		latest := core.LatestSession(ZotHome(), args.CWD)
709		if latest != "" {
710			s, msgs, err = core.OpenSession(latest)
711		}
712	case args.Resume:
713		picked, perr := pickSession(args.CWD)
714		if perr != nil {
715			return nil, perr
716		}
717		if picked != "" {
718			s, msgs, err = core.OpenSession(picked)
719		}
720	}
721	if err != nil {
722		return nil, err
723	}
724	if s != nil {
725		ag.SetMessages(msgs)
726		return s, nil
727	}
728	return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
729}
730
731func pickSession(cwd string) (string, error) {
732	files := core.ListSessions(ZotHome(), cwd)
733	if len(files) == 0 {
734		fmt.Fprintln(os.Stderr, "no sessions for", cwd)
735		return "", nil
736	}
737	for i, f := range files {
738		fmt.Fprintf(os.Stderr, "  %2d) %s\n", i+1, f)
739	}
740	fmt.Fprint(os.Stderr, "pick #: ")
741	rd := bufio.NewReader(os.Stdin)
742	line, _ := rd.ReadString('\n')
743	line = strings.TrimSpace(line)
744	var n int
745	if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
746		return "", fmt.Errorf("invalid selection")
747	}
748	return files[n-1], nil
749}
750
751// WriteNewTranscript appends only messages after index `from` from the
752// agent's transcript to the session.
753func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
754	if sess == nil || ag == nil {
755		return
756	}
757	msgs := ag.Messages()
758	for i := from; i < len(msgs); i++ {
759		_ = sess.AppendMessage(msgs[i])
760	}
761	cum := ag.Cost()
762	_ = sess.AppendUsage(cum, cum)
763}
764
765func readAllStdin() (string, error) {
766	fi, err := os.Stdin.Stat()
767	if err != nil {
768		return "", err
769	}
770	if (fi.Mode() & os.ModeCharDevice) != 0 {
771		return "", nil
772	}
773	b, err := io.ReadAll(os.Stdin)
774	return string(b), err
775}
776
777func printModels() {
778	fmt.Println("provider   model id                       context  max-out  reasoning  source        name")
779	for _, m := range provider.Active() {
780		reason := " "
781		if m.Reasoning {
782			reason = "✓"
783		}
784		source := m.Source
785		if source == "" {
786			source = "catalog"
787		}
788		if m.Speculative {
789			source = "speculative"
790		}
791		fmt.Printf("%-10s %-30s %8d %8d     %s        %-11s   %s\n",
792			m.Provider, m.ID, m.ContextWindow, m.MaxOutput, reason, source, m.DisplayName)
793	}
794}

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