v0.3.35 a159f47

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

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