v0.1.51 ff1af01

cli.go RawHistoryFolder

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

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