v0.33.0 653c635

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close