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