v0.1.10 8a38171

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		changelogCh <- modes.ChangelogPayload{
558			Version: info.Version,
559			Body:    info.Body,
560			URL:     info.URL,
561		}
562	}()
563
564	iv = modes.NewInteractive(modes.InteractiveConfig{
565		Terminal:       term,
566		Theme:          tui.Dark,
567		Model:          r.Model,
568		Provider:       r.Provider,
569		AuthMethod:     r.AuthMethod,
570		BaseURL:        r.BaseURL,
571		Reasoning:      r.Reasoning,
572		SystemPrompt:   r.SystemPrompt,
573		Tools:          r.ToolRegistry,
574		MaxSteps:       r.MaxSteps,
575		CWD:            r.CWD,
576		ZotHome:        ZotHome(),
577		Version:        version,
578		UpdateInfoChan: updateCh,
579		Sandbox:        sharedSandbox,
580		Agent:          ag,
581		InitialInput:   args.Prompt,
582		AuthManager:    mgr,
583		BuildAgent:     buildAgent,
584		BuildAgentFor:  buildAgentFor,
585		LoadSession:    loadSession,
586		CurrentSessionPath: func() string {
587			if sess == nil {
588				return ""
589			}
590			return sess.Path
591		},
592		FlushSession: func() {
593			// Append any not-yet-persisted agent messages to the
594			// current session file, then advance the baseline so
595			// the final WriteNewTranscript at exit doesn't write
596			// duplicates. Called by /session export so the
597			// exported bytes include everything the user has
598			// said in the running TUI, not just whatever got
599			// flushed at startup.
600			if sess == nil {
601				return
602			}
603			currentAg := iv.Agent()
604			if currentAg == nil {
605				return
606			}
607			WriteNewTranscript(currentAg, sess, sessBaselineMsgs)
608			sessBaselineMsgs = len(currentAg.Messages())
609		},
610		Extensions:    extMgr,
611		ChangelogChan: changelogCh,
612		OnChangelogDismiss: func() {
613			_ = MarkChangelogShown(version)
614		},
615		SkillSnapshot: func() []*skills.Skill {
616			if args.NoSkill {
617				// --no-skill: nothing for the picker to show.
618				return nil
619			}
620			// Re-discover so the picker reflects edits made during
621			// the session. Cheap; SKILL.md files are small. Filter
622			// out built-in skills — they're hidden from user-facing
623			// surfaces because they're implementation detail; the
624			// model still sees them through the system-prompt
625			// manifest and the skill tool. User skills only appear
626			// when --with-skills is set; without it the picker shows
627			// nothing but the model still has the built-ins.
628			userHome, _ := os.UserHomeDir()
629			list, _ := skills.Discover(ZotHome(), r.CWD, userHome, args.WithSkills)
630			return skills.VisibleSkills(list)
631		},
632		NoYolo:      args.NoYolo,
633		ConfirmGate: confirmGate,
634		PersistModel: func(providerName, model string) {
635			// Update config.json so next launch uses the same pick.
636			cfg, _ := LoadConfig()
637			cfg.Provider = providerName
638			cfg.Model = model
639			_ = SaveConfig(cfg)
640			// Update the active session's meta so resume picks this up.
641			if sess != nil {
642				_ = sess.UpdateModel(providerName, model)
643			}
644		},
645	})
646
647	// Bind the interactive TUI as the Confirmer. We deferred this
648	// until now because the gate is constructed before the TUI
649	// (the BeforeToolExecute closure captures it). SetConfirmer
650	// is mutex-guarded on the gate so this is safe.
651	if confirmGate != nil {
652		confirmGate.SetConfirmer(iv)
653	}
654
655	runErr := iv.Run(ctx)
656
657	// Flush final transcript to session (only if we had / ended up with an agent).
658	if finalAg := iv.Agent(); finalAg != nil && sess != nil {
659		WriteNewTranscript(finalAg, sess, sessBaselineMsgs)
660	}
661	return runErr
662}
663
664// openOrCreateSession returns a session for the run. sess may be nil
665// with a nil error if session persistence is disabled.
666func openOrCreateSession(args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
667	if args.NoSess {
668		return nil, nil
669	}
670	// Sweep meta-only files left over from older zot versions (and from
671	// any session that crashed before its first AppendMessage). Cheap;
672	// reads the first few bytes of each file in the cwd's session dir.
673	core.PruneEmptySessions(ZotHome(), args.CWD)
674	var (
675		s    *core.Session
676		msgs []provider.Message
677		err  error
678	)
679	switch {
680	case args.Session != "":
681		s, msgs, err = core.OpenSession(args.Session)
682	case args.Continue:
683		latest := core.LatestSession(ZotHome(), args.CWD)
684		if latest != "" {
685			s, msgs, err = core.OpenSession(latest)
686		}
687	case args.Resume:
688		picked, perr := pickSession(args.CWD)
689		if perr != nil {
690			return nil, perr
691		}
692		if picked != "" {
693			s, msgs, err = core.OpenSession(picked)
694		}
695	}
696	if err != nil {
697		return nil, err
698	}
699	if s != nil {
700		ag.SetMessages(msgs)
701		return s, nil
702	}
703	return core.NewSession(ZotHome(), args.CWD, r.Provider, r.Model, version)
704}
705
706func pickSession(cwd string) (string, error) {
707	files := core.ListSessions(ZotHome(), cwd)
708	if len(files) == 0 {
709		fmt.Fprintln(os.Stderr, "no sessions for", cwd)
710		return "", nil
711	}
712	for i, f := range files {
713		fmt.Fprintf(os.Stderr, "  %2d) %s\n", i+1, f)
714	}
715	fmt.Fprint(os.Stderr, "pick #: ")
716	rd := bufio.NewReader(os.Stdin)
717	line, _ := rd.ReadString('\n')
718	line = strings.TrimSpace(line)
719	var n int
720	if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
721		return "", fmt.Errorf("invalid selection")
722	}
723	return files[n-1], nil
724}
725
726// WriteNewTranscript appends only messages after index `from` from the
727// agent's transcript to the session.
728func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) {
729	if sess == nil || ag == nil {
730		return
731	}
732	msgs := ag.Messages()
733	for i := from; i < len(msgs); i++ {
734		_ = sess.AppendMessage(msgs[i])
735	}
736	cum := ag.Cost()
737	_ = sess.AppendUsage(cum, cum)
738}
739
740func readAllStdin() (string, error) {
741	fi, err := os.Stdin.Stat()
742	if err != nil {
743		return "", err
744	}
745	if (fi.Mode() & os.ModeCharDevice) != 0 {
746		return "", nil
747	}
748	b, err := io.ReadAll(os.Stdin)
749	return string(b), err
750}
751
752func printModels() {
753	fmt.Println("provider   model id                       context  max-out  reasoning  source        name")
754	for _, m := range provider.Active() {
755		reason := " "
756		if m.Reasoning {
757			reason = "✓"
758		}
759		source := m.Source
760		if source == "" {
761			source = "catalog"
762		}
763		if m.Speculative {
764			source = "speculative"
765		}
766		fmt.Printf("%-10s %-30s %8d %8d     %s        %-11s   %s\n",
767			m.Provider, m.ID, m.ContextWindow, m.MaxOutput, reason, source, m.DisplayName)
768	}
769}

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