v0.16.0 042538b

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	"slices"
14	"strings"
15	"sync"
16	"syscall"
17	"time"
18
19	"github.com/bnema/zut/packages/agent/extensions"
20	"github.com/bnema/zut/packages/agent/extproto"
21	"github.com/bnema/zut/packages/agent/modes"
22	"github.com/bnema/zut/packages/agent/skills"
23	"github.com/bnema/zut/packages/agent/subagents"
24	"github.com/bnema/zut/packages/agent/tools"
25	"github.com/bnema/zut/packages/core"
26	"github.com/bnema/zut/packages/provider"
27	"github.com/bnema/zut/packages/provider/auth"
28	"github.com/bnema/zut/packages/tui"
29)
30
31// interactiveExtHooks is a tiny adapter that lets the extension
32// manager call back into the Interactive instance built later in
33// runInteractive. Alerts are buffered until the instance is attached so
34// an extension that signals attention during startup is not silently lost.
35// Keep the startup buffer bounded because extensions can flood their host.
36const maxBufferedInteractiveAlerts = 64
37
38type interactiveExtHooks struct {
39	mu              sync.Mutex
40	interactive     *modes.Interactive
41	pendingAlerts   []interactiveAlert
42	pendingStatuses map[string]interactiveStatus
43	pendingWidgets  map[string]interactiveWidget
44}
45
46type interactiveAlert struct {
47	extName string
48	alert   extproto.AlertRequest
49}
50
51type interactiveStatus struct {
52	extName string
53	key     string
54	level   string
55	text    string
56}
57
58type interactiveWidget struct {
59	extName  string
60	id       string
61	position string
62	title    string
63	lines    []string
64}
65
66func (h *interactiveExtHooks) iv() *modes.Interactive {
67	if h == nil {
68		return nil
69	}
70	h.mu.Lock()
71	defer h.mu.Unlock()
72	return h.interactive
73}
74
75func (h *interactiveExtHooks) attachInteractive(iv *modes.Interactive) {
76	if h == nil || iv == nil {
77		return
78	}
79	h.mu.Lock()
80	h.interactive = iv
81	pendingAlerts := h.pendingAlerts
82	pendingStatuses := h.pendingStatuses
83	pendingWidgets := h.pendingWidgets
84	h.pendingAlerts = nil
85	h.pendingStatuses = nil
86	h.pendingWidgets = nil
87	h.mu.Unlock()
88	for _, item := range pendingAlerts {
89		iv.Alert(item.extName, item.alert)
90	}
91	for _, item := range pendingStatuses {
92		iv.SetStatus(item.extName, item.key, item.level, item.text)
93	}
94	for _, item := range pendingWidgets {
95		iv.SetWidget(item.extName, item.id, item.position, item.title, item.lines)
96	}
97}
98
99func (h *interactiveExtHooks) Notify(extName, level, message string) {
100	if iv := h.iv(); iv != nil {
101		iv.Notify(extName, level, message)
102	}
103}
104func (h *interactiveExtHooks) Alert(extName string, alert extproto.AlertRequest) {
105	if h == nil {
106		return
107	}
108	h.mu.Lock()
109	if h.interactive == nil {
110		if len(h.pendingAlerts) < maxBufferedInteractiveAlerts {
111			h.pendingAlerts = append(h.pendingAlerts, interactiveAlert{extName: extName, alert: alert})
112		}
113		h.mu.Unlock()
114		return
115	}
116	iv := h.interactive
117	h.mu.Unlock()
118	iv.Alert(extName, alert)
119}
120func (h *interactiveExtHooks) Submit(text string) {
121	if iv := h.iv(); iv != nil {
122		iv.SubmitOrQueue(text, nil)
123	}
124}
125func (h *interactiveExtHooks) SubmitSlash(text string) {
126	if iv := h.iv(); iv != nil {
127		iv.SubmitSlash(text)
128	}
129}
130func (h *interactiveExtHooks) Insert(text string) {
131	if iv := h.iv(); iv != nil {
132		iv.Insert(text)
133	}
134}
135func (h *interactiveExtHooks) Display(extName, text string) {
136	if iv := h.iv(); iv != nil {
137		iv.Display(extName, text)
138	}
139}
140func (h *interactiveExtHooks) ClearNotes(extName string) {
141	if iv := h.iv(); iv != nil {
142		iv.ClearNotes(extName)
143	}
144}
145func (h *interactiveExtHooks) OpenPanel(extName string, spec extproto.PanelSpec) {
146	if iv := h.iv(); iv != nil {
147		iv.OpenPanel(extName, spec)
148	}
149}
150func (h *interactiveExtHooks) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
151	if iv := h.iv(); iv != nil {
152		iv.UpdatePanel(extName, panelID, title, lines, footer)
153	}
154}
155func (h *interactiveExtHooks) ClosePanel(extName, panelID string) {
156	if iv := h.iv(); iv != nil {
157		iv.ClosePanel(extName, panelID)
158	}
159}
160func pendingChromeKey(extName, key string) string { return extName + "\x00" + key }
161
162func (h *interactiveExtHooks) SetStatus(extName, key, level, text string) {
163	if h == nil {
164		return
165	}
166	h.mu.Lock()
167	if h.interactive == nil {
168		if h.pendingStatuses == nil {
169			h.pendingStatuses = map[string]interactiveStatus{}
170		}
171		pendingKey := pendingChromeKey(extName, key)
172		if strings.TrimSpace(text) == "" {
173			delete(h.pendingStatuses, pendingKey)
174		} else {
175			h.pendingStatuses[pendingKey] = interactiveStatus{extName: extName, key: key, level: level, text: text}
176		}
177		h.mu.Unlock()
178		return
179	}
180	iv := h.interactive
181	h.mu.Unlock()
182	iv.SetStatus(extName, key, level, text)
183}
184func (h *interactiveExtHooks) SetWidget(extName, id, position, title string, lines []string) {
185	if h == nil {
186		return
187	}
188	h.mu.Lock()
189	if h.interactive == nil {
190		if h.pendingWidgets == nil {
191			h.pendingWidgets = map[string]interactiveWidget{}
192		}
193		h.pendingWidgets[pendingChromeKey(extName, id)] = interactiveWidget{
194			extName: extName, id: id, position: position, title: title, lines: append([]string(nil), lines...),
195		}
196		h.mu.Unlock()
197		return
198	}
199	iv := h.interactive
200	h.mu.Unlock()
201	iv.SetWidget(extName, id, position, title, lines)
202}
203func (h *interactiveExtHooks) ClearWidget(extName, id string) {
204	if h == nil {
205		return
206	}
207	h.mu.Lock()
208	if h.interactive == nil {
209		if h.pendingWidgets != nil {
210			delete(h.pendingWidgets, pendingChromeKey(extName, id))
211		}
212		h.mu.Unlock()
213		return
214	}
215	iv := h.interactive
216	h.mu.Unlock()
217	iv.ClearWidget(extName, id)
218}
219
220func (h *interactiveExtHooks) ClearExtensionChrome(extName string) {
221	if h == nil {
222		return
223	}
224	h.mu.Lock()
225	if h.interactive == nil {
226		prefix := extName + "\x00"
227		for key := range h.pendingStatuses {
228			if strings.HasPrefix(key, prefix) {
229				delete(h.pendingStatuses, key)
230			}
231		}
232		for key := range h.pendingWidgets {
233			if strings.HasPrefix(key, prefix) {
234				delete(h.pendingWidgets, key)
235			}
236		}
237		h.mu.Unlock()
238		return
239	}
240	iv := h.interactive
241	h.mu.Unlock()
242	iv.ClearExtensionChrome(extName)
243}
244
245// extToolAdapter bridges *extensions.Manager to the
246// ExtensionToolSource interface declared in build.go (kept narrow to
247// avoid a build->extensions import cycle). One adapter instance per
248// run; used at every Resolve point so re-built agents pick up the
249// same set of extension tools.
250type extToolAdapter struct {
251	mgr *extensions.Manager
252}
253
254var _ ExtensionToolSource = (*extToolAdapter)(nil)
255var _ ExtensionSkillSource = (*extToolAdapter)(nil)
256
257func (a *extToolAdapter) Skills() []*skills.Skill {
258	if a == nil || a.mgr == nil {
259		return nil
260	}
261	return a.mgr.Skills()
262}
263
264func (a *extToolAdapter) Tools() []ExtensionToolInfo {
265	infos := a.mgr.Tools()
266	out := make([]ExtensionToolInfo, len(infos))
267	for i, t := range infos {
268		out[i] = ExtensionToolInfo{
269			Extension:   t.Extension,
270			Name:        t.Name,
271			Description: t.Description,
272			Schema:      t.Schema,
273			Deferred:    t.Deferred,
274		}
275	}
276	return out
277}
278
279func (a *extToolAdapter) NewExtensionTool(info ExtensionToolInfo) core.Tool {
280	return extensions.NewTool(a.mgr, extensions.ToolInfo{
281		Extension:   info.Extension,
282		Name:        info.Name,
283		Description: info.Description,
284		Schema:      info.Schema,
285		Deferred:    info.Deferred,
286	})
287}
288
289// liveInteractiveAgent returns the agent currently owned by the TUI. The
290// fallback is only used before the Interactive has been constructed.
291//
292// Agent rebuilds, such as cross-provider model switches, replace the TUI's
293// agent without replacing the startup pointer held by runInteractive. Session
294// operations must therefore resolve the live agent at the time of the action.
295func liveInteractiveAgent(iv *modes.Interactive, fallback *core.Agent) *core.Agent {
296	if iv != nil {
297		return iv.Agent()
298	}
299	return fallback
300}
301
302func newSessionTransition(mu *sync.RWMutex) func(func()) {
303	return func(fn func()) {
304		mu.Lock()
305		defer mu.Unlock()
306		fn()
307	}
308}
309
310// newPersistModelCallback returns the callback used by the TUI while its
311// session transition write lock is held. It must not acquire that lock again
312// because sync.RWMutex is not reentrant.
313func newPersistModelCallback(persistMu *sync.Mutex, sess **core.Session, activeProvider, activeModel *string, notify func(string)) func(string, string) {
314	return func(providerName, model string) {
315		providerName = strings.TrimSpace(providerName)
316		model = strings.TrimSpace(model)
317
318		persistMu.Lock()
319		var sessionErr error
320		if *sess != nil {
321			sessionErr = (*sess).UpdateModel(providerName, model)
322		}
323		*activeProvider = providerName
324		*activeModel = model
325		persistMu.Unlock()
326		if sessionErr != nil {
327			if notify != nil {
328				notify("model change was not persisted: " + sessionErr.Error())
329			}
330			return
331		}
332
333		cfg, err := LoadConfig()
334		if err != nil {
335			if notify != nil {
336				notify("model changed for this run, but config could not be read: " + err.Error())
337			}
338			return
339		}
340		cfg.Provider = providerName
341		cfg.Model = model
342		if err := SaveConfig(cfg); err != nil && notify != nil {
343			notify("model changed for this run, but config could not be saved: " + err.Error())
344		}
345	}
346}
347
348func closeAgentLSP(ag *core.Agent) {
349	if ag != nil {
350		_ = tools.CloseLSPManagers(ag.ToolsSnapshot())
351	}
352}
353
354func joinSessionCloseError(err error, sess *core.Session) error {
355	if sess == nil {
356		return err
357	}
358	if closeErr := sess.Close(); closeErr != nil {
359		return errors.Join(err, fmt.Errorf("close session: %w", closeErr))
360	}
361	return err
362}
363
364func closeResolvedLSP(r Resolved) {
365	_ = tools.CloseLSPManagers(r.ToolRegistry)
366}
367
368func trimMessagesForResume(msgs []provider.Message, keepTail int) []provider.Message {
369	if keepTail <= 0 || len(msgs) <= keepTail {
370		return provider.RepairOrphanedToolResults(msgs)
371	}
372	var out []provider.Message
373	start := len(msgs) - keepTail
374	var carriedToolNames []string
375	addToolNames := func(names []string) {
376		for _, name := range names {
377			if name == "" || slices.Contains(carriedToolNames, name) {
378				continue
379			}
380			carriedToolNames = append(carriedToolNames, name)
381		}
382	}
383	// Activation markers in the discarded prefix still affect the retained
384	// provider request. Carry them onto its first message rather than dropping
385	// deferred-tool availability when the resume tail is shortened.
386	for _, msg := range msgs[:start] {
387		addToolNames(msg.AddedToolNames)
388	}
389	// Preserve the synthetic compaction summary when present so an
390	// already-compacted session stays compacted after resume. Count it
391	// within the tail budget instead of dropping it at the exact boundary.
392	if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" && start > 0 {
393		out = append(out, msgs[0])
394		start++
395	}
396	// Avoid hydrating a tail that starts with orphan tool_result rows;
397	// provider APIs require those to be paired with an earlier tool_use.
398	for start < len(msgs) && msgs[start].Role == provider.RoleTool {
399		start++
400	}
401	out = append(out, msgs[start:]...)
402	if len(carriedToolNames) > 0 && len(out) > 0 {
403		first := out[0]
404		for _, name := range first.AddedToolNames {
405			addToolNames([]string{name})
406		}
407		first.AddedToolNames = append([]string(nil), carriedToolNames...)
408		out[0] = first
409	}
410	return provider.RepairOrphanedToolResults(out)
411}
412
413// sessionResumeCandidate contains all state needed to resume a session.
414// It is deliberately assembled before the caller changes any live state:
415// opening the transcript, reading usage, and rebuilding a provider/model
416// must all succeed before the candidate can replace the current session.
417type sessionResumeCandidate struct {
418	session          *core.Session
419	agent            *core.Agent
420	messages         []provider.Message
421	fullMessageCount int
422	cumulative       provider.Usage
423	lastTurn         provider.Usage
424	provider         string
425	model            string
426	rebuilt          bool
427}
428
429// prepareSessionResume opens and validates a selected session without
430// touching the current agent. Missing provider/model metadata is treated as
431// legacy metadata: the current agent is reused, preserving compatibility
432// with sessions written before those fields were persisted.
433//
434// The returned candidate owns session until its caller commits it. On any
435// error this function closes the candidate session and leaves the current
436// agent untouched.
437func prepareSessionResume(path string, current *core.Agent, currentProvider, currentModel string, buildAgentFor func(string, string) (*core.Agent, string, string, error)) (sessionResumeCandidate, error) {
438	return prepareSessionResumeWithOptions(path, current, currentProvider, currentModel, false, false, buildAgentFor)
439}
440
441// prepareSessionResumeWithOptions is the provider/model-aware implementation.
442// An explicit CLI provider or model keeps that field authoritative; an empty
443// field falls back to the selected session's metadata when it is complete.
444func prepareSessionResumeWithOptions(path string, current *core.Agent, currentProvider, currentModel string, explicitProvider, explicitModel bool, buildAgentFor func(string, string) (*core.Agent, string, string, error)) (candidate sessionResumeCandidate, err error) {
445	if current == nil {
446		return candidate, fmt.Errorf("no agent running; log in first")
447	}
448
449	sess, msgs, err := core.OpenSession(path)
450	if err != nil {
451		return candidate, err
452	}
453	keepSession := false
454	defer func() {
455		if !keepSession {
456			err = joinSessionCloseError(err, sess)
457		}
458	}()
459
460	cumulative, lastTurn, err := core.SessionUsageDetail(path)
461	if err != nil {
462		return candidate, fmt.Errorf("read session usage: %w", err)
463	}
464
465	fullMessageCount := len(msgs)
466	resumedMessages := trimMessagesForResume(msgs, 100)
467	storedProvider := strings.TrimSpace(sess.Meta.Provider)
468	storedModel := strings.TrimSpace(sess.Meta.Model)
469	currentProvider = strings.TrimSpace(currentProvider)
470	currentModel = strings.TrimSpace(currentModel)
471
472	candidate = sessionResumeCandidate{
473		session:          sess,
474		agent:            current,
475		messages:         resumedMessages,
476		fullMessageCount: fullMessageCount,
477		cumulative:       cumulative,
478		lastTurn:         lastTurn,
479		provider:         currentProvider,
480		model:            currentModel,
481	}
482
483	// Old sessions may have either field absent. Only a complete stored
484	// selection is actionable; otherwise resume exactly as older zut did.
485	if storedProvider == "" || storedModel == "" {
486		keepSession = true
487		return candidate, nil
488	}
489
490	resumeProvider := storedProvider
491	if explicitProvider {
492		resumeProvider = currentProvider
493	}
494	resumeModel := storedModel
495	if explicitModel {
496		resumeModel = currentModel
497	}
498	if resumeProvider == currentProvider && resumeModel == currentModel {
499		keepSession = true
500		return candidate, nil
501	}
502	if buildAgentFor == nil {
503		return sessionResumeCandidate{}, fmt.Errorf("cannot resume session with provider %q and model %q: no agent builder configured", resumeProvider, resumeModel)
504	}
505
506	rebuilt, resolvedProvider, resolvedModel, err := buildAgentFor(resumeProvider, resumeModel)
507	if err != nil {
508		return sessionResumeCandidate{}, fmt.Errorf("rebuild agent for session provider %q/model %q: %w", resumeProvider, resumeModel, err)
509	}
510	if rebuilt == nil {
511		return sessionResumeCandidate{}, fmt.Errorf("rebuild agent for session provider %q/model %q returned no agent", resumeProvider, resumeModel)
512	}
513	resolvedProvider = strings.TrimSpace(resolvedProvider)
514	resolvedModel = strings.TrimSpace(resolvedModel)
515	if resolvedProvider == "" {
516		resolvedProvider = storedProvider
517	}
518	if resolvedModel == "" {
519		resolvedModel = storedModel
520	}
521
522	// Hydrate and seed the replacement while it is still private. The live
523	// agent is not modified until the caller commits the complete candidate.
524	rebuilt.SetMessages(resumedMessages)
525	rebuilt.SeedCost(cumulative)
526	rebuilt.SeedLastTurnUsage(lastTurn)
527	candidate.agent = rebuilt
528	candidate.provider = resolvedProvider
529	candidate.model = resolvedModel
530	candidate.rebuilt = true
531	keepSession = true
532	return candidate, nil
533}
534
535func buildNonInteractiveSessionAgentWithRegistry(ctx context.Context, args Args, base Resolved, extMgr *extensions.Manager, providerName, model string, prepareRegistry func(core.Registry) core.Registry) (*core.Agent, string, string, error) {
536	next := args
537	next.Provider = providerName
538	next.Model = model
539	resolved, err := Resolve(next, true)
540	if err != nil {
541		return nil, "", "", err
542	}
543	resolved.UseSandbox(base.Sandbox)
544	if extMgr != nil {
545		resolved.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
546	}
547	if prepareRegistry != nil {
548		prepareRegistry(resolved.ToolRegistry)
549	}
550	ag := resolved.NewAgent()
551	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
552	return ag, resolved.Provider, resolved.Model, nil
553}
554
555// applySessionResume shares the startup gate, candidate hydration, and
556// commit order used by interactive and non-interactive session opening. The
557// old append handle is closed only after the candidate has been prepared and
558// seeded successfully.
559func applySessionResume(sess *core.Session, ag *core.Agent, currentProvider, currentModel string, explicitProvider, explicitModel bool, buildAgentFor func(string, string) (*core.Agent, string, string, error)) (sessionResumeCandidate, error) {
560	candidate := sessionResumeCandidate{
561		session:          sess,
562		agent:            ag,
563		fullMessageCount: 0,
564		provider:         currentProvider,
565		model:            currentModel,
566	}
567	if ag != nil {
568		candidate.fullMessageCount = len(ag.Messages())
569	}
570	if sess == nil || ag == nil {
571		return candidate, nil
572	}
573	ag.SetSessionTimeContext(sess.Meta.Started, sess.Meta.Timezone, sess.Meta.TimezoneOffset)
574	// A newly created meta-only session is already on the active pair. Avoid
575	// reopening and closing it through the resume path: Close intentionally
576	// removes fresh empty sessions, and a second append handle would otherwise
577	// keep an unlinked file alive.
578	if len(ag.Messages()) == 0 &&
579		strings.TrimSpace(sess.Meta.Provider) == strings.TrimSpace(currentProvider) &&
580		strings.TrimSpace(sess.Meta.Model) == strings.TrimSpace(currentModel) {
581		return candidate, nil
582	}
583	candidate, err := prepareSessionResumeWithOptions(sess.Path, ag, currentProvider, currentModel, explicitProvider, explicitModel, buildAgentFor)
584	if err != nil {
585		return sessionResumeCandidate{}, joinSessionCloseError(err, sess)
586	}
587	if !candidate.rebuilt {
588		candidate.agent.SetMessages(candidate.messages)
589		candidate.agent.SeedCost(candidate.cumulative)
590		candidate.agent.SeedLastTurnUsage(candidate.lastTurn)
591	}
592	if closeErr := sess.Close(); closeErr != nil {
593		return sessionResumeCandidate{}, errors.Join(fmt.Errorf("close session: %w", closeErr), joinSessionCloseError(nil, candidate.session))
594	}
595	candidate.agent.SetSessionTimeContext(candidate.session.Meta.Started, candidate.session.Meta.Timezone, candidate.session.Meta.TimezoneOffset)
596	return candidate, nil
597}
598
599// applyInitialSessionResume applies the same provider/model-aware candidate
600// contract used by interactive session switching to non-interactive startup
601// modes. The returned session owns the replacement append handle.
602func applyInitialSessionResume(ctx context.Context, args Args, base Resolved, extMgr *extensions.Manager, sess *core.Session, ag *core.Agent) (*core.Session, *core.Agent, string, string, error) {
603	return applyInitialSessionResumeWithRegistry(ctx, args, base, extMgr, sess, ag, nil)
604}
605
606func applyInitialSessionResumeWithRegistry(ctx context.Context, args Args, base Resolved, extMgr *extensions.Manager, sess *core.Session, ag *core.Agent, prepareRegistry func(core.Registry) core.Registry) (*core.Session, *core.Agent, string, string, error) {
607	candidate, err := applySessionResume(sess, ag, base.Provider, base.Model,
608		strings.TrimSpace(args.Provider) != "", strings.TrimSpace(args.Model) != "", func(providerName, model string) (*core.Agent, string, string, error) {
609			return buildNonInteractiveSessionAgentWithRegistry(ctx, args, base, extMgr, providerName, model, prepareRegistry)
610		})
611	if err != nil {
612		return nil, ag, "", "", err
613	}
614	return candidate.session, candidate.agent, candidate.provider, candidate.model, nil
615}
616
617func applyInitialSessionResumeWithRuntime(ctx context.Context, args Args, base Resolved, extMgr *extensions.Manager, sess *core.Session, ag *core.Agent, runtime *subagentRuntime) (*core.Session, *core.Agent, string, string, error) {
618	candidate, err := applySessionResume(sess, ag, base.Provider, base.Model,
619		strings.TrimSpace(args.Provider) != "", strings.TrimSpace(args.Model) != "", func(providerName, model string) (*core.Agent, string, string, error) {
620			next := args
621			next.Provider = providerName
622			next.Model = model
623			resolved, resolveErr := Resolve(next, true)
624			if resolveErr != nil {
625				return nil, "", "", resolveErr
626			}
627			resolved.UseSandbox(base.Sandbox)
628			if extMgr != nil {
629				resolved.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
630			}
631			if runtime != nil {
632				runtime.SetProvider(resolved.Provider)
633				runtime.SetModel(resolved.Model)
634				runtime.SetProviderSettings(resolved.BaseURL, resolved.InsecureTLS)
635				runtime.SetFastMode(resolved.FastMode)
636				runtime.PrepareResolvedRegistry(resolved.ToolRegistry, resolved.WebSearchPolicy)
637			}
638			rebuilt := resolved.NewAgent()
639			wireNonInteractiveAgentExtHooks(ctx, rebuilt, extMgr)
640			return rebuilt, resolved.Provider, resolved.Model, nil
641		})
642	if err != nil {
643		return nil, ag, "", "", err
644	}
645	return candidate.session, candidate.agent, candidate.provider, candidate.model, nil
646}
647
648// fanoutAgentEvent translates a core.AgentEvent into the wire-format
649// EventFromHost and pushes it through the extension manager. Only
650// the events that have a clear extension-facing meaning are
651// forwarded; internal-only ones (text_delta, tool_progress) are
652// dropped to keep the per-extension stream sane.
653func sessionContext(sess *core.Session) *extproto.SessionContext {
654	if sess == nil {
655		return nil
656	}
657	return &extproto.SessionContext{
658		ID:        sess.Meta.ID,
659		ParentID:  sess.Meta.Parent,
660		Path:      sess.Path,
661		CWD:       sess.Meta.CWD,
662		ForkPoint: sess.Meta.ForkPoint,
663	}
664}
665
666func announceSession(mgr *extensions.Manager, sess *core.Session) {
667	if mgr == nil {
668		return
669	}
670	var states map[string]json.RawMessage
671	if sess != nil {
672		states = copyExtensionStates(sess.ExtensionState)
673	}
674	mgr.EmitSessionEvent("session_start", sessionContext(sess), states)
675	if sess != nil {
676		mgr.EmitSessionEvent("session_opened", sessionContext(sess), states)
677	}
678}
679
680func copyExtensionStates(states map[string]json.RawMessage) map[string]json.RawMessage {
681	if len(states) == 0 {
682		return nil
683	}
684	out := make(map[string]json.RawMessage, len(states))
685	for name, state := range states {
686		out[name] = append(json.RawMessage(nil), state...)
687	}
688	return out
689}
690
691func persistToolResultState(mgr *extensions.Manager, sess *core.Session, result core.ToolResult) error {
692	if sess == nil {
693		return nil
694	}
695	if details, ok := result.Details.(extensions.ToolResultDetails); ok && details.Extension != "" && len(details.State) > 0 {
696		if err := sess.AppendExtensionState(details.Extension, details.State); err != nil {
697			return fmt.Errorf("extension state: %w", err)
698		}
699		if mgr != nil {
700			mgr.UpdateSessionState(details.Extension, details.State)
701		}
702	}
703	if err := persistGoalToolResult(sess, result); err != nil {
704		return fmt.Errorf("goal state: %w", err)
705	}
706	return nil
707}
708
709func persistGoalToolResult(sess *core.Session, result core.ToolResult) error {
710	if sess == nil {
711		return nil
712	}
713	update, ok := tools.GoalUpdateFromResult(result)
714	if !ok {
715		return nil
716	}
717	if update.Status == core.GoalActive {
718		if sess.Meta.Goal != nil && sess.Meta.Goal.Status == core.GoalActive {
719			return fmt.Errorf("cannot replace an active goal")
720		}
721		if sess.Meta.Mission != nil && update.MissionID != "" && update.MissionID != sess.Meta.Mission.ID {
722			return fmt.Errorf("goal update does not belong to the active mission")
723		}
724		return sess.UpdateGoal(&core.SessionGoal{Objective: update.Objective, Status: core.GoalActive, Owner: core.GoalOwnerManager})
725	}
726	if sess.Meta.Goal == nil || sess.Meta.Goal.Status != core.GoalActive {
727		return nil
728	}
729	goal := *sess.Meta.Goal
730	goal.Status = update.Status
731	goal.Reason = update.Reason
732	return sess.UpdateGoal(&goal)
733}
734
735func fanoutAgentEvent(mgr *extensions.Manager, ev core.AgentEvent) {
736	if mgr == nil {
737		return
738	}
739	switch e := ev.(type) {
740	case core.EvTurnStart:
741		mgr.EmitEvent(extproto.EventFromHost{Event: "turn_start", Step: e.Step})
742	case core.EvToolCall:
743		mgr.EmitEvent(extproto.EventFromHost{
744			Event: "tool_call", ToolID: e.ID, ToolName: e.Name, ToolArgs: e.Args,
745		})
746	case core.EvAssistantMessage:
747		// Concat the visible text portions of the message; binary
748		// blocks (tool_use, etc.) are skipped because subscribers
749		// usually want a string they can grep / display.
750		var text string
751		for _, c := range e.Message.Content {
752			if tb, ok := c.(provider.TextBlock); ok {
753				text += tb.Text
754			}
755		}
756		mgr.EmitEvent(extproto.EventFromHost{Event: "assistant_message", Text: text})
757	case core.EvTurnEnd:
758		ev := extproto.EventFromHost{Event: "turn_end", Stop: string(e.Stop)}
759		if e.Err != nil {
760			ev.Error = e.Err.Error()
761		}
762		mgr.EmitEvent(ev)
763	}
764}
765
766// Run is the top-level entrypoint for the zut binary.
767func Run(rawArgs []string, version string) error {
768	// Apply network configuration before any subcommand can make an HTTP
769	// request. Standard proxy environment variables retain precedence.
770	applyConfiguredHTTPProxy()
771
772	// Extension installs can invoke external build and clone processes.
773	// Give those processes a cancellation context without changing signal
774	// handling for the interactive modes below.
775	extCtx := context.Background()
776	stopExtContext := func() {}
777	if len(rawArgs) > 0 && rawArgs[0] == "ext" {
778		extCtx, stopExtContext = signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
779	}
780	defer stopExtContext()
781
782	// Subcommand router: `zut bot ...` is handled separately so the
783	// generic flag parser doesn't reject "bot" as a positional arg.
784	if handled, err := runBotCommand(rawArgs, version); handled {
785		return err
786	}
787	if handled, err := runExtCommand(extCtx, rawArgs, version); handled {
788		return err
789	}
790	if handled, err := runUpdateCommand(rawArgs, version); handled {
791		return err
792	}
793	if handled, err := runZutfileCommand(rawArgs, version); handled {
794		return err
795	}
796	if handled, err := runDebugCommand(rawArgs, os.Stdout); handled {
797		return err
798	}
799	return runWithArgsRaw(rawArgs, version)
800}
801
802func runWithArgsRaw(rawArgs []string, version string) error {
803	// `zut rpc` is shorthand for `zut --rpc` so third-party apps can
804	// spawn the binary with a clean argv. Strip the leading 'rpc'
805	// token and let the rest flow through the normal arg parser.
806	if len(rawArgs) > 0 && rawArgs[0] == "rpc" {
807		rawArgs = append([]string{"--rpc"}, rawArgs[1:]...)
808	}
809
810	if fi, err := os.Stdin.Stat(); err == nil {
811		rawArgs = argsForStdin(rawArgs, fi.Mode())
812	}
813	args, err := ParseArgs(rawArgs)
814	if err != nil {
815		PrintHelp(version)
816		return err
817	}
818	if args.Help {
819		PrintHelp(version)
820		return nil
821	}
822	if args.Version {
823		fmt.Println("zut", version)
824		return nil
825	}
826	// Reject invalid orchestration combinations before catalog repair or model
827	// refresh can mutate local state or launch background work.
828	if err := validateOrchestrationArgs(args); err != nil {
829		return err
830	}
831	// Model catalog: load any cached discovery data before we inspect
832	// the model list (list-models, print/json, interactive).
833	prepareRuntimeCatalog()
834
835	if args.ListModels {
836		printModels()
837		return nil
838	}
839
840	return runWithArgs(args, version)
841}
842
843func runWithArgs(args Args, version string) error {
844	if err := validateOrchestrationArgs(args); err != nil {
845		return err
846	}
847	ctx := context.Background()
848	switch args.Mode {
849	case ModePrint:
850		return runPrintMode(ctx, args, version)
851	case ModeStream:
852		return runStreamMode(ctx, args, version)
853	case ModeJSON:
854		return runJSONMode(ctx, args, version)
855	case ModeRPC:
856		return runRPCMode(ctx, args, version)
857	case ModeSubagentWorker:
858		return runSubagentWorkerMode(ctx, args, version)
859	default:
860		return runInteractive(ctx, args, version)
861	}
862}
863
864// ---- print / json modes: require credentials, run single-shot ----
865
866// nonInteractiveExtHooks is the HostHooks impl used by print / json
867// modes. They have no TUI, so notify / display go to stderr and
868// submit / insert are no-ops (the extension can't steer a
869// single-shot run once it's in flight anyway).
870type nonInteractiveExtHooks struct{}
871
872func (nonInteractiveExtHooks) Notify(ext, level, message string) {
873	fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", ext, level, message)
874}
875func (nonInteractiveExtHooks) Alert(string, extproto.AlertRequest)                  {}
876func (nonInteractiveExtHooks) Submit(string)                                        {}
877func (nonInteractiveExtHooks) SubmitSlash(string)                                   {}
878func (nonInteractiveExtHooks) Insert(string)                                        {}
879func (nonInteractiveExtHooks) Display(string, string)                               {}
880func (nonInteractiveExtHooks) ClearNotes(string)                                    {}
881func (nonInteractiveExtHooks) OpenPanel(string, extproto.PanelSpec)                 {}
882func (nonInteractiveExtHooks) UpdatePanel(string, string, string, []string, string) {}
883func (nonInteractiveExtHooks) ClosePanel(string, string)                            {}
884func (nonInteractiveExtHooks) SetStatus(string, string, string, string)             {}
885func (nonInteractiveExtHooks) SetWidget(string, string, string, string, []string)   {}
886func (nonInteractiveExtHooks) ClearWidget(string, string)                           {}
887
888// setupNonInteractiveExtensions loads --ext paths and (unless
889// --no-ext) runs discovery. Returns the manager so the caller can
890// wire tools into the resolved registry, and a cleanup closure to
891// defer. Mirrors the interactive-mode setup minus the TUI hooks.
892func setupNonInteractiveExtensions(ctx context.Context, args Args, r *Resolved, version string) (*extensions.Manager, func()) {
893	extMgr := extensions.New(ZutHome(), r.CWD, version, r.Provider, r.Model, nonInteractiveExtHooks{})
894	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
895		fmt.Fprintln(os.Stderr, "extension load:", e)
896	}
897	if !args.NoExt {
898		for _, e := range extMgr.Discover(ctx) {
899			fmt.Fprintln(os.Stderr, "extension load:", e)
900		}
901	}
902	extMgr.WaitForReady(3 * time.Second)
903	r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
904	return extMgr, func() { extMgr.Stop(2 * time.Second) }
905}
906
907// wireNonInteractiveAgentExtHooks installs the same BeforeToolExecute
908// / BeforeTurn / BeforeAssistantMessage / OnEvent hooks the
909// interactive path wires up, so extensions get their normal
910// event-intercept surface in print / json / rpc flows too.
911func wireNonInteractiveAgentExtHooks(ctx context.Context, ag *core.Agent, extMgr *extensions.Manager) {
912	if ag == nil || extMgr == nil {
913		return
914	}
915	ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
916		res := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
917		if res.Block {
918			return false, res.Reason, nil
919		}
920		return true, "", res.ModifiedArgs
921	}
922	ag.BeforeTurnContext = func(turnCtx context.Context, step int) (bool, string, string) {
923		res := extMgr.InterceptTurnStart(turnCtx, step)
924		return !res.Block, res.Reason, res.Context
925	}
926	ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
927		res := extMgr.InterceptAssistantMessage(ctx, text)
928		if res.Block {
929			return false, res.Reason, ""
930		}
931		return true, "", res.ReplaceText
932	}
933	ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
934}
935
936type printStats struct {
937	Provider              string `json:"provider"`
938	Model                 string `json:"model"`
939	PromptTokens          int    `json:"prompt_tokens"`
940	ReasoningTokens       *int   `json:"reasoning_tokens"`
941	GeneratedOutputTokens int    `json:"generated_output_tokens"`
942	ElapsedMS             int64  `json:"elapsed_ms"`
943}
944
945func writePrintStats(path, providerID, model string, usage provider.Usage, elapsed time.Duration) error {
946	var reasoning *int
947	generated := usage.OutputTokens
948	if usage.ReasoningTokensKnown {
949		count := usage.ReasoningTokens
950		reasoning = &count
951		generated -= count
952		if generated < 0 {
953			generated = 0
954		}
955	}
956	stats := printStats{
957		Provider:              providerID,
958		Model:                 model,
959		PromptTokens:          usage.InputTokens + usage.CacheReadTokens + usage.CacheWriteTokens,
960		ReasoningTokens:       reasoning,
961		GeneratedOutputTokens: generated,
962		ElapsedMS:             elapsed.Milliseconds(),
963	}
964	data, err := json.MarshalIndent(stats, "", "  ")
965	if err != nil {
966		return fmt.Errorf("encode stats: %w", err)
967	}
968	data = append(data, '\n')
969	if err := os.WriteFile(path, data, 0o644); err != nil {
970		return fmt.Errorf("write stats %q: %w", path, err)
971	}
972	return nil
973}
974
975func runPrintMode(ctx context.Context, args Args, version string) (runErr error) {
976	if args.Orchestrate {
977		return runOrchestratedPrintMode(ctx, args, version)
978	}
979	if args.NoYolo {
980		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in print mode (no interactive prompt available); tools will run without confirmation")
981	}
982	r, err := Resolve(args, true)
983	if err != nil {
984		return err
985	}
986	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
987	defer stopExt()
988
989	ag := r.NewAgent()
990	initialAg := ag
991	defer func() {
992		closeAgentLSP(ag)
993		if ag != initialAg {
994			closeAgentLSP(initialAg)
995		}
996	}()
997	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
998	sess, err := openOrCreateSession(ctx, args, r, ag, version)
999	if err != nil {
1000		return err
1001	}
1002	if sess != nil {
1003		var providerName, model string
1004		sess, ag, providerName, model, err = applyInitialSessionResume(ctx, args, r, extMgr, sess, ag)
1005		if err != nil {
1006			return err
1007		}
1008		r.Provider, r.Model = providerName, model
1009		ag.CommitToolResult = func(_ string, result core.ToolResult) error { return persistToolResultState(extMgr, sess, result) }
1010		defer func() { runErr = joinSessionCloseError(runErr, sess) }()
1011	}
1012	announceSession(extMgr, sess)
1013	wireRetryLifecyclePersistence(ag, sess)
1014	if sess != nil {
1015		defer func() { runErr = errors.Join(runErr, sess.FlushRetryLifecycle(ag.LastTurnUsage(), ag.Cost())) }()
1016	}
1017
1018	piped, _ := readAllStdin()
1019	prompt := combinePromptInput(piped, args.Prompt)
1020	if prompt == "" {
1021		return fmt.Errorf("print mode requires a prompt (arg or stdin)")
1022	}
1023
1024	start := len(ag.Messages())
1025	if err := runZutfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, nil, os.Stderr); err != nil {
1026		return err
1027	}
1028	if err := reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag); err != nil {
1029		return err
1030	}
1031	var persistCompaction func([]provider.Message) error
1032	if sess != nil {
1033		persistCompaction = sess.AppendCompaction
1034	}
1035	started := time.Now()
1036	usage, recovery, err := modes.RunPrintWithContextRecovery(ctx, ag, prompt, nil, os.Stdout, persistCompaction)
1037	elapsed := time.Since(started)
1038	transcriptStart := start
1039	if recovery.Compacted {
1040		transcriptStart = recovery.OutputStart
1041	}
1042	if persistErr := WriteNewTranscript(ag, sess, transcriptStart); persistErr != nil {
1043		if err != nil {
1044			return errors.Join(err, persistErr)
1045		}
1046		return persistErr
1047	}
1048	if err != nil {
1049		return err
1050	}
1051	if args.StatsPath != "" {
1052		return writePrintStats(args.StatsPath, r.Provider, r.Model, usage, elapsed)
1053	}
1054	return nil
1055}
1056
1057func runStreamMode(ctx context.Context, args Args, version string) (runErr error) {
1058	if args.Orchestrate {
1059		return runOrchestratedStreamMode(ctx, args, version)
1060	}
1061	if args.NoYolo {
1062		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in stream mode (no interactive prompt available); tools will run without confirmation")
1063	}
1064	r, err := Resolve(args, true)
1065	if err != nil {
1066		return err
1067	}
1068	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
1069	defer stopExt()
1070
1071	ag := r.NewAgent()
1072	initialAg := ag
1073	defer func() {
1074		closeAgentLSP(ag)
1075		if ag != initialAg {
1076			closeAgentLSP(initialAg)
1077		}
1078	}()
1079	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
1080	sess, err := openOrCreateSession(ctx, args, r, ag, version)
1081	if err != nil {
1082		return err
1083	}
1084	if sess != nil {
1085		var providerName, model string
1086		sess, ag, providerName, model, err = applyInitialSessionResume(ctx, args, r, extMgr, sess, ag)
1087		if err != nil {
1088			return err
1089		}
1090		r.Provider, r.Model = providerName, model
1091		ag.CommitToolResult = func(_ string, result core.ToolResult) error { return persistToolResultState(extMgr, sess, result) }
1092		defer func() { runErr = joinSessionCloseError(runErr, sess) }()
1093	}
1094	announceSession(extMgr, sess)
1095	wireRetryLifecyclePersistence(ag, sess)
1096	if sess != nil {
1097		defer func() { runErr = errors.Join(runErr, sess.FlushRetryLifecycle(ag.LastTurnUsage(), ag.Cost())) }()
1098	}
1099
1100	piped, _ := readAllStdin()
1101	prompt := combinePromptInput(piped, args.Prompt)
1102	if prompt == "" {
1103		return fmt.Errorf("stream mode requires a prompt (arg or stdin)")
1104	}
1105
1106	start := len(ag.Messages())
1107	preSink, finishPre := newStreamTextSink(os.Stdout)
1108	if err := runZutfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
1109		finishPre()
1110		return err
1111	}
1112	finishPre()
1113	if err := reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag); err != nil {
1114		return err
1115	}
1116	var persistCompaction func([]provider.Message) error
1117	if sess != nil {
1118		persistCompaction = sess.AppendCompaction
1119	}
1120	recovery, err := modes.RunStreamWithContextRecovery(ctx, ag, prompt, nil, os.Stdout, os.Stderr, persistCompaction)
1121	transcriptStart := start
1122	if recovery.Compacted {
1123		transcriptStart = recovery.OutputStart
1124	}
1125	if persistErr := WriteNewTranscript(ag, sess, transcriptStart); persistErr != nil {
1126		if err != nil {
1127			return errors.Join(err, persistErr)
1128		}
1129		return persistErr
1130	}
1131	return err
1132}
1133
1134func newStreamTextSink(out io.Writer) (func(core.AgentEvent), func()) {
1135	var streamed, wroteText, lastWasNL bool
1136	writeText := func(text string) {
1137		if text == "" {
1138			return
1139		}
1140		_, _ = fmt.Fprint(out, text)
1141		if syncer, ok := out.(interface{ Sync() error }); ok {
1142			_ = syncer.Sync()
1143		}
1144		wroteText = true
1145		lastWasNL = strings.HasSuffix(text, "\n")
1146	}
1147	sink := func(ev core.AgentEvent) {
1148		switch e := ev.(type) {
1149		case core.EvAssistantStart:
1150			streamed = false
1151		case core.EvTextDelta:
1152			streamed = true
1153			writeText(e.Delta)
1154		case core.EvAssistantMessage:
1155			if streamed {
1156				return
1157			}
1158			var text strings.Builder
1159			for _, content := range e.Message.Content {
1160				if block, ok := content.(provider.TextBlock); ok {
1161					if text.Len() > 0 {
1162						text.WriteString("\n")
1163					}
1164					text.WriteString(block.Text)
1165				}
1166			}
1167			writeText(text.String())
1168		}
1169	}
1170	finish := func() {
1171		if wroteText && !lastWasNL {
1172			writeText("\n")
1173		}
1174	}
1175	return sink, finish
1176}
1177
1178func runJSONMode(ctx context.Context, args Args, version string) (runErr error) {
1179	if args.Orchestrate {
1180		return runOrchestratedJSONMode(ctx, args, version)
1181	}
1182	if args.NoYolo {
1183		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in json mode (no interactive prompt available); tools will run without confirmation")
1184	}
1185	r, err := Resolve(args, true)
1186	if err != nil {
1187		return err
1188	}
1189	extMgr, stopExt := setupNonInteractiveExtensions(ctx, args, &r, version)
1190	defer stopExt()
1191
1192	ag := r.NewAgent()
1193	initialAg := ag
1194	defer func() {
1195		closeAgentLSP(ag)
1196		if ag != initialAg {
1197			closeAgentLSP(initialAg)
1198		}
1199	}()
1200	wireNonInteractiveAgentExtHooks(ctx, ag, extMgr)
1201	sess, err := openOrCreateSession(ctx, args, r, ag, version)
1202	if err != nil {
1203		return err
1204	}
1205	if sess != nil {
1206		var providerName, model string
1207		sess, ag, providerName, model, err = applyInitialSessionResume(ctx, args, r, extMgr, sess, ag)
1208		if err != nil {
1209			return err
1210		}
1211		r.Provider, r.Model = providerName, model
1212		ag.CommitToolResult = func(_ string, result core.ToolResult) error { return persistToolResultState(extMgr, sess, result) }
1213		defer func() { runErr = joinSessionCloseError(runErr, sess) }()
1214	}
1215	announceSession(extMgr, sess)
1216	wireRetryLifecyclePersistence(ag, sess)
1217	if sess != nil {
1218		defer func() { runErr = errors.Join(runErr, sess.FlushRetryLifecycle(ag.LastTurnUsage(), ag.Cost())) }()
1219	}
1220
1221	piped, _ := readAllStdin()
1222	prompt := combinePromptInput(piped, args.Prompt)
1223	if prompt == "" {
1224		return fmt.Errorf("json mode requires a prompt (arg or stdin)")
1225	}
1226
1227	start := len(ag.Messages())
1228	enc := json.NewEncoder(os.Stdout)
1229	preSink := func(ev core.AgentEvent) {
1230		_ = enc.Encode(modes.EventToJSON(ev))
1231	}
1232	if err := runZutfileStartupPre(ctx, args.StartupPre, r.CWD, r.Sandbox, ag, preSink, os.Stderr); err != nil {
1233		_ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
1234		return err
1235	}
1236	if err := reloadResourcesAfterStartupPre(ctx, args, extMgr, r.Sandbox, ag); err != nil {
1237		_ = enc.Encode(map[string]any{"type": "error", "message": err.Error()})
1238		return err
1239	}
1240	var persistCompaction func([]provider.Message) error
1241	if sess != nil {
1242		persistCompaction = sess.AppendCompaction
1243	}
1244	recovery, err := modes.RunJSONWithContextRecovery(ctx, ag, prompt, nil, os.Stdout, persistCompaction)
1245	transcriptStart := start
1246	if recovery.Compacted {
1247		transcriptStart = recovery.OutputStart
1248	}
1249	if persistErr := WriteNewTranscript(ag, sess, transcriptStart); persistErr != nil {
1250		finalErr := persistErr
1251		if err != nil {
1252			finalErr = errors.Join(err, persistErr)
1253		}
1254		_ = enc.Encode(map[string]any{"type": "error", "message": finalErr.Error()})
1255		return finalErr
1256	}
1257	return err
1258}
1259
1260// runZutfileStartupPre runs entry.pre before the main non-interactive prompt.
1261// "!command" values execute via BashTool; other values are sent as an agent turn.
1262// shellOut receives live shell chunks (typically os.Stderr); sink receives
1263// agent events for plain-text pre (stream mode wires a live text sink).
1264func runZutfileStartupPre(ctx context.Context, pre, cwd string, sandbox *tools.Sandbox, ag *core.Agent, sink func(core.AgentEvent), shellOut io.Writer) error {
1265	pre = strings.TrimSpace(pre)
1266	if pre == "" {
1267		return nil
1268	}
1269	if cmd, ok := modes.ShellEscapeCommand(pre); ok {
1270		raw, err := json.Marshal(map[string]any{"command": cmd})
1271		if err != nil {
1272			return err
1273		}
1274		if shellOut != nil {
1275			fmt.Fprintf(shellOut, "$ %s\n", cmd)
1276			if f, ok := shellOut.(interface{ Sync() error }); ok {
1277				_ = f.Sync()
1278			}
1279		}
1280		progress := func(chunk string) {
1281			if shellOut == nil || chunk == "" {
1282				return
1283			}
1284			fmt.Fprint(shellOut, chunk)
1285			if f, ok := shellOut.(interface{ Sync() error }); ok {
1286				_ = f.Sync()
1287			}
1288		}
1289		bash := &tools.BashTool{CWD: cwd, Sandbox: sandbox}
1290		res, err := bash.Execute(ctx, raw, progress)
1291		if err != nil {
1292			return fmt.Errorf("zutfile entry.pre: %w", err)
1293		}
1294		if res.IsError {
1295			var sb strings.Builder
1296			for _, c := range res.Content {
1297				if tb, ok := c.(provider.TextBlock); ok {
1298					sb.WriteString(tb.Text)
1299				}
1300			}
1301			msg := strings.TrimSpace(sb.String())
1302			if msg == "" {
1303				msg = "command failed"
1304			}
1305			return fmt.Errorf("zutfile entry.pre: %s", msg)
1306		}
1307		return nil
1308	}
1309	if ag == nil {
1310		return fmt.Errorf("zutfile entry.pre requires an agent for non-shell prompts")
1311	}
1312	if sink == nil {
1313		sink = func(core.AgentEvent) {}
1314	}
1315	return ag.Prompt(ctx, pre, nil, sink)
1316}
1317
1318var errInteractiveAgentChanged = errors.New("interactive agent or web-search policy changed during prompt refresh")
1319
1320// refreshAgentToolsAndPrompt re-resolves tools (including rediscovered
1321// skills and currently loaded extension tools) and updates the live
1322// agent's registry and system prompt. Used after /reload-ext and after
1323// zutfile entry.pre installs new skills or extensions.
1324// mutateRegistry, if non-nil, can inject session-specific tools (e.g. subagent_spawn).
1325// interactive, when non-nil, serializes the final commit with agent replacement.
1326func refreshAgentToolsAndPrompt(args Args, sharedSandbox *tools.Sandbox, extToolAdapter ExtensionToolSource, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry, interactive *modes.Interactive) (subagents.WebSearchPolicy, error) {
1327	if ag == nil {
1328		return subagents.WebSearchDeny, nil
1329	}
1330	var webSearchPolicyGeneration uint64
1331	if interactive != nil {
1332		// Capture before Resolve: the final commit must fail if settings,
1333		// Telegram attachment, or a newer registry commit changes policy while
1334		// filesystem/config/extension discovery is in flight.
1335		webSearchPolicyGeneration = interactive.WebSearchPolicyGeneration()
1336	}
1337	resolved, err := Resolve(args, true)
1338	if err != nil {
1339		return subagents.WebSearchDeny, fmt.Errorf("refresh agent prompt and tools: %w", err)
1340	}
1341	if sharedSandbox != nil {
1342		resolved.UseSandbox(sharedSandbox)
1343	}
1344	if extToolAdapter != nil {
1345		resolved.MergeExtensionTools(extToolAdapter)
1346	}
1347	reg := resolved.ToolRegistry
1348	if resolved.WebSearchPolicy != subagents.WebSearchAllow {
1349		delete(reg, "web_search")
1350	}
1351	if mutateRegistry != nil {
1352		reg = mutateRegistry(reg)
1353	}
1354	if interactive != nil {
1355		oldTools, applied := interactive.ApplyAgentPromptConfigAtWebSearchGeneration(ag, resolved.SystemPrompt, reg, webSearchPolicyGeneration)
1356		if !applied {
1357			_ = tools.CloseLSPManagers(reg)
1358			return subagents.WebSearchDeny, errInteractiveAgentChanged
1359		}
1360		interactive.DeferUntilIdle(func() {
1361			_ = tools.CloseLSPManagers(oldTools)
1362		})
1363		return webSearchPolicyForRegistry(resolved.WebSearchPolicy, ag.ToolsSnapshot()), nil
1364	}
1365	oldTools := ag.SetPromptConfig(resolved.SystemPrompt, reg)
1366	_ = tools.CloseLSPManagers(oldTools)
1367	return webSearchPolicyForRegistry(resolved.WebSearchPolicy, reg), nil
1368}
1369
1370func webSearchPolicyForRegistry(policy subagents.WebSearchPolicy, reg core.Registry) subagents.WebSearchPolicy {
1371	if policy == subagents.WebSearchAllow {
1372		if _, ok := reg["web_search"]; ok {
1373			return subagents.WebSearchAllow
1374		}
1375	}
1376	return subagents.WebSearchDeny
1377}
1378
1379func webSearchToolAllowedForSession(args Args) bool {
1380	if args.NoTools || args.PermissionSet != nil {
1381		return false
1382	}
1383	if args.ToolsSet || len(args.Tools) > 0 {
1384		return toolListContains(args.Tools, "web_search")
1385	}
1386	return true
1387}
1388
1389func webSearchExplicitlyEnabledForSession(args Args) bool {
1390	return !args.NoTools && args.PermissionSet == nil && (args.ToolsSet || len(args.Tools) > 0) && toolListContains(args.Tools, "web_search")
1391}
1392
1393// reloadResourcesAfterStartupPre reloads extensions (if any) and
1394// refreshes the agent tool registry + system prompt so skills/extensions
1395// installed by entry.pre are visible to the following turn.
1396func reloadResourcesAfterStartupPre(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent) error {
1397	_, err := reloadResourcesAfterStartupPreWithRegistry(ctx, args, extMgr, sharedSandbox, ag, nil)
1398	return err
1399}
1400
1401func reloadResourcesAfterStartupPreWithRegistry(ctx context.Context, args Args, extMgr *extensions.Manager, sharedSandbox *tools.Sandbox, ag *core.Agent, mutateRegistry func(core.Registry) core.Registry) (subagents.WebSearchPolicy, error) {
1402	if strings.TrimSpace(args.StartupPre) == "" || ag == nil {
1403		return subagents.WebSearchDeny, nil
1404	}
1405	adapter := &extToolAdapter{mgr: extMgr}
1406	if extMgr != nil {
1407		_ = extMgr.Reload(ctx, 2*time.Second)
1408	}
1409	return refreshAgentToolsAndPrompt(args, sharedSandbox, adapter, ag, mutateRegistry, nil)
1410}
1411
1412// ---- interactive mode: opens the TUI even without credentials ----
1413
1414func runInteractive(ctx context.Context, args Args, version string) (runErr error) {
1415	initialCfg, _ := LoadConfig()
1416	// Resolve WITHOUT requiring credentials.
1417	r, err := Resolve(args, false)
1418	if err != nil {
1419		return err
1420	}
1421
1422	authStore := AuthStoreFor()
1423	mgr := auth.NewManager(authStore)
1424	defer mgr.Close()
1425
1426	// Keep the sandbox pointer stable across agent rebuilds (login / model
1427	// switch). The Interactive UI toggles the lock via this pointer, and
1428	// rebuilt tool instances must share the same one so the lock sticks.
1429	sharedSandbox := r.Sandbox
1430
1431	// persistMu guards the active session and selection across the agent
1432	// loop, TUI callbacks, and session swaps. Declare it before tool
1433	// construction because subagent defaults must read the live selection too.
1434	var persistMu sync.Mutex
1435	// Serialize session transitions with persistence callbacks so a candidate
1436	// is read only after the old agent is flushed and cannot be overwritten by
1437	// an in-flight append before commit.
1438	var sessionTransitionMu sync.RWMutex
1439	activeProvider := r.Provider
1440	activeModel := r.Model
1441
1442	// Build the extension manager BEFORE the agent so we can fold
1443	// extension-defined tools into the registry. Attach the interactive
1444	// host after constructing it below so startup alerts can be buffered.
1445	var iv *modes.Interactive
1446	extHooks := &interactiveExtHooks{}
1447	extMgr := extensions.New(ZutHome(), r.CWD, version, r.Provider, r.Model, extHooks)
1448	var startupExtensionErrors []string
1449	// --ext paths first so they win against installed extensions of
1450	// the same name (loadOne's first-write-wins semantics).
1451	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
1452		startupExtensionErrors = append(startupExtensionErrors, e.Error())
1453	}
1454	// --no-ext skips the global + project-local discovery scan;
1455	// explicit --ext paths above are still honoured so you can run
1456	// "only this extension" with --no-ext --ext ./x.
1457	if !args.NoExt {
1458		for _, e := range extMgr.Discover(ctx) {
1459			startupExtensionErrors = append(startupExtensionErrors, e.Error())
1460		}
1461	}
1462	// Wait briefly for extensions to flush their initial register_tool
1463	// frames before we build the agent's tool registry. Half a second
1464	// is plenty for any extension that's actually well-behaved; ones
1465	// that don't send a ready frame eat the full grace and proceed.
1466	// 3s is the per-extension grace period for the ready frame.
1467	// Native binaries are instant; runtimes like `npx tsx` take ~1.5s
1468	// from cold cache. The wait is tight only for extensions that
1469	// haven't sent ready by then; ones that signalled earlier release
1470	// the wait immediately.
1471	extMgr.WaitForReady(3 * time.Second)
1472	defer extMgr.Stop(2 * time.Second)
1473
1474	extToolAdapter := &extToolAdapter{mgr: extMgr}
1475	r.MergeExtensionTools(extToolAdapter)
1476	webSearchGuard := &webSearchSessionGuard{}
1477
1478	// Keep the shared subagent runtime in the outer scope: session reloads,
1479	// dashboard updates, agent rebuilds, and shutdown all use the same owner.
1480	var runtime *subagentRuntime
1481	var subagentsMgr *subagents.Supervisor
1482	// These callbacks deliberately resolve iv lazily because the Interactive
1483	// instance is constructed after the agent and its registry.
1484	onSpawnedSupervisor := func(a *subagents.Agent, task string, required bool) {
1485		if iv != nil {
1486			iv.TrackSubagentWorker(a, task, required)
1487		}
1488	}
1489	onResumedSupervisor := func(a *subagents.Agent, prompt string, required bool) {
1490		if iv != nil {
1491			iv.TrackResumedSubagentWorker(a, prompt, required)
1492		}
1493	}
1494	onBeforeResumedSupervisor := func(a *subagents.Agent, prompt string, required bool) func() {
1495		if iv != nil {
1496			return iv.PrepareResumedSubagentWorker(a, prompt, required)
1497		}
1498		return nil
1499	}
1500	onStopRequestedSupervisor := func(a *subagents.Agent) {
1501		if iv != nil {
1502			iv.TrackStoppedSubagentWorker(a)
1503		}
1504	}
1505	activeProviderForSubagents := func() string {
1506		persistMu.Lock()
1507		defer persistMu.Unlock()
1508		return activeProvider
1509	}
1510	activeModelForSubagents := func() string {
1511		persistMu.Lock()
1512		defer persistMu.Unlock()
1513		return activeModel
1514	}
1515
1516	runtime = newSubagentRuntime(subagentRuntimeConfig{
1517		Context:         ctx,
1518		Args:            args,
1519		Root:            filepath.Join(ZutHome(), "subagents"),
1520		RepoRoot:        r.CWD,
1521		Provider:        r.Provider,
1522		Model:           r.Model,
1523		Reasoning:       r.Reasoning,
1524		BaseURL:         r.BaseURL,
1525		InsecureTLS:     r.InsecureTLS,
1526		FastMode:        r.FastMode,
1527		APIKey:          args.APIKey,
1528		Policy:          subagentPolicyFromConfig(initialCfg.Subagents),
1529		WebSearchPolicy: webSearchPolicyForRegistry(r.WebSearchPolicy, r.ToolRegistry),
1530		WebSearchGuard:  webSearchGuard,
1531		ActiveProvider:  activeProviderForSubagents,
1532		ActiveModel:     activeModelForSubagents,
1533		OnSpawned:       onSpawnedSupervisor,
1534		OnResumed:       onResumedSupervisor,
1535		BeforeResumed:   onBeforeResumedSupervisor,
1536		OnStopRequested: onStopRequestedSupervisor,
1537	})
1538	subagentsMgr = runtime.Supervisor()
1539	reloadDone := make(chan struct{})
1540	var reloadErrs []error
1541	runtime.SetRequiredWorkerReady(reloadDone, func() error {
1542		return errors.Join(reloadErrs...)
1543	})
1544	if subagentsMgr != nil {
1545		// Replaying historical event logs can take seconds. Populate the
1546		// detached-agent dashboard without blocking the first interactive paint.
1547		go func() {
1548			_, reloadErrs = subagentsMgr.Reload()
1549			close(reloadDone)
1550		}()
1551	} else {
1552		close(reloadDone)
1553	}
1554	defer func() {
1555		// Reload may attach detached workers, so let it finish before shutdown
1556		// snapshots the supervisor's worker set.
1557		<-reloadDone
1558		_ = closeSubagentRuntimeFresh(runtime)
1559	}()
1560
1561	prepareInteractiveRegistry := runtime.PrepareRegistry
1562	prepareResolvedInteractiveRegistry := runtime.PrepareResolvedRegistry
1563	prepareResolvedInteractiveRegistry(r.ToolRegistry, r.WebSearchPolicy)
1564	initialWebSearchPolicy := webSearchPolicyForRegistry(r.WebSearchPolicy, r.ToolRegistry)
1565	webSearchGuard.setAvailable(initialWebSearchPolicy == subagents.WebSearchAllow)
1566	runtime.SetWebSearchPolicy(initialWebSearchPolicy)
1567	resolveSubagent := runtime.resolveSubagent
1568
1569	// Confirmation gate: when --no-yolo is on, the agent must ask
1570	// the user before every tool call. In interactive mode the TUI
1571	// provides the Confirmer; in print/json/rpc modes there's no
1572	// way to prompt, so the gate is constructed with a nil inner
1573	// which auto-refuses every call with a helpful reason.
1574	var confirmGate *core.ConfirmGate
1575	if args.NoYolo {
1576		confirmGate = core.NewConfirmGate(nil) // set below for interactive
1577	}
1578
1579	// Capture current args in a closure so BuildAgent can re-resolve
1580	// after a successful login (picks up the newly stored credential).
1581	wireAgentExt := func(a *core.Agent) *core.Agent {
1582		if a == nil {
1583			return a
1584		}
1585		a.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
1586			// Guards run before confirmation because they may rewrite the
1587			// arguments. The user must approve the effective call that will
1588			// actually execute, not the model's original arguments.
1589			r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
1590			if r.Block {
1591				return false, r.Reason, nil
1592			}
1593			effectiveArgs := call.Arguments
1594			if len(r.ModifiedArgs) > 0 && json.Valid(r.ModifiedArgs) {
1595				effectiveArgs = r.ModifiedArgs
1596			}
1597			if confirmGate != nil {
1598				var content strings.Builder
1599				_, currentTools := a.PromptConfig()
1600				if tool, err := currentTools.Get(call.Name); err == nil {
1601					if previewer, ok := tool.(core.ToolPreviewer); ok {
1602						preview, err := previewer.Preview(ctx, effectiveArgs)
1603						if err != nil {
1604							return false, err.Error(), nil
1605						}
1606						for _, block := range preview.Content {
1607							if text, ok := block.(provider.TextBlock); ok {
1608								if content.Len() > 0 {
1609									content.WriteString("\n")
1610								}
1611								content.WriteString(text.Text)
1612							}
1613						}
1614					}
1615				}
1616				ok, reason, _ := confirmGate.CheckToolCall(core.ToolCallConfirmation{
1617					ID:      call.ID,
1618					Name:    call.Name,
1619					Summary: core.BuildPreview(effectiveArgs, 120),
1620					Content: content.String(),
1621					Origin:  call.Origin,
1622				})
1623				if !ok {
1624					return false, reason, nil
1625				}
1626			}
1627			return true, "", r.ModifiedArgs
1628		}
1629		a.BeforeTurnContext = func(turnCtx context.Context, step int) (bool, string, string) {
1630			r := extMgr.InterceptTurnStart(turnCtx, step)
1631			return !r.Block, r.Reason, r.Context
1632		}
1633		a.BeforeAssistantMessage = func(text string) (bool, string, string) {
1634			r := extMgr.InterceptAssistantMessage(ctx, text)
1635			if r.Block {
1636				return false, r.Reason, ""
1637			}
1638			return true, "", r.ReplaceText
1639		}
1640		a.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
1641		runtime.WireRequiredWorkerGate(a)
1642		return a
1643	}
1644
1645	var ag *core.Agent
1646	buildAgent := func() (*core.Agent, string, string, error) {
1647		resolved, err := Resolve(args, true)
1648		if err != nil {
1649			return nil, "", "", err
1650		}
1651		resolved.UseSandbox(sharedSandbox)
1652		runtime.SetProvider(resolved.Provider)
1653		runtime.SetProviderSettings(resolved.BaseURL, resolved.InsecureTLS)
1654		runtime.SetFastMode(resolved.FastMode)
1655		resolved.MergeExtensionTools(extToolAdapter)
1656		prepareResolvedInteractiveRegistry(resolved.ToolRegistry, resolved.WebSearchPolicy)
1657		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
1658	}
1659
1660	// Rebuild agent with an explicit provider/model override.
1661	buildAgentFor := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1662		next := args
1663		if providerOverride != "" {
1664			next.Provider = providerOverride
1665		}
1666		if modelOverride != "" {
1667			next.Model = modelOverride
1668		}
1669		resolved, err := Resolve(next, true)
1670		if err != nil {
1671			return nil, "", "", err
1672		}
1673		resolved.UseSandbox(sharedSandbox)
1674		runtime.SetProvider(resolved.Provider)
1675		runtime.SetProviderSettings(resolved.BaseURL, resolved.InsecureTLS)
1676		runtime.SetFastMode(resolved.FastMode)
1677		resolved.MergeExtensionTools(extToolAdapter)
1678		prepareResolvedInteractiveRegistry(resolved.ToolRegistry, resolved.WebSearchPolicy)
1679		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
1680	}
1681
1682	// Rebuild agent for the rescue picker after a recoverable failure.
1683	// Unlike buildAgentFor, this drops launch-time --api-key and
1684	// --base-url overrides because those are typically the cause of the
1685	// rescue (a bad key, a typo'd base URL, or a corporate gateway that
1686	// only the originally-picked provider needed). Re-resolving without
1687	// them lets the rescue retry use env vars / auth.json / provider
1688	// defaults the way zut would have without the overrides.
1689	buildAgentForRescue := func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1690		next := args
1691		next.APIKey = ""
1692		next.BaseURL = ""
1693		if providerOverride != "" {
1694			next.Provider = providerOverride
1695		}
1696		if modelOverride != "" {
1697			next.Model = modelOverride
1698		}
1699		resolved, err := Resolve(next, true)
1700		if err != nil {
1701			return nil, "", "", err
1702		}
1703		resolved.UseSandbox(sharedSandbox)
1704		runtime.SetProvider(resolved.Provider)
1705		runtime.SetProviderSettings(resolved.BaseURL, resolved.InsecureTLS)
1706		runtime.SetFastMode(resolved.FastMode)
1707		resolved.MergeExtensionTools(extToolAdapter)
1708		prepareResolvedInteractiveRegistry(resolved.ToolRegistry, resolved.WebSearchPolicy)
1709		return wireAgentExt(resolved.NewAgent()), resolved.Provider, resolved.Model, nil
1710	}
1711
1712	if r.HasCredential() {
1713		ag = wireAgentExt(r.NewAgent())
1714	}
1715
1716	// /reload-ext callback: after the manager has respawned every
1717	// extension, re-resolve the tool registry (built-ins + freshly-
1718	// registered extension tools) and swap it onto the current
1719	// agent in-place. The current agent may have been replaced by a
1720	// /model swap since spawn, so re-read the live `ag` on each
1721	// invocation.
1722	extMgr.SetOnReload(func() {
1723		current := liveInteractiveAgent(iv, ag)
1724		if current == nil {
1725			return
1726		}
1727		if _, err := refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, prepareInteractiveRegistry, iv); err != nil && iv != nil {
1728			iv.ReportError(err)
1729		}
1730	})
1731
1732	var sess *core.Session
1733	var sessBaselineMsgs int // messages already on disk when current session opened
1734	var sessionTitlePending bool
1735	if !args.NoSess && ag != nil {
1736		var sessErr error
1737		sess, sessErr = openOrCreateSession(ctx, args, r, ag, version)
1738		if sessErr != nil {
1739			return sessErr
1740		}
1741		sessBaselineMsgs = len(ag.Messages())
1742		if sess != nil {
1743			// Startup resume uses the same provider/model-aware preparation as
1744			// the interactive session picker. This matters for --continue,
1745			// --resume, and explicit --session paths whose latest meta row was
1746			// written by another provider/model.
1747			candidate, resumeErr := applySessionResume(sess, ag, r.Provider, r.Model,
1748				strings.TrimSpace(args.Provider) != "", strings.TrimSpace(args.Model) != "", buildAgentFor)
1749			if resumeErr != nil {
1750				return resumeErr
1751			}
1752			sess = candidate.session
1753			ag = candidate.agent
1754			sessBaselineMsgs = candidate.fullMessageCount
1755			activeProvider = candidate.provider
1756			activeModel = candidate.model
1757			r.Provider = candidate.provider
1758			r.Model = candidate.model
1759		}
1760		if sess != nil && ag != nil {
1761			sessionTitlePending = sess.Meta.Parent != "" && sess.Title == "" && len(ag.Messages()) <= sess.Meta.ForkPoint
1762		}
1763	}
1764	announceSession(extMgr, sess)
1765	// Print the hint after the session close defer below and all terminal/TUI
1766	// cleanup defers. Close removes a fresh empty session, so only a session
1767	// that remains discoverable through the hinted command gets a hint.
1768	defer func() {
1769		if !iv.ExitedViaCtrlC() {
1770			return
1771		}
1772		persistMu.Lock()
1773		current := sess
1774		persistMu.Unlock()
1775		hasMessages := false
1776		if finalAg := iv.Agent(); finalAg != nil {
1777			hasMessages = finalAg.MessageCount() > 0
1778		}
1779		if resumeID := resumableSessionID(ZutHome(), current, hasMessages); resumeID != "" {
1780			fmt.Print(resumeSessionHint(resumeID))
1781		}
1782	}()
1783	defer func() {
1784		persistMu.Lock()
1785		defer persistMu.Unlock()
1786		runErr = joinSessionCloseError(runErr, sess)
1787	}()
1788
1789	// persistMessage is the per-message hook bound to the agent. It
1790	// appends each new transcript message to the live session as soon
1791	// as it lands, so a kill / closed terminal / OS crash costs at
1792	// most the in-flight turn instead of the whole session. The
1793	// baseline counter advances in lock-step so the exit-time flush
1794	// doesn't double-write rows already on disk.
1795	persistMessage := func(m provider.Message) {
1796		sessionTransitionMu.RLock()
1797		defer sessionTransitionMu.RUnlock()
1798		persistMu.Lock()
1799		defer persistMu.Unlock()
1800		if sess == nil {
1801			return
1802		}
1803		if err := sess.AppendMessage(m); err == nil {
1804			sessBaselineMsgs++
1805		}
1806	}
1807	persistUsage := func(cum provider.Usage) {
1808		sessionTransitionMu.RLock()
1809		defer sessionTransitionMu.RUnlock()
1810		persistMu.Lock()
1811		defer persistMu.Unlock()
1812		if sess == nil {
1813			return
1814		}
1815		_ = sess.AppendUsage(cum, cum)
1816	}
1817	persistRetryLifecycle := func(record core.RetryLifecycleRecord) {
1818		sessionTransitionMu.RLock()
1819		defer sessionTransitionMu.RUnlock()
1820		persistMu.Lock()
1821		defer persistMu.Unlock()
1822		if sess != nil {
1823			sess.RecordRetryLifecycle(record)
1824		}
1825	}
1826	persistCompaction := func(messages []provider.Message) {
1827		sessionTransitionMu.RLock()
1828		var session *extproto.SessionContext
1829		var states map[string]json.RawMessage
1830		persistMu.Lock()
1831		if sess != nil {
1832			if err := sess.AppendCompaction(messages); err == nil {
1833				sessBaselineMsgs = len(messages)
1834				session = sessionContext(sess)
1835				states = copyExtensionStates(sess.ExtensionState)
1836			}
1837		}
1838		persistMu.Unlock()
1839		sessionTransitionMu.RUnlock()
1840		if session != nil {
1841			extMgr.EmitSessionEvent("session_compacted", session, states)
1842		}
1843	}
1844	persistCompactHandoff := func(state json.RawMessage) error {
1845		sessionTransitionMu.RLock()
1846		defer sessionTransitionMu.RUnlock()
1847		persistMu.Lock()
1848		defer persistMu.Unlock()
1849		if sess == nil {
1850			return nil
1851		}
1852		return sess.UpdateCompactHandoff(state)
1853	}
1854	currentCompactHandoff := func() json.RawMessage {
1855		persistMu.Lock()
1856		defer persistMu.Unlock()
1857		if sess == nil {
1858			return nil
1859		}
1860		return append(json.RawMessage(nil), sess.Meta.CompactHandoff...)
1861	}
1862	persistGoal := func(goal *core.SessionGoal) error {
1863		sessionTransitionMu.RLock()
1864		defer sessionTransitionMu.RUnlock()
1865		persistMu.Lock()
1866		defer persistMu.Unlock()
1867		if sess == nil {
1868			return errors.New("session persistence is disabled")
1869		}
1870		return sess.UpdateGoal(goal)
1871	}
1872	ensureMission := func(objective string) error {
1873		sessionTransitionMu.RLock()
1874		defer sessionTransitionMu.RUnlock()
1875		persistMu.Lock()
1876		defer persistMu.Unlock()
1877		if sess == nil {
1878			return errors.New("session persistence is disabled")
1879		}
1880		return sess.EnsureMission(objective, core.MissionSourceUser)
1881	}
1882	currentGoal := func() *core.SessionGoal {
1883		persistMu.Lock()
1884		defer persistMu.Unlock()
1885		if sess == nil || sess.Meta.Goal == nil {
1886			return nil
1887		}
1888		goal := *sess.Meta.Goal
1889		return &goal
1890	}
1891	currentGoalHistory := func() []core.SessionGoal {
1892		persistMu.Lock()
1893		defer persistMu.Unlock()
1894		if sess == nil {
1895			return nil
1896		}
1897		return append([]core.SessionGoal(nil), sess.Meta.GoalHistory...)
1898	}
1899	bindAgentToolResultSession := func(a *core.Agent, boundSession *core.Session) {
1900		if a == nil {
1901			return
1902		}
1903		a.CommitToolResult = func(_ string, result core.ToolResult) error {
1904			persistMu.Lock()
1905			defer persistMu.Unlock()
1906			return persistToolResultState(extMgr, boundSession, result)
1907		}
1908	}
1909	wireAgentPersist := func(a *core.Agent) *core.Agent {
1910		if a == nil {
1911			return a
1912		}
1913		persistMu.Lock()
1914		currentSession := sess
1915		persistMu.Unlock()
1916		if currentSession != nil {
1917			a.SetSessionTimeContext(currentSession.Meta.Started, currentSession.Meta.Timezone, currentSession.Meta.TimezoneOffset)
1918		}
1919		a.OnMessageAppended = persistMessage
1920		a.OnUsage = persistUsage
1921		a.OnRetryLifecycle = persistRetryLifecycle
1922		a.OnTranscriptCompacted = persistCompaction
1923		bindAgentToolResultSession(a, currentSession)
1924		return a
1925	}
1926	wireAgentPersist(ag)
1927	defer func() {
1928		closeAgentLSP(liveInteractiveAgent(iv, ag))
1929		closeResolvedLSP(r)
1930	}()
1931
1932	// Re-wrap the build closures so any agent constructed by the TUI
1933	// (login, /model swap to a different provider) also gets the
1934	// persistence hooks. Without this, switching provider would
1935	// silently revert to the old in-memory-only behaviour. Selection state
1936	// is published by the successful transition itself, not by preparation.
1937	baseBuildAgent := buildAgent
1938	buildAgent = func() (*core.Agent, string, string, error) {
1939		a, p, m, err := baseBuildAgent()
1940		return wireAgentPersist(a), p, m, err
1941	}
1942	baseBuildAgentFor := buildAgentFor
1943	buildAgentFor = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1944		a, p, m, err := baseBuildAgentFor(providerOverride, modelOverride)
1945		return wireAgentPersist(a), p, m, err
1946	}
1947	baseBuildAgentForRescue := buildAgentForRescue
1948	buildAgentForRescue = func(providerOverride, modelOverride string) (*core.Agent, string, string, error) {
1949		a, p, m, err := baseBuildAgentForRescue(providerOverride, modelOverride)
1950		return wireAgentPersist(a), p, m, err
1951	}
1952
1953	// loadSession replaces the current session with the one at path and
1954	// hands its messages to the agent. Used by the /sessions picker.
1955	loadSession := func(path string) (loadErr error) {
1956		// Hold the transition lock from the pre-flush through the commit.
1957		// Persistence callbacks take the read side, so an active session
1958		// cannot be snapshotted before its lazy writes land or overwritten by
1959		// a callback while the candidate is being installed.
1960		sessionTransitionMu.Lock()
1961		defer sessionTransitionMu.Unlock()
1962
1963		currentAg := liveInteractiveAgent(iv, ag)
1964		if currentAg == nil {
1965			return fmt.Errorf("no agent running; log in first")
1966		}
1967
1968		persistMu.Lock()
1969		currentProvider := activeProvider
1970		currentModel := activeModel
1971		oldSess := sess
1972		// Flush before reading the candidate. Use the locked form rather
1973		// than the public callback, which would acquire the read lock held
1974		// by this transition.
1975		if oldSess != nil {
1976			next, flushErr := writeNewTranscriptLocked(currentAg, oldSess, sessBaselineMsgs)
1977			sessBaselineMsgs = next
1978			if flushErr != nil {
1979				persistMu.Unlock()
1980				return fmt.Errorf("flush current session: %w", flushErr)
1981			}
1982		}
1983		currentMessageCount := len(currentAg.Messages())
1984		currentCost := currentAg.Cost()
1985		persistMu.Unlock()
1986
1987		// A candidate build must not publish its provider/model as the live
1988		// selection before the candidate commits. The builder also stages
1989		// provider settings on the shared runtime, so restore those settings on
1990		// every failed path, including errors returned during preparation.
1991		runtimeConfig := runtime.snapshotConfiguration()
1992		committed := false
1993		var candidate sessionResumeCandidate
1994		defer func() {
1995			if !committed {
1996				runtime.restoreConfiguration(runtimeConfig)
1997				loadErr = joinSessionCloseError(loadErr, candidate.session)
1998			}
1999		}()
2000		candidate, err := prepareSessionResume(path, currentAg, currentProvider, currentModel, baseBuildAgentFor)
2001		if err != nil {
2002			// prepareSessionResume closes its append handle on failure;
2003			// no live agent or session has been changed.
2004			return err
2005		}
2006
2007		// Wire the private candidate before it can become visible. This is
2008		// also required for legacy same-provider resumes, where the current
2009		// agent is reused and only its transcript/usage are refreshed.
2010		wireAgentPersist(candidate.agent)
2011
2012		persistMu.Lock()
2013		// A provider rebuild ran outside persistMu. Refuse to install it if
2014		// the live agent, session, selection, transcript, or cost changed in
2015		// the meantime; otherwise a slow resume could discard a newer turn or
2016		// model swap.
2017		live := liveInteractiveAgent(iv, ag)
2018		changed := sess != oldSess || activeProvider != currentProvider || activeModel != currentModel || live != currentAg
2019		if !changed && live != nil {
2020			changed = len(live.Messages()) != currentMessageCount || live.Cost() != currentCost
2021		}
2022		if changed {
2023			persistMu.Unlock()
2024			return fmt.Errorf("session changed while loading; please try again")
2025		}
2026		newStates := copyExtensionStates(candidate.session.ExtensionState)
2027		var oldCloseErr error
2028		if oldSess != nil {
2029			oldCloseErr = oldSess.Close()
2030		}
2031		sess = candidate.session
2032		bindAgentToolResultSession(candidate.agent, candidate.session)
2033		candidate.agent.SetSessionTimeContext(candidate.session.Meta.Started, candidate.session.Meta.Timezone, candidate.session.Meta.TimezoneOffset)
2034		sessionTitlePending = candidate.session != nil && candidate.session.Meta.Parent != "" && candidate.session.Title == "" && candidate.fullMessageCount <= candidate.session.Meta.ForkPoint
2035		// The live agent only receives a compact resume window, but the
2036		// session file remains intact. Keep the persistence baseline at
2037		// the original on-disk message count so future turns append after
2038		// the full session instead of duplicating the hydrated tail.
2039		sessBaselineMsgs = candidate.fullMessageCount
2040
2041		if candidate.rebuilt {
2042			// Commit the TUI agent while persistMu still protects the session
2043			// writer, so no new message can land on the old file between the
2044			// two state changes.
2045			if iv != nil {
2046				iv.ApplySessionAgentWithCompactHandoff(candidate.agent, candidate.provider, candidate.model, candidate.session.Meta.CompactHandoff)
2047			}
2048			ag = candidate.agent
2049		} else {
2050			currentAg.SetMessages(candidate.messages)
2051			currentAg.SeedCost(candidate.cumulative)
2052			currentAg.SeedLastTurnUsage(candidate.lastTurn)
2053			ag = currentAg
2054		}
2055		activeProvider = candidate.provider
2056		activeModel = candidate.model
2057		if subagentsMgr != nil && candidate.session != nil {
2058			// Keep the dashboard scope in the same commit as the session,
2059			// agent, usage, and persistence baseline.
2060			if iv != nil {
2061				iv.SetSubagentSessionScope(candidate.session.ID)
2062			} else {
2063				runtime.SetActiveSession(candidate.session.ID)
2064			}
2065		}
2066		committed = true
2067		persistMu.Unlock()
2068		if iv != nil {
2069			iv.RefreshGoal()
2070		}
2071		if candidate.session.Meta.Parent != "" {
2072			extMgr.EmitSessionEvent("session_forked", sessionContext(candidate.session), newStates)
2073		}
2074		extMgr.EmitSessionEvent("session_switched", sessionContext(candidate.session), newStates)
2075		if oldCloseErr != nil {
2076			return fmt.Errorf("close current session: %w", oldCloseErr)
2077		}
2078		return nil
2079	}
2080
2081	// changeCWD switches the running session to a new working directory.
2082	// Wired into InteractiveConfig.ChangeCWD and invoked by the hidden
2083	// /cd slash command (which itself is only fired by the workspaces
2084	// extension's panel-key Enter handler today; the user can type /cd
2085	// directly but it's not in autocomplete / help / the README).
2086	//
2087	// Steps, in order:
2088	//   1. resolve + validate the new path (~ expansion, abs/rel)
2089	//   2. stage the candidate cwd, sandbox, and subagent state
2090	//   3. rebuild the agent and allocate its new session
2091	//   4. commit all new state together, closing the old session last
2092	//   5. push the committed state into the running Interactive
2093	//
2094	// The /jail state is preserved verbatim: if the sandbox was locked
2095	// to the old cwd, it stays locked, just re-pointed at the new one.
2096	changeCWD := func(path string) error {
2097		sessionTransitionMu.Lock()
2098		defer sessionTransitionMu.Unlock()
2099		if path == "" {
2100			return fmt.Errorf("empty path")
2101		}
2102		// ~ expansion.
2103		if path == "~" || strings.HasPrefix(path, "~/") {
2104			home, herr := os.UserHomeDir()
2105			if herr != nil || home == "" {
2106				return fmt.Errorf("cannot expand ~: %v", herr)
2107			}
2108			if path == "~" {
2109				path = home
2110			} else {
2111				path = filepath.Join(home, path[2:])
2112			}
2113		}
2114		if !filepath.IsAbs(path) {
2115			path = filepath.Join(args.CWD, path)
2116		}
2117		absPath, err := filepath.Abs(path)
2118		if err != nil {
2119			return err
2120		}
2121		info, err := os.Stat(absPath)
2122		if err != nil {
2123			return err
2124		}
2125		if !info.IsDir() {
2126			return fmt.Errorf("not a directory: %s", absPath)
2127		}
2128
2129		currentAg := liveInteractiveAgent(iv, ag)
2130		if currentAg == nil {
2131			return fmt.Errorf("no agent running; log in first")
2132		}
2133
2134		// Stage the candidate state while retaining a complete rollback
2135		// snapshot. A failed rebuild or session allocation must leave the
2136		// current agent, session, sandbox, and subagent root usable.
2137		oldCWD := args.CWD
2138		oldResolvedCWD := r.CWD
2139		oldPermissionSet := args.PermissionSet
2140		persistMu.Lock()
2141		oldActiveProvider := activeProvider
2142		oldActiveModel := activeModel
2143		persistMu.Unlock()
2144		runtimeConfig := runtime.snapshotConfiguration()
2145		oldSandboxRoot := ""
2146		oldSandboxLocked := false
2147		if sharedSandbox != nil {
2148			oldSandboxRoot = sharedSandbox.Root
2149			oldSandboxLocked = sharedSandbox.Locked()
2150		}
2151		rollback := func() {
2152			args.CWD = oldCWD
2153			r.CWD = oldResolvedCWD
2154			args.PermissionSet = oldPermissionSet
2155			persistMu.Lock()
2156			activeProvider = oldActiveProvider
2157			activeModel = oldActiveModel
2158			persistMu.Unlock()
2159			runtime.restoreConfiguration(runtimeConfig)
2160			if sharedSandbox != nil {
2161				sharedSandbox.Root = oldSandboxRoot
2162				if oldSandboxLocked {
2163					sharedSandbox.Lock()
2164				} else {
2165					sharedSandbox.Unlock()
2166				}
2167			}
2168		}
2169
2170		args.CWD = absPath
2171		r.CWD = absPath
2172		runtime.SetRepoRoot(absPath)
2173		if args.PermissionSet != nil {
2174			expanded := args.PermissionSet.Expand(absPath, args.AgentDataDir)
2175			args.PermissionSet = &expanded
2176		}
2177		if sharedSandbox != nil {
2178			sharedSandbox.Root = absPath
2179			if oldSandboxLocked {
2180				sharedSandbox.Lock()
2181			} else {
2182				sharedSandbox.Unlock()
2183			}
2184		}
2185
2186		// Rebuild the agent so tools / AGENTS.md / system prompt
2187		// re-bind to the new cwd. buildAgent() reads from args + r.
2188		newAg, newProvider, newModel, berr := buildAgent()
2189		if berr != nil {
2190			rollback()
2191			return fmt.Errorf("rebuild agent: %w", berr)
2192		}
2193
2194		// Fresh session in the new cwd's bucket. We bypass
2195		// openOrCreateSession's --continue / --resume branches
2196		// because /cd's semantics are "start fresh here", matching
2197		// what relaunching `zut --cwd <path>` would do today.
2198		var newSess *core.Session
2199		if !args.NoSess {
2200			newRoot := agentSessionsRoot(ZutHome(), args)
2201			core.PruneEmptySessions(newRoot, absPath)
2202			var serr error
2203			newSess, serr = core.NewSession(newRoot, absPath, newProvider, newModel, version)
2204			if serr != nil {
2205				rollback()
2206				return fmt.Errorf("open session in %s: %w", absPath, serr)
2207			}
2208		}
2209
2210		// Invalidate any title request before swapping the host-owned session
2211		// pointer. The interactive state reset below happens after the swap,
2212		// so this guard closes the window where a late result could otherwise
2213		// be written to the new session.
2214		if iv != nil {
2215			iv.CancelPendingSessionTitle()
2216		}
2217
2218		// Commit only after every fallible operation has succeeded. Close
2219		// the old session last so rollback never has to resurrect it.
2220		var newStates map[string]json.RawMessage
2221		var oldCloseErr error
2222		persistMu.Lock()
2223		if sess != nil {
2224			next, flushErr := writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
2225			sessBaselineMsgs = next
2226			if flushErr != nil {
2227				persistMu.Unlock()
2228				rollbackErr := joinSessionCloseError(fmt.Errorf("flush current session: %w", flushErr), newSess)
2229				rollback()
2230				return rollbackErr
2231			}
2232			oldCloseErr = sess.Close()
2233		}
2234		sess = newSess
2235		bindAgentToolResultSession(newAg, newSess)
2236		if newSess != nil {
2237			newAg.SetSessionTimeContext(newSess.Meta.Started, newSess.Meta.Timezone, newSess.Meta.TimezoneOffset)
2238			newStates = copyExtensionStates(newSess.ExtensionState)
2239		}
2240		sessBaselineMsgs = 0
2241		sessionTitlePending = false
2242		activeProvider = newProvider
2243		activeModel = newModel
2244		persistMu.Unlock()
2245		ag = newAg
2246		closeAgentLSP(currentAg)
2247
2248		// Push the new state into the running Interactive.
2249		if iv != nil {
2250			startupPaths := instructionContextPaths(loadAgentsContext(absPath, ZutHome()))
2251			iv.ApplyChangedCWDWithStartupContext(newAg, newProvider, newModel, absPath, startupPaths)
2252			iv.RefreshGoal()
2253		}
2254
2255		// Re-scope the subagent dashboard to the new session.
2256		if newSess != nil {
2257			if iv != nil {
2258				iv.SetSubagentSessionScope(newSess.ID)
2259			} else {
2260				runtime.SetActiveSession(newSess.ID)
2261			}
2262		}
2263		if newSess != nil {
2264			extMgr.EmitSessionEvent("session_opened", sessionContext(newSess), newStates)
2265		}
2266		if oldCloseErr != nil {
2267			return fmt.Errorf("close current session: %w", oldCloseErr)
2268		}
2269		return nil
2270	}
2271
2272	devBuild := isDevVersion(version)
2273	if devBuild {
2274		fmt.Fprintln(os.Stderr, "zut:", devVersionNotice)
2275	}
2276	term := tui.NewProcTerm()
2277
2278	var updateCh chan modes.UpdateInfo
2279	var changelogCh chan modes.ChangelogPayload
2280	if !devBuild {
2281		// Kick off the async update check so the banner can appear when the
2282		// http response eventually arrives (usually <1s on cached DNS). Map
2283		// agent.UpdateInfo -> modes.UpdateInfo here to avoid a cyclic import.
2284		updateCh = make(chan modes.UpdateInfo, 1)
2285		go func() {
2286			defer close(updateCh)
2287			src := <-CheckForUpdateAsync(ZutHome(), version)
2288			updateCh <- modes.UpdateInfo{
2289				Current:   src.Current,
2290				Latest:    src.Latest,
2291				Available: src.Available,
2292				URL:       src.URL,
2293			}
2294		}()
2295
2296		// Changelog: when the running version differs from the last
2297		// version whose release notes the user dismissed, fetch the
2298		// release body from GitHub and have the TUI show it once. On
2299		// first-ever launch (no prior LastChangelogShown), seed the
2300		// stored version silently — don't dump release notes at someone
2301		// who just installed.
2302		changelogCh = make(chan modes.ChangelogPayload, 1)
2303		go func() {
2304			defer close(changelogCh)
2305			cfg, _ := LoadConfig()
2306			if cfg.LastChangelogShown == "" {
2307				SeedChangelogVersion(version)
2308				return
2309			}
2310			if !ShouldShowChangelog(version, cfg) {
2311				return
2312			}
2313			info := <-FetchChangelogAsync(version)
2314			if info.Body == "" {
2315				return
2316			}
2317			changelogCh <- modes.ChangelogPayload{
2318				Version: info.Version,
2319				Body:    info.Body,
2320				URL:     info.URL,
2321			}
2322		}()
2323	}
2324
2325	fastMode := r.FastMode
2326	quickModelShortcuts := make([]modes.QuickModelShortcut, len(initialCfg.QuickModelShortcuts))
2327	for idx, s := range initialCfg.QuickModelShortcuts {
2328		quickModelShortcuts[idx] = modes.QuickModelShortcut{Provider: s.Provider, Model: s.Model}
2329	}
2330	theme, _, themeErr := tui.DetectThemeWithCustom(ZutHome(), initialCfg.Theme, 80*time.Millisecond)
2331	if themeErr != nil {
2332		fmt.Fprintln(os.Stderr, "theme load:", themeErr)
2333		if initialCfg.Theme != "" && !tui.ThemeExists(ZutHome(), initialCfg.Theme) {
2334			initialCfg.Theme = ""
2335			_ = SaveConfig(initialCfg)
2336		}
2337	}
2338
2339	// Scope the dashboard to the active host session. The runtime owns
2340	// shutdown separately and closes the supervisor exactly once.
2341	if sess != nil {
2342		runtime.SetActiveSession(sess.ID)
2343	}
2344
2345	var startupSkills []*skills.Skill
2346	if r.SkillTool != nil {
2347		startupSkills = r.SkillTool.Skills()
2348	}
2349	homeDir, _ := os.UserHomeDir()
2350	discoveredSubagents, _ := subagents.Discover(r.CWD, homeDir)
2351	subagentsAddendum := subagents.SystemPromptAddendum(discoveredSubagents)
2352	autoSubagentsToolAllowedForSession := autoSubagentsToolAllowed(args)
2353	autoSubagentsStatusToolAllowedForSession := autoSubagentsStatusToolAllowed(args)
2354	autoSubagentsStopToolAllowedForSession := autoSubagentsStopToolAllowed(args)
2355	autoSubagentsResumeToolAllowedForSession := autoSubagentsResumeToolAllowed(args)
2356	webSearchToolAllowedForInvocation := webSearchToolAllowedForSession(args)
2357	webSearchInvocationOverride := webSearchExplicitlyEnabledForSession(args)
2358	setWebSearchAvailable := func(available bool) {
2359		webSearchGuard.setAvailable(available)
2360		if subagentsMgr == nil {
2361			return
2362		}
2363		policy := subagents.WebSearchDeny
2364		if available {
2365			policy = subagents.WebSearchAllow
2366		}
2367		runtime.SetWebSearchPolicy(policy)
2368	}
2369
2370	iv = modes.NewInteractive(modes.InteractiveConfig{
2371		Terminal:                       term,
2372		Theme:                          theme,
2373		InlineImagesEnabled:            initialCfg.InlineImagesEnabled,
2374		TerminalAlertsEnabled:          initialCfg.TerminalAlertsEnabled,
2375		TerminalTitleEnabled:           initialCfg.TerminalTitleEnabled,
2376		AutoSubagentsEnabled:           initialCfg.AutoSubagentsEnabled,
2377		PonytailEnabled:                initialCfg.PonytailEnabled,
2378		WebSearchEnabled:               initialCfg.WebSearchEnabled,
2379		WebSearchToolAllowed:           &webSearchToolAllowedForInvocation,
2380		WebSearchInvocationOverride:    webSearchInvocationOverride,
2381		AutoSubagentsToolAllowed:       &autoSubagentsToolAllowedForSession,
2382		AutoSubagentsStatusToolAllowed: &autoSubagentsStatusToolAllowedForSession,
2383		AutoSubagentsStopToolAllowed:   &autoSubagentsStopToolAllowedForSession,
2384		AutoSubagentsResumeToolAllowed: &autoSubagentsResumeToolAllowedForSession,
2385		FastMode:                       &fastMode,
2386		LSPEnabled:                     initialCfg.LSPEnabled,
2387		SubagentLSPEnabled:             initialCfg.SubagentLSPEnabled,
2388		AutoCompactThreshold:           initialCfg.AutoCompactThreshold,
2389		JailByDefault:                  initialCfg.JailByDefault,
2390		QuickModelShortcuts:            quickModelShortcuts,
2391		RecursiveFileSuggest:           initialCfg.RecursiveFileSuggest,
2392		RespectGitignore:               initialCfg.RespectGitignore,
2393		CompactMode:                    initialCfg.CompactMode,
2394		TUIInputStyle:                  initialCfg.TUIInputStyle,
2395		TUIStatusPosition:              initialCfg.TUIStatusPosition,
2396		TUIWorkingPosition:             initialCfg.TUIWorkingPosition,
2397		TUISubagentPosition:            initialCfg.TUISubagentPosition,
2398		ThemeName:                      initialCfg.Theme,
2399		FlatTools:                      initialCfg.FlatToolRender(),
2400		CompactUser:                    initialCfg.CompactUserInput(),
2401		ExtensionThemes:                extMgr.ThemeOptions,
2402		AutoSubagentsSystemAddendum: AutoSubagentsSystemAddendumFor(
2403			autoSubagentsToolAllowedForSession,
2404			autoSubagentsStopToolAllowedForSession,
2405			autoSubagentsResumeToolAllowedForSession,
2406		),
2407		OnDemandSubagentsSystemAddendum: OnDemandSubagentsSystemAddendum,
2408		SubagentsSystemAddendum:         subagentsAddendum,
2409		SettingsStore:                   configSettingsStore{},
2410		Model:                           r.Model,
2411		Provider:                        r.Provider,
2412		AuthMethod:                      r.AuthMethod,
2413		BaseURL:                         r.BaseURL,
2414		Reasoning:                       r.Reasoning,
2415		OnReasoningChanged:              runtime.SetReasoning,
2416		SystemPrompt:                    r.SystemPrompt,
2417		WritingGuidance:                 WritingGuidance(),
2418		Tools:                           r.ToolRegistry,
2419		MaxSteps:                        r.MaxSteps,
2420		CWD:                             r.CWD,
2421		StartupAgentName:                args.AgentName,
2422		StartupContextPaths:             instructionContextPaths(r.ContextFiles),
2423		StartupExtensionNames:           startupExtensionNames(extMgr.All()),
2424		StartupExtensionErrors:          startupExtensionErrors,
2425		StartupSkillNames:               startupSkillNames(startupSkills),
2426		ShowInstructionsAtStartup:       initialCfg.ShowInstructionsAtStartup,
2427		ZutHome:                         ZutHome(),
2428		SessionsRoot:                    agentSessionsRoot(ZutHome(), args),
2429		Version:                         version,
2430		UpdateInfoChan:                  updateCh,
2431		Sandbox:                         sharedSandbox,
2432		Agent:                           ag,
2433		InitialCompactHandoff:           currentCompactHandoff(),
2434		InitialSessionTitle: func() string {
2435			if sess == nil || sessionTitlePending {
2436				return ""
2437			}
2438			return sess.Title
2439		}(),
2440		InitialSessionTitlePending: sessionTitlePending,
2441		InitialInput:               args.Prompt,
2442		StartupPre:                 args.StartupPre,
2443		OnStartupPreDone: func() {
2444			// entry.pre often installs skills/extensions; rediscover them
2445			// before the user starts a model turn.
2446			current := liveInteractiveAgent(iv, ag)
2447			if extMgr != nil {
2448				_ = extMgr.Reload(context.Background(), 2*time.Second)
2449			}
2450			if current != nil {
2451				if _, err := refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, prepareInteractiveRegistry, iv); err != nil {
2452					iv.ReportError(err)
2453				}
2454			}
2455		},
2456		RefreshTools: func() error {
2457			current := liveInteractiveAgent(iv, ag)
2458			webSearchPolicy, err := refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, prepareInteractiveRegistry, iv)
2459			if err != nil {
2460				if !errors.Is(err, errInteractiveAgentChanged) {
2461					setWebSearchAvailable(false)
2462				}
2463				return err
2464			}
2465			setWebSearchAvailable(webSearchPolicy == subagents.WebSearchAllow)
2466			return nil
2467		},
2468		SetWebSearchAvailable: setWebSearchAvailable,
2469		RefreshPrompt: func() error {
2470			current := liveInteractiveAgent(iv, ag)
2471			webSearchPolicy, err := refreshAgentToolsAndPrompt(args, sharedSandbox, extToolAdapter, current, prepareInteractiveRegistry, iv)
2472			if err != nil {
2473				return err
2474			}
2475			setWebSearchAvailable(webSearchPolicy == subagents.WebSearchAllow)
2476			return nil
2477		},
2478		AuthManager:                mgr,
2479		LlamaCPPConfig:             ResolveLlamaCPPConfig,
2480		RefreshLlamaCPPModels:      RefreshLlamaCPPModels,
2481		BuildAgent:                 buildAgent,
2482		SetKimiCLIFallbackDisabled: SetKimiCLIFallbackDisabled,
2483		BuildAgentFor:              buildAgentFor,
2484		BuildAgentForRescue:        buildAgentForRescue,
2485		LoggedInProviders: func() []string {
2486			var out []string
2487			seen := map[string]bool{}
2488			for _, p := range knownProviders {
2489				if CredentialAvailable(p) && !seen[p] {
2490					out = append(out, p)
2491					seen[p] = true
2492				}
2493			}
2494			// Include custom providers that have credentials stored.
2495			for p := range provider.CustomProviders() {
2496				if CredentialAvailable(p) && !seen[p] {
2497					out = append(out, p)
2498					seen[p] = true
2499				}
2500			}
2501			// Ollama models are always available (no auth needed).
2502			if !seen["ollama"] {
2503				out = append(out, "ollama")
2504			}
2505			return out
2506		},
2507		LoadSession:           loadSession,
2508		ChangeCWD:             changeCWD,
2509		PersistCompactHandoff: persistCompactHandoff,
2510		CurrentCompactHandoff: currentCompactHandoff,
2511		PersistGoal:           persistGoal,
2512		CurrentGoal:           currentGoal,
2513		CurrentGoalHistory:    currentGoalHistory,
2514		EnsureMission:         ensureMission,
2515		CurrentSessionPath: func() string {
2516			persistMu.Lock()
2517			defer persistMu.Unlock()
2518			if sess == nil {
2519				return ""
2520			}
2521			return sess.Path
2522		},
2523		FlushSession: func() {
2524			sessionTransitionMu.RLock()
2525			defer sessionTransitionMu.RUnlock()
2526			// Append any not-yet-persisted agent messages to the
2527			// current session file, then advance the baseline so
2528			// the final WriteNewTranscript at exit doesn't write
2529			// duplicates. Per-message persistence keeps the on-
2530			// disk file current already, so this is mostly a
2531			// defensive flush — still needed for /session export
2532			// to guarantee the exported bytes include the very
2533			// last in-flight turn.
2534			currentAg := iv.Agent()
2535			if currentAg == nil {
2536				return
2537			}
2538			persistMu.Lock()
2539			defer persistMu.Unlock()
2540			if sess == nil {
2541				return
2542			}
2543			next, flushErr := writeNewTranscriptLocked(currentAg, sess, sessBaselineMsgs)
2544			sessBaselineMsgs = next
2545			if flushErr != nil {
2546				iv.ReportError(fmt.Errorf("flush session: %w", flushErr))
2547				return
2548			}
2549		},
2550		SessionTransition: newSessionTransition(&sessionTransitionMu),
2551		Extensions:        extMgr,
2552		Supervisor:        subagentsMgr,
2553		ResolveSubagent:   resolveSubagent,
2554		ChangelogChan:     changelogCh,
2555		OnChangelogDismiss: func() {
2556			// For development builds, store the actual release version
2557			// so the same changelog doesn't show again next launch.
2558			// For real builds, store the binary version.
2559			v := version
2560			if devBuild {
2561				if iv != nil && iv.ChangelogVersion() != "" {
2562					v = iv.ChangelogVersion()
2563				}
2564			}
2565			_ = MarkChangelogShown(v)
2566		},
2567		SkillSnapshot: func() []*skills.Skill {
2568			if args.NoSkill {
2569				// --no-skill: nothing for the picker to show.
2570				return nil
2571			}
2572			// Re-discover so the picker reflects edits made during
2573			// the session. Cheap; SKILL.md files are small. Filter
2574			// out built-in skills — they're hidden from user-facing
2575			// surfaces because they're implementation detail; the
2576			// model still sees them through the system-prompt
2577			// manifest and the skill tool.
2578			userHome, _ := os.UserHomeDir()
2579			list, _ := skills.Discover(ZutHome(), r.CWD, userHome, args.WithSkills)
2580			list = mergeExtensionSkills(skills.NewTool(list), extMgr.Skills())
2581			return skills.VisibleSkills(list)
2582		},
2583		NoYolo:      args.NoYolo,
2584		ConfirmGate: confirmGate,
2585		PersistModel: newPersistModelCallback(&persistMu, &sess, &activeProvider, &activeModel, func(message string) {
2586			if iv != nil {
2587				iv.Notify("session", "error", message)
2588			}
2589		}),
2590		CurrentSessionTitle: func() string {
2591			sessionTransitionMu.RLock()
2592			defer sessionTransitionMu.RUnlock()
2593			persistMu.Lock()
2594			defer persistMu.Unlock()
2595			if sess == nil || sessionTitlePending {
2596				return ""
2597			}
2598			return sess.Title
2599		},
2600		CurrentSessionTitlePending: func() bool {
2601			sessionTransitionMu.RLock()
2602			defer sessionTransitionMu.RUnlock()
2603			persistMu.Lock()
2604			defer persistMu.Unlock()
2605			return sessionTitlePending
2606		},
2607		PersistTitle: func(title string) error {
2608			persistMu.Lock()
2609			defer persistMu.Unlock()
2610			if sess == nil {
2611				return nil
2612			}
2613			if err := sess.UpdateTitle(title); err != nil {
2614				return err
2615			}
2616			sessionTitlePending = false
2617			return nil
2618		},
2619		OnSessionTitleChanged: func(title string) {
2620			sessionTransitionMu.RLock()
2621			defer sessionTransitionMu.RUnlock()
2622			persistMu.Lock()
2623			defer persistMu.Unlock()
2624			if sess != nil {
2625				sess.Title = title
2626				sessionTitlePending = false
2627			}
2628		},
2629	})
2630	extHooks.attachInteractive(iv)
2631	go func() {
2632		<-reloadDone
2633		for _, reloadErr := range reloadErrs {
2634			if reloadErr != nil {
2635				iv.ReportError(fmt.Errorf("reload subagents: %w", reloadErr))
2636			}
2637		}
2638	}()
2639
2640	// Bind the interactive TUI as the Confirmer. We deferred this
2641	// until now because the gate is constructed before the TUI
2642	// (the BeforeToolExecute closure captures it). SetConfirmer
2643	// is mutex-guarded on the gate so this is safe.
2644	if confirmGate != nil {
2645		confirmGate.SetConfirmer(&confirmationEventConfirmer{
2646			inner: iv,
2647			emit:  extMgr.EmitEvent,
2648		})
2649	}
2650
2651	// Signal-driven flush: a SIGTERM / SIGHUP to the zut process
2652	// (closed terminal window, system shutdown, kill) used to lose
2653	// the entire in-memory transcript because the deferred post-Run
2654	// flush below never ran. Per-message persistence above covers
2655	// most of it; this handler writes any in-flight remainder and
2656	// then exits the process so we don't double-paint over a
2657	// broken terminal that the TUI's restore deferreds can no
2658	// longer fix from a signal context.
2659	//
2660	// SIGINT is intentionally NOT handled here — the TUI consumes
2661	// Ctrl+C as a regular key event for cancel/clear semantics, and
2662	// installing a SIGINT notifier here would swallow it.
2663	sigCh := make(chan os.Signal, 1)
2664	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGHUP)
2665	defer signal.Stop(sigCh)
2666	go func() {
2667		_, ok := <-sigCh
2668		if !ok {
2669			return
2670		}
2671		finalAg := iv.Agent()
2672		if finalAg != nil {
2673			persistMu.Lock()
2674			if sess != nil {
2675				next, flushErr := writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
2676				sessBaselineMsgs = next
2677				if flushErr != nil {
2678					fmt.Fprintf(os.Stderr, "flush session: %v\n", flushErr)
2679				}
2680				if closeErr := sess.Close(); closeErr != nil {
2681					fmt.Fprintf(os.Stderr, "close session: %v\n", closeErr)
2682				}
2683				sess = nil
2684			}
2685			persistMu.Unlock()
2686		}
2687		closeAgentLSP(finalAg)
2688		closeResolvedLSP(r)
2689		// Stop supervised workers before exiting. os.Exit skips deferred
2690		// cleanup, so wait for reload and close the shared runtime explicitly.
2691		<-reloadDone
2692		_ = closeSubagentRuntimeFresh(runtime)
2693		// Exit cleanly. Re-raising the signal would skip os.Exit's
2694		// at-exit hooks; explicit exit is fine because we've already
2695		// flushed the only at-risk state (the session file) and stopped
2696		// supervised workers.
2697		os.Exit(0)
2698	}()
2699
2700	runErr = iv.Run(ctx)
2701
2702	// Flush final transcript to session (only if we had / ended up with an agent).
2703	if finalAg := iv.Agent(); finalAg != nil {
2704		persistMu.Lock()
2705		if sess != nil {
2706			next, flushErr := writeNewTranscriptLocked(finalAg, sess, sessBaselineMsgs)
2707			sessBaselineMsgs = next
2708			if flushErr != nil {
2709				runErr = errors.Join(runErr, fmt.Errorf("flush session: %w", flushErr))
2710			}
2711		}
2712		persistMu.Unlock()
2713	}
2714	return runErr
2715}
2716
2717func resumableSessionID(root string, sess *core.Session, hasMessages bool) string {
2718	if !hasMessages || sess == nil || sess.ID == "" || sess.Path == "" {
2719		return ""
2720	}
2721	managedRoot, err := filepath.Abs(filepath.Join(root, "sessions"))
2722	if err != nil {
2723		return ""
2724	}
2725	path, err := filepath.Abs(sess.Path)
2726	if err != nil {
2727		return ""
2728	}
2729	rel, err := filepath.Rel(managedRoot, path)
2730	if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
2731		return ""
2732	}
2733	if _, err := os.Stat(path); err != nil {
2734		return ""
2735	}
2736	return sess.ID
2737}
2738
2739func resumeSessionHint(id string) string {
2740	return fmt.Sprintf("Session ID: %s\nResume with: zut --resume %s\n\n", id, id)
2741}
2742
2743func agentSessionsRoot(root string, args Args) string {
2744	if args.AgentName == "" {
2745		return root
2746	}
2747	return filepath.Join(root, "sessions", "agents", safeAgentName(args.AgentName))
2748}
2749
2750// openOrCreateSession returns a session for the run. sess may be nil
2751// with a nil error if session persistence is disabled.
2752func openOrCreateSession(ctx context.Context, args Args, r Resolved, ag *core.Agent, version string) (*core.Session, error) {
2753	if args.NoSess {
2754		return nil, nil
2755	}
2756	// Sweep meta-only files left over from older zut versions (and from
2757	// any session that crashed before its first AppendMessage) for the
2758	// cwd-scoped picker paths. Explicit UUID lookup stays strict so it
2759	// can report metadata failures instead of turning them into misses.
2760	sessionsRoot := agentSessionsRoot(ZutHome(), args)
2761	if args.ResumeSessionID == "" {
2762		core.PruneEmptySessions(sessionsRoot, args.CWD)
2763	}
2764	var (
2765		s    *core.Session
2766		msgs []provider.Message
2767		err  error
2768	)
2769	switch {
2770	case args.Session != "":
2771		s, msgs, err = core.OpenSession(args.Session)
2772		// The subagent-worker child passes a fixed --session path that
2773		// may not exist yet on first Spawn. Treat ENOENT as "create
2774		// a fresh session AT THIS PATH" so the conversation actually
2775		// gets persisted; without this fallback the subagent child runs
2776		// with sess==nil and every Resume re-starts with no memory
2777		// of the prior turns. Other openers (--continue / --resume /
2778		// the picker) never see ENOENT here because they only choose
2779		// paths that already exist on disk.
2780		if err != nil && errors.Is(err, os.ErrNotExist) {
2781			s, err = core.NewSessionAtPath(args.Session, args.CWD, r.Provider, r.Model, version)
2782			msgs = nil
2783		}
2784	case args.Continue:
2785		latest := core.LatestSession(sessionsRoot, args.CWD)
2786		if latest != "" {
2787			s, msgs, err = core.OpenSession(latest)
2788		}
2789	case args.Resume:
2790		if args.ResumeSessionID != "" {
2791			picked, lookupErr := core.FindManagedSessionByID(ctx, ZutHome(), args.ResumeSessionID)
2792			if lookupErr != nil {
2793				return nil, lookupErr
2794			}
2795			if picked == "" {
2796				return nil, fmt.Errorf("session %q not found", args.ResumeSessionID)
2797			}
2798			s, msgs, err = core.OpenSession(picked)
2799			break
2800		}
2801		picked, perr := pickSession(sessionsRoot, args.CWD)
2802		if perr != nil {
2803			return nil, perr
2804		}
2805		if picked != "" {
2806			s, msgs, err = core.OpenSession(picked)
2807		}
2808	}
2809	if err != nil {
2810		return nil, err
2811	}
2812	if s != nil {
2813		ag.SetSessionTimeContext(s.Meta.Started, s.Meta.Timezone, s.Meta.TimezoneOffset)
2814		ag.SetMessages(msgs)
2815		if cum, last, uerr := core.SessionUsageDetail(s.Path); uerr == nil {
2816			ag.SeedCost(cum)
2817			ag.SeedLastTurnUsage(last)
2818		}
2819		return s, nil
2820	}
2821	s, err = core.NewSession(sessionsRoot, args.CWD, r.Provider, r.Model, version)
2822	if err == nil {
2823		ag.SetSessionTimeContext(s.Meta.Started, s.Meta.Timezone, s.Meta.TimezoneOffset)
2824	}
2825	return s, err
2826}
2827
2828func pickSession(root, cwd string) (string, error) {
2829	files := core.ListSessions(root, cwd)
2830	if len(files) == 0 {
2831		fmt.Fprintln(os.Stderr, "no sessions for", cwd)
2832		return "", nil
2833	}
2834	for i, f := range files {
2835		fmt.Fprintf(os.Stderr, "  %2d) %s\n", i+1, f)
2836	}
2837	fmt.Fprint(os.Stderr, "pick #: ")
2838	rd := bufio.NewReader(os.Stdin)
2839	line, _ := rd.ReadString('\n')
2840	line = strings.TrimSpace(line)
2841	var n int
2842	if _, err := fmt.Sscanf(line, "%d", &n); err != nil || n < 1 || n > len(files) {
2843		return "", fmt.Errorf("invalid selection")
2844	}
2845	return files[n-1], nil
2846}
2847
2848// WriteNewTranscript appends only messages after index `from` from the
2849// agent's transcript to the session. Used by callers that don't hold
2850// the persistMu (non-interactive print/json modes which run a single
2851// turn under their own goroutine).
2852func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) error {
2853	_, err := writeNewTranscriptLocked(ag, sess, from)
2854	return err
2855}
2856
2857func wireRetryLifecyclePersistence(ag *core.Agent, sess *core.Session) {
2858	if ag == nil {
2859		return
2860	}
2861	if sess == nil {
2862		ag.OnRetryLifecycle = nil
2863		return
2864	}
2865	ag.OnRetryLifecycle = sess.RecordRetryLifecycle
2866}
2867
2868// writeNewTranscriptLocked is the same as WriteNewTranscript. The
2869// suffix marks that interactive callers must hold persistMu when
2870// invoking it so concurrent appends from the agent loop don't race
2871// with this catch-up flush.
2872func writeNewTranscriptLocked(ag *core.Agent, sess *core.Session, from int) (next int, err error) {
2873	next = from
2874	if sess == nil || ag == nil {
2875		return next, nil
2876	}
2877	msgs, total := ag.MessagesFrom(from)
2878	for offset, msg := range msgs {
2879		index := from + offset
2880		if err := sess.AppendMessage(msg); err != nil {
2881			return next, fmt.Errorf("append transcript message %d: %w", index, err)
2882		}
2883		next = index + 1
2884	}
2885	if len(msgs) == 0 {
2886		next = total
2887	}
2888	cum := ag.Cost()
2889	if err := sess.AppendUsage(cum, cum); err != nil {
2890		return next, fmt.Errorf("append transcript usage: %w", err)
2891	}
2892	if err := sess.Flush(); err != nil {
2893		return next, fmt.Errorf("flush transcript: %w", err)
2894	}
2895	return next, nil
2896}
2897
2898func argsForStdin(rawArgs []string, mode os.FileMode) []string {
2899	if mode&os.ModeCharDevice != 0 {
2900		return rawArgs
2901	}
2902	return append([]string{"--print"}, rawArgs...)
2903}
2904
2905func combinePromptInput(stdin, positional string) string {
2906	parts := make([]string, 0, 2)
2907	if stdin = strings.TrimSpace(stdin); stdin != "" {
2908		parts = append(parts, stdin)
2909	}
2910	if positional = strings.TrimSpace(positional); positional != "" {
2911		parts = append(parts, positional)
2912	}
2913	return strings.Join(parts, "\n")
2914}
2915
2916func readAllStdin() (string, error) {
2917	fi, err := os.Stdin.Stat()
2918	if err != nil {
2919		return "", err
2920	}
2921	if (fi.Mode() & os.ModeCharDevice) != 0 {
2922		return "", nil
2923	}
2924	return readAllStdinFrom(os.Stdin)
2925}
2926
2927func readAllStdinFrom(r io.Reader) (string, error) {
2928	b, err := io.ReadAll(r)
2929	return string(b), err
2930}
2931
2932func printModels() {
2933	models := provider.Active()
2934
2935	// Compute column widths from actual data so wide providers (e.g.
2936	// xiaomi-token-plan-sgp) and long bedrock model ids don't force the
2937	// `name` column off-screen. Floors mirror the historical layout so
2938	// short catalogs look the same as before.
2939	provW, idW, srcW := len("provider"), len("model id"), len("source")
2940	for _, m := range models {
2941		if w := len(m.Provider); w > provW {
2942			provW = w
2943		}
2944		if w := len(m.ID); w > idW {
2945			idW = w
2946		}
2947		source := m.Source
2948		if source == "" {
2949			source = "catalog"
2950		}
2951		if m.Speculative {
2952			source = "speculative"
2953		}
2954		if w := len(source); w > srcW {
2955			srcW = w
2956		}
2957	}
2958
2959	header := fmt.Sprintf("%-*s  %-*s  %8s  %8s  %s  %-*s  %s",
2960		provW, "provider",
2961		idW, "model id",
2962		"context", "max-out", "reasoning",
2963		srcW, "source",
2964		"name")
2965	fmt.Println(header)
2966
2967	for _, m := range models {
2968		reason := " "
2969		if m.Reasoning {
2970			reason = "✓"
2971		}
2972		source := m.Source
2973		if source == "" {
2974			source = "catalog"
2975		}
2976		if m.Speculative {
2977			source = "speculative"
2978		}
2979		fmt.Printf("%-*s  %-*s  %8d  %8d     %s      %-*s  %s\n",
2980			provW, m.Provider,
2981			idW, m.ID,
2982			m.ContextWindow, m.MaxOutput,
2983			reason,
2984			srcW, source,
2985			m.DisplayName)
2986	}
2987}

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 477

↑↓ moveenter openesc close