v0.40.0 076e2bb

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

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