v0.2.98 b7f2f12

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

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