返回 DeepSeek-Reasonix
controller.go
根目录 / internal / control / controller.go
1 // Package control is the transport-agnostic session driver. A Controller owns
2 // the agent run loop and session lifecycle, takes commands (Send/Cancel/Approve/
3 // SetPlanMode/Compact/NewSession/…), and emits everything that happens —
4 // reasoning, tool calls, approvals, turn completion — as a typed event stream to
5 // a single event.Sink.
6 //
7 // The point is one orchestration layer behind every frontend: a terminal TUI, a
8 // desktop webview, or an HTTP/SSE server each drive the Controller identically
9 // (issue commands, render events) and none of them re-implement turn lifecycle,
10 // cancellation, or approval. The Controller depends on no frontend.
11 package control
12
13 import (
14 "context"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "log/slog"
19 "net/http"
20 "os"
21 "path/filepath"
22 "reflect"
23 "slices"
24 "sort"
25 "strconv"
26 "strings"
27 "sync"
28 "sync/atomic"
29 "time"
30
31 "reasonix/internal/ablation"
32 "reasonix/internal/agent"
33 "reasonix/internal/agentpreset"
34 "reasonix/internal/autoresearch"
35 "reasonix/internal/billing"
36 "reasonix/internal/capability"
37 "reasonix/internal/checkpoint"
38 "reasonix/internal/command"
39 "reasonix/internal/config"
40 "reasonix/internal/event"
41 "reasonix/internal/evidence"
42 "reasonix/internal/extension"
43 "reasonix/internal/extension/dispatch"
44 "reasonix/internal/extension/uihub"
45 "reasonix/internal/gitcmd"
46 goaldomain "reasonix/internal/goal"
47 "reasonix/internal/guardian"
48 "reasonix/internal/hook"
49 "reasonix/internal/i18n"
50 "reasonix/internal/jobs"
51 "reasonix/internal/mcpinteraction"
52 "reasonix/internal/memory"
53 "reasonix/internal/nilutil"
54 "reasonix/internal/permission"
55 "reasonix/internal/permissionpreset"
56 "reasonix/internal/persistentshell"
57 "reasonix/internal/plugin"
58 "reasonix/internal/provider"
59 "reasonix/internal/sandbox"
60 "reasonix/internal/session"
61 "reasonix/internal/sessioncontext"
62 "reasonix/internal/sessioninbox"
63 "reasonix/internal/sessiontemp"
64 "reasonix/internal/shellrun"
65 "reasonix/internal/skill"
66 "reasonix/internal/store"
67 "reasonix/internal/taskmonitor"
68 "reasonix/internal/tool"
69 "reasonix/internal/workspacelease"
70 )
71
72 // ErrTurnRunning reports that a caller tried to start a second foreground turn
73 // while one is already active in the same Controller.
74 var ErrTurnRunning = errors.New("turn already running")
75
76 // ErrNoFinalReadinessRecovery is retained for old recovery-action clients.
77 var ErrNoFinalReadinessRecovery = errors.New("final_readiness_recovery_retired: readiness recovery actions can no longer restore evidence or replay checks")
78
79 // ErrRuntimeDraining reports that a caller targeted a controller generation
80 // superseded by a successful rebuild.
81 var ErrRuntimeDraining = errors.New("runtime is draining after rebuild")
82
83 // ErrRecoveryRequired reports that the previous foreground activity did not
84 // stop inside the cancellation grace period. The controller keeps queued input
85 // and write ownership sealed until the process is restarted.
86 var ErrRecoveryRequired = errors.New("session recovery is required before another turn can start")
87
88 // errTurnRunningRotation and errRotationInProgress are returned by the
89 // session-rotation gate (beginRotation) when a rotation cannot proceed: a turn
90 // is in flight, or another rotation already holds the gate.
91 var (
92 errTurnRunningRotation = errors.New("cannot start a new session while a turn is running")
93 errRotationInProgress = errors.New("cannot start a new session while another session change is in progress")
94 )
95
96 // errNoSessionPath is returned by snapshot when a session has content to persist
97 // but no resolved session path — a misconfiguration (e.g. an unresolvable data
98 // dir in a bot deployment) that previously dropped conversations silently
99 // (#4414). Callers log it and continue; it must never be swallowed quietly.
100 var errNoSessionPath = errors.New("session has content but no session path; conversation cannot be persisted")
101
102 // Controller drives one chat session. Construct with New; drive with the command
103 // methods; observe through the Sink passed in Options.
104 type Controller struct {
105 lifecycleDiagnostics lifecycleDiagnosticBuffer
106 providerDiagnostics providerDiagnosticBuffer
107 runtimeState controllerRuntimeState
108 controllerPromptRouting
109 authentication authenticationGate
110 runner agent.Runner
111 executor *agent.Agent
112 guardianSess *guardian.Session // nil when guardian is disabled
113 guardianPath string // persisted guardian session file ("" when disabled)
114 // taskBudget is the configured spend gate, as passed at construction.
115 taskBudget agent.TaskBudget
116 // goalTokenBudget bounds an unattended Goal loop; 0 leaves it unbounded.
117 goalTokenBudget int
118 goalResourceMu sync.Mutex
119 goalTokensUsed int
120 goalRequestsUsed int
121 goalTokenLimit int
122 goalBudgetExtensions int
123
124 // goalUsageTee accounts billable usage events into the active goal turn's
125 // observational token total. It wraps the public sink when the caller didn't provide one.
126 goalUsageTee *goalUsageTee
127 sink event.Sink
128 policy permission.Policy
129 // subagentGate is the shared gate every headless-only sub-agent surface
130 // reads from (see Options.SubagentGate). Nil when the caller didn't build
131 // one — sub-agents then keep whatever gate they were constructed with.
132 subagentGate *SharedHeadlessGate
133
134 label string
135 selection modelSelection
136 resolveSessionModel func(string, string) (string, error)
137 visionModel string
138 visionProviderResolver func(string) (provider.Provider, error)
139 visionModelSelector func(string, string) (string, bool)
140 modelCapabilityResolver func(*config.ProviderEntry) config.ResolvedModelCapability
141 frozenImageInput *bool
142 imageCapabilityChanged func() bool
143 controllerAttachmentState
144 modelSettings controllerModelSettings
145 prompt controllerPromptState
146 pinnedContextLoader PinnedContextLoader
147 sessionContextStatic sessioncontext.Sections
148 sessionDir string
149 controllerSessionBinding
150 // managedSessionEvents is set for hosts that publish controllers only after
151 // a session-lease handoff. An unpublished replacement may read the shared
152 // v3 projection, but it must not mutate that projection before its final
153 // write authority is bound.
154 managedSessionEvents atomic.Bool
155 commands atomic.Pointer[[]command.Command]
156 // skills owns the session's discovered skills (enabled subset, full set, and
157 // the reloadable stores) — the skills slice of the Capabilities concern. See
158 // skill.go.
159 skills skillSet
160 skillRunner skill.SubagentRunner
161 readOnlySkillRunner skill.SubagentRunner
162 skillProfile skill.ProfileResolver
163 disableImplicitSkillInvocation bool
164 slashSkillSeq atomic.Uint64
165 hooks *hook.Runner // session hook runner; nil-safe (no hooks configured)
166 // hookContexts carries one-shot lifecycle hook context into the next real
167 // user turn without changing the cache-stable system prompt.
168 hookContexts []string
169 // memory owns the loaded memory snapshot, the pending turn-tail notes queue,
170 // and write serialization behind its own locks, off c.mu — so a memory-panel
171 // save never stalls an approval or status poll. See memory.go.
172 memory memoryManager
173 cleanup func()
174 responseLanguage string
175 reasoningLanguage string
176 disableColdResumePrune bool // legacy; rewrite elision removed, still gates cold notice
177 headPolicy sessionHeadPolicy
178 // testCacheColdAfter overrides cacheColdAfter() in tests. Zero uses the
179 // vendor-aware resolution from config.
180 testCacheColdAfter time.Duration
181 // testCancelGrace overrides the production cancellation grace in tests.
182 // Zero uses the documented 15 second boundary.
183 testCancelGrace time.Duration
184
185 shell sandbox.Shell // interpreter for user-invoked "!" commands; zero = auto
186 startedOnce bool // guards the one-shot SessionStart hook on first turn
187 closeOnce sync.Once // makes close idempotent under racing teardown paths
188 closeFinalizeOnce sync.Once // releases persistence/resources only after the terminal boundary
189 closeFinalized chan struct{} // closes after every controller-owned resource has been released
190 closeFireSessionEnd bool
191 closeJobsMode closeJobsMode
192 onRemember func(rule string) RememberResult // set via Options; invoked when user picks "always allow"
193 onRememberPlanModeReadOnlyCommand func(prefix string) PlanModeReadOnlyCommandTrustResult
194 writeAccess controllerWriteAccess
195 sessionRecoveryMeta func(SessionRecoveryRequest) agent.BranchMeta
196 onSessionRecovered func(SessionRecoveryInfo) error
197 onSessionTransition func(SessionTransitionInfo) error
198 onSessionRotation func(context.Context, SessionRotationRequest) (SessionRotationPlan, error)
199
200 // balanceURL/balanceKey target the active provider's optional wallet-balance
201 // endpoint (empty when the provider declares none). Captured at build so a
202 // model/key switch — which rebuilds the controller — refreshes them.
203 balanceURL string
204 balanceKey string
205 balanceClient *http.Client
206
207 // jobs is the session-scoped background-job manager. The agent's background
208 // tools spawn into it; Compose drains its completion notes into the next turn;
209 // Close cancels its still-running jobs.
210 jobs *jobs.Manager
211 background controllerBackground
212 // workspaceLease is the Delivery writer owner shared with the executor.
213 // It is exposed only through a sanitized state snapshot for Desktop recovery.
214 workspaceLease *workspacelease.Owner
215
216 // mcp owns the session's live tool/plugin surface behind its own lock, off
217 // c.mu; the Controller keeps config-facing orchestration. See mcp.go.
218 mcp mcpManager
219 mcpDefaultCallTimeout time.Duration
220 mcpConfigureSpec func(*plugin.Spec)
221 capabilityRuntime *agent.MCPCapabilityRuntime
222
223 runtimeGeneration uint64 // PublishGate gen; 0 disables
224 permissionMu sync.Mutex
225 permissionStateMu sync.RWMutex
226 permissionRevision atomic.Uint64
227 runtimeOwner *extension.RuntimeOwner
228 lastResumeDecision extension.ResumeDecision
229 // extensions is the frozen extension dispatcher for this controller
230 // generation, or nil when no v2 runtime packages are installed (the
231 // universal pre-dispatch fast path). It is installed before the controller
232 // starts serving (Options.Extensions or SetExtensions) and never swapped
233 // afterwards, so wiring points read it without locking.
234 extensions *dispatch.Dispatcher
235 // extensionUI is the host extension UI hub for this controller generation
236 // (stage 8a), or nil when no v2 runtime packages started. Installed via
237 // SetExtensionUI before serving and never swapped; readers take c.mu.
238 extensionUI *uihub.Hub
239 // providerResolver is the build's merged provider catalog (extension
240 // sidecar providers over the config/broker base), or nil when no sidecar
241 // declared providers. Immutable after New; ProviderCatalog reads it.
242 providerResolver provider.Resolver
243
244 // Capability routing (Delivery hybrid route + dual-model Planner proxy).
245 // Not part of the provider-visible prefix; only seeds the turn-scoped ledger
246 // and optional semantic router.
247 pluginCfg []config.PluginEntry
248 capCachedTools map[string][]plugin.CachedTool
249 capCacheKeyOK map[string]bool
250 semanticRouter *capability.SemanticRouter
251 capabilityAudit *capability.Audit
252 // capabilityProxy directs unready MCP candidates to use_capability in the
253 // transient route block (Delivery and dual-model Planner).
254 capabilityProxy bool
255 // proxyToolsFn returns live tools observed through use_capability without
256 // entering the provider-visible registry (dual-model Planner).
257 proxyToolsFn func() map[string][]plugin.CachedTool
258 ablation ablation.Set
259
260 // goals owns the active goal's FSM (status, intercepts, idle/turn counters)
261 // and its persistence, behind its own mutex so a per-turn goal save never
262 // stalls an approval or status poll on c.mu. See goal.go.
263 goals goalMachine
264 // goalLifecycle is the versioned session goal authority. The legacy
265 // goalMachine remains only while old sidecars are imported and must not be
266 // used as the execution source once the v3 lifecycle cutover is complete.
267 goalLifecycleMu sync.RWMutex
268 goalLifecycleMutationMu sync.Mutex
269 goalLifecycle *goaldomain.Machine
270 goalLifecycleLoadErr error
271 // goalDriver is a level-triggered, process-local scheduler. It never owns a
272 // cross-turn Activity: each accepted continuation enters through the normal
273 // guarded top-level turn path.
274 goalDriverMu sync.Mutex
275 goalDriverWG sync.WaitGroup
276 goalDriverPending bool
277 goalDriverActive *goalRoundReservation
278 goalDriverControl goalDriverControl
279 // legacyResearchArchive reads explicit pre-unification task paths. It never
280 // creates or mutates archive state. See
281 // autoresearch_manager.go.
282 legacyResearchArchive legacyResearchArchive
283 legacyRestoreMu sync.Mutex
284 legacyRestore legacyGoalRestore
285
286 // workspaceRoot is the workspace root: the base for resolving @-refs and slash
287 // path refs, the working directory for user "!" shell commands and custom
288 // command discovery, and the guard root for checkpoint restore writes. It is
289 // surfaced to frontends via WorkspaceRoot().
290 workspaceRoot string
291 // workspaceRepo is workspaceRoot's git identity, resolved before any turn ran.
292 workspaceRepo gitcmd.Repo
293
294 // externalFolderRefs maps session-generated @ tokens to user-dropped
295 // directories outside workspaceRoot. It is intentionally per-controller:
296 // dragging a folder authorizes that folder for this chat session only, without
297 // widening scoped @ resolution to arbitrary absolute paths.
298 externalFolderRefsMu sync.RWMutex
299 externalFolderRefs map[string]string
300 externalFolderToolRefs externalFolderToolRefs
301
302 // checkpoints owns the snapshot-based rewind bookkeeping (the per-session
303 // store, the monotonic turn counter, and the conversation-rewind boundary map)
304 // behind its own lock, off c.mu — so a boundary read for a rewind/fork never
305 // contends on the run-state lock. The Controller keeps the rewind/fork/summarize
306 // orchestration (truncating the session, restoring code, emitting events). See
307 // checkpoint.go.
308 checkpoints checkpointManager
309 // mutationObserver is the host-side file mutation observer for v2 checkpoints.
310 mutationObserver *checkpoint.MutationObserver
311 // sessionRevision increments on successful rewind/undo and is used as a
312 // prepare/commit freshness token.
313 sessionRevision int64
314
315 // approval owns the approval/ask prompt bookkeeping and the runtime approval
316 // posture (ask/auto/yolo, session grants, the just-approved-plan window)
317 // behind its own locks, off c.mu. The Controller keeps the I/O orchestration
318 // (requestApproval/Ask emit events + fire hooks + rebuild the executor gate).
319 // See approval.go.
320 approval approvalManager
321
322 // mu guards the run state; every critical section under it is short and
323 // non-blocking.
324 mu sync.Mutex
325 // turns is the sole execution authority: phase, current cancel/done/token,
326 // and the FIFO pending queue.
327 turns turnLoop
328 // executionGeneration is the Runtime BindExecution generation for this
329 // controller. Unbind uses the exact value so a rebuilt controller cannot
330 // clear the replacement's control.
331 executionGeneration atomic.Uint64
332 // closed marks the controller as terminally torn down (close() ran). It
333 // seals turn admission: without it, a submit arriving AFTER close cleared
334 // the parked queue — but while a still-running turn's TurnDone delivery
335 // was in flight — would park again and then start against freed resources
336 // when the window closed.
337 closed bool
338 // rotating is set under mu while NewSession/ClearSession swap the executor
339 // session out. Checking running once and then swapping later leaves a
340 // TOCTOU window: a turn can start (running=false at check time) during the
341 // intervening Snapshot() and then have its live session replaced. running
342 // and rotating are mutually exclusive gates — a turn refuses to start while
343 // a rotation is in progress, and a rotation refuses to start while a turn
344 // runs — so the run loop's session reference cannot change under it.
345 rotating bool
346 // maintenance is the controller-owned foreground maintenance operation.
347 // It is deliberately separate from rotating: Stop can cancel it and normal
348 // user input can remain in the durable inbox until it reaches a terminal
349 // boundary.
350 maintenance *controllerMaintenance
351 autosaveWG sync.WaitGroup
352 // sessionSettings groups the per-session posture knobs that share one
353 // lifetime: swapped together on session rotation.
354 sessionSettings sessionSettings
355 sessionPath string
356 // sessionTemp owns the logical-session private temporary directory shared
357 // by Bash calls. Retained for this Controller's lifetime; rotated on
358 // /new, /clear, resume of another session, and branch switches.
359 sessionTemp *sessiontemp.Manager
360 persistentShell *persistentshell.Manager
361 // snapshotMu serializes the whole save/recovery handoff for this controller.
362 // Agent-level path locks protect individual files, but recovery also moves
363 // controller-owned state (sessionPath, guardianPath, checkpoints, rewrite
364 // baseline). Letting a second snapshot observe that migration halfway through
365 // can turn one conflict into a recovery cascade. Session/path swaps
366 // (new/clear/fork/branch/switch/resume/SetSessionPath) hold it for the same
367 // reason: a save that reads the old path but the new session would write one
368 // transcript's messages into another's file, or manufacture a bogus conflict.
369 // Not reentrant — never call snapshot (or anything that snapshots, such as
370 // recoverInterruptedTurn or maybeColdResumePrune) while holding it.
371 snapshotMu sync.Mutex
372 // turn counts model turns this session, passed to hooks in their payload.
373 turn int
374 turnEvents turnEventState
375 submissions submissionIdentityState
376 liveness turnLiveness
377
378 displayRecorder func(content, display string)
379
380 // inbox is the durable session-level instruction queue. Disk I/O never
381 // runs under c.mu; the store owns its own lock.
382 inbox inboxState
383 }
384
385 type approvalReply struct {
386 allow bool
387 session bool
388 persist bool // true = write "always allow" rule to config
389 onceDirs []string
390 persistErr error
391 }
392
393 type pendingApproval struct {
394 id string
395 tool string
396 subject string
397 reason string
398 rawInput json.RawMessage
399 fresh bool
400 requireHuman bool
401 autoDrain bool
402 kind string // tool | plan | recovery | write_access; empty = tool
403 recovery *event.RecoveryApproval
404 writeAccess *event.WriteAccessApproval
405 reply chan approvalReply
406 }
407
408 // pendingAsk is an in-flight ask question batch. questions is retained so the
409 // AskRequest can be re-emitted to a frontend that reconnected after the original
410 // event (see ReplayPendingPrompts).
411 type pendingAsk struct {
412 questions []event.AskQuestion
413 reply chan []event.AskAnswer
414 queued bool // registered but not yet shown; replay must skip it
415 }
416
417 type plannerSessionResetter interface {
418 ResetPlannerSession()
419 }
420
421 type controllerSessionBinding struct {
422 // sessionRuntime is the final identity-bound v3 owner. When exclusiveSession is
423 // set, SessionPath is a legacy import/display locator only and no production
424 // transcript or business sidecar may be written through it.
425 sessionService *session.Service
426 sessionCreateService *session.Service
427 sessionRuntime *session.Runtime
428 sessionBinding *session.ClientBinding
429 exclusiveSession bool
430 nativeLegacySession bool
431 // Only Serve opts into session-scoped preset restoration. TUI and Desktop
432 // keep their own live permission policy across canonical session binds.
433 servePresetRestore bool
434 v3BindingMu sync.RWMutex
435 }
436
437 type controllerPromptRouting struct {
438 // promptEpochMu protects only the routing epoch. One-shot resolution is
439 // owned by PendingPromptOwner and the typed registries; cancellation must
440 // never wait behind an answer callback.
441 promptEpochMu sync.RWMutex
442 promptRuntimeEpoch string
443 promptOwner PendingPromptOwner
444 // promptResolveMu serializes permission-generation changes with legacy
445 // resolver entry points while they transition onto PendingPromptOwner.
446 // It is never held while waiting for a user answer.
447 promptResolveMu sync.Mutex
448 }
449
450 // RuntimeStatus is the frontend-facing snapshot of foreground turn state. It is
451 // intentionally more explicit than the legacy Running bool so UI code can
452 // distinguish a cancellable foreground turn from pending prompts and background
453 // jobs.
454 type RuntimeStatus struct {
455 Running bool
456 PendingPrompt bool
457 BackgroundJobs int
458 CancelRequested bool
459 Cancellable bool
460 TurnID string
461 Status event.TurnStatus
462 TurnEventSeq uint64
463 ReplayAfterSeq uint64
464 }
465
466 const (
467 ToolApprovalReadOnly = string(permissionpreset.ReadOnly)
468 ToolApprovalWorkspaceWrite = string(permissionpreset.WorkspaceWrite)
469 ToolApprovalDangerFullAccess = string(permissionpreset.DangerFullAccess)
470 ToolApprovalDontAsk = "dontAsk"
471
472 // Deprecated source aliases. Persisted legacy strings are migrated by
473 // normalizeToolApprovalMode; these names keep older integrations building.
474 ToolApprovalAsk = ToolApprovalReadOnly
475 ToolApprovalAuto = ToolApprovalWorkspaceWrite
476 ToolApprovalYolo = ToolApprovalDangerFullAccess
477 )
478
479 const (
480 memoryRememberTool = "remember"
481 memoryForgetTool = "forget"
482 )
483
484 // RememberResult describes what happened when an approval rule was persisted.
485 type RememberResult struct {
486 Rule string
487 Path string
488 Saved bool
489 CoveredBy string
490 Err error
491 }
492
493 // PlanModeReadOnlyCommandTrustResult describes what happened when a trusted bash
494 // command prefix was persisted for plan-mode research.
495 type PlanModeReadOnlyCommandTrustResult struct {
496 Prefix string
497 Path string
498 Saved bool
499 CoveredBy string
500 Err error
501 }
502
503 type SessionRecoveryRequest struct {
504 OriginalPath string
505 Reason string
506 Mode string
507 }
508
509 type SessionRecoveryInfo struct {
510 OriginalPath string
511 RecoveryPath string
512 Existing bool
513 Reason string
514 BaseRevision int64
515 DiskRevision int64
516 Meta agent.BranchMeta
517 commit *sessionRecoveryCommit
518 }
519
520 func snapshotConflictRevisions(err error) (base, disk int64) {
521 var conflict *agent.SessionSnapshotConflictError
522 if errors.As(err, &conflict) && conflict != nil {
523 return conflict.BaseRevision, conflict.DiskRevision
524 }
525 return 0, 0
526 }
527
528 // OnCommit defers publication work until the controller has installed the
529 // recovery path and rebound all path-scoped state.
530 func (i SessionRecoveryInfo) OnCommit(fn func()) {
531 if i.commit != nil && fn != nil {
532 i.commit.hooks = append(i.commit.hooks, fn)
533 }
534 }
535
536 type sessionRecoveryCommit struct {
537 hooks []func()
538 }
539
540 func (c *sessionRecoveryCommit) publish() {
541 for _, hook := range c.hooks {
542 hook()
543 }
544 c.hooks = nil
545 }
546
547 type externalFolderToolRefs interface {
548 RegisterReadRoot(token, root string)
549 }
550
551 // Options carries the already-built pieces setup assembles. Lifecycle metadata
552 // lets the controller mint and rotate session files; Host/Commands are surfaced
553 // to frontends that resolve MCP prompts and slash commands.
554 type Options struct {
555 ImageRouteConfig *config.Config
556 Runner agent.Runner
557 Executor *agent.Agent
558 // Authentication is the frozen runtime credential snapshot's initial
559 // admission state. An empty value remains Ready for source compatibility.
560 Authentication AuthenticationState
561 AuthenticationForModel func(string) AuthenticationState
562 Guardian *guardian.Session
563 // RecoveryHeadless is decoded for source compatibility and ignored. Auto
564 // Guard cannot be re-enabled through Controller options.
565 RecoveryHeadless bool
566 // TaskBudget is the configured spend gate; unset leaves a turn unbounded.
567 TaskBudget agent.TaskBudget
568 // GoalTokenBudget bounds an unattended Goal loop by cumulative tokens.
569 GoalTokenBudget int
570 // GoalEvaluator is accepted only for source compatibility.
571 // when the working model submits no update_goal report. nil fails closed:
572 // the goal pauses instead of defaulting to continue.
573 GoalEvaluator any // deprecated: accepted but never invoked
574 Sink event.Sink
575 Policy permission.Policy
576 // SubagentGate is the shared, mutable gate every headless-only sub-agent
577 // surface (task, writer-capable skill sub-agents, planner) reads from. Nil
578 // disables gating for those surfaces same as before this field existed.
579 // SetToolApprovalMode and ApplyHeadlessApprovalMode call Update on it so a
580 // runtime approval-mode switch reaches sub-agents, not just the parent
581 // executor's own gate.
582 SubagentGate *SharedHeadlessGate
583 Label string
584 ModelRef string
585 ModelIdentity string
586 ResolveSessionModel func(string, string) (string, error)
587 // VisionModel is empty (off), "auto", or a canonical provider/model ref.
588 // The resolver and selector are assembled by boot so the controller remains
589 // transport-agnostic and tests can inject deterministic fake providers.
590 VisionModel string
591 VisionProviderResolver func(string) (provider.Provider, error)
592 VisionModelSelector func(string, string) (string, bool)
593 // ModelCapabilityResolver returns the adapter/config-resolved metadata for
594 // the exact active model. Nil keeps the legacy config-only behavior.
595 ModelCapabilityResolver func(*config.ProviderEntry) config.ResolvedModelCapability
596 // FrozenImageInput belongs to the provider instance built for this runtime.
597 FrozenImageInput *bool
598 ImageCapabilityChanged func() bool
599 ModelSettingsRevision string
600 ModelSettingsSourceRevision string
601 ModelSettingsCurrent func() (string, error)
602 ModelSettingsContinuation func() error
603 ModelConnectionTarget string
604 // BeforeInboxDispatch lets the owner reserve runtime admission before a
605 // queued message becomes a new turn. The returned release runs after claim
606 // and synchronous turn admission, outside every controller lock.
607 BeforeInboxDispatch func(*Controller) (func(), error)
608 SystemPrompt string
609 // PinnedContextLoader snapshots the current session sidecar at turn
610 // admission. The Agent persists changes as append-only user-role revisions.
611 PinnedContextLoader PinnedContextLoader
612 SessionDir string
613 SessionPath string
614 // SessionRuntime binds this Controller/Agent view to an already-published
615 // immutable v3 session identity. SessionService owns exact-instance close,
616 // fork, query and cancellation. ExclusiveSession disables legacy
617 // transcript and business-sidecar writes.
618 SessionService *session.Service
619 SessionCreateService *session.Service
620 SessionRuntime *session.Runtime
621 ExclusiveSession bool
622 NativeLegacySession bool
623 Host *plugin.Host
624 // MCPHostProfile is the surface lazily created hosts declare; injected
625 // hosts keep their own profile.
626 MCPHostProfile plugin.HostProfile
627 Commands []command.Command
628 Skills []skill.Skill
629 AllSkills []skill.Skill
630 SkillStore *skill.Store
631 AllSkillStore *skill.Store
632 // DisableImplicitSkillInvocation controls model-facing discovery only;
633 // explicit /skill commands and management remain host-side capabilities.
634 DisableImplicitSkillInvocation bool
635 // SkillRunner executes a runAs=subagent skill in an isolated child loop.
636 // ReadOnlySkillRunner is reserved for explicitly read-only entry points;
637 // Plan itself is a workflow instruction and uses SkillRunner with the shared
638 // Permissions/Sandbox gate. SkillProfile supplies model/effort display
639 // metadata for the synthetic top-level run_skill event.
640 SkillRunner skill.SubagentRunner
641 ReadOnlySkillRunner skill.SubagentRunner
642 SkillProfile skill.ProfileResolver
643 Hooks *hook.Runner
644 Memory *memory.Set
645 Cleanup func()
646 // BalanceURL/BalanceKey wire the active provider's optional wallet-balance
647 // endpoint and bearer key; empty when the provider declares no balance_url.
648 BalanceURL string
649 BalanceKey string
650 BalanceClient *http.Client
651 // Jobs is the session-scoped background-job manager (nil disables background jobs).
652 Jobs *jobs.Manager
653 BackgroundScope *jobs.SessionBackgroundScope
654 BackgroundSink event.Sink
655 // TaskStore remains a FileStore-compatible authority. Desktop injects one
656 // observed instance so recorder and task-control APIs share post-commit
657 // projection hints; nil preserves the ordinary FileStore.
658 TaskStore taskmonitor.WriteStore
659 // WorkspaceLease is the Delivery writer owner shared with the executor.
660 WorkspaceLease *workspacelease.Owner
661 // Registry is the executor's live tool set, and PluginCtx the session-scoped
662 // context; both are needed for hot-adding MCP servers via AddMCPServer.
663 Registry *tool.Registry
664 PluginCtx context.Context
665 // MCPDefaultCallTimeout is the global MCP call cap used by hot-connected
666 // servers when they do not declare a server- or tool-specific override.
667 MCPDefaultCallTimeout time.Duration
668 // MCPConfigureSpec injects host-local launch and isolation policy into every
669 // hot-connected server without persisting that state in project config.
670 MCPConfigureSpec func(*plugin.Spec)
671 // CapabilityRuntime is the controller-local authoritative MCP inventory used
672 // by stable use_capability frontends. It shares Host processes with sibling
673 // tabs but never shares their enabled/disabled state.
674 CapabilityRuntime *agent.MCPCapabilityRuntime
675 RuntimeGeneration uint64 // PublishGate generation for admission
676 // RuntimeOwner isolates publish/drain gates and receipts to one
677 // controller/session rebuild lineage. Nil preserves compatibility behavior.
678 RuntimeOwner *extension.RuntimeOwner
679 // WorkspaceRoot is the project root checkpoint restores are confined to ("" =
680 // no confinement). Frontends pass the cwd they launched the session in.
681 WorkspaceRoot string
682 WorkspaceRepo gitcmd.Repo // WorkspaceRoot's identity, resolved when the session opened
683 ExternalFolderToolRefs externalFolderToolRefs
684 // ResponseLanguage controls final-answer language preference. Empty/auto
685 // means no transient injection because the stable language policy follows the
686 // current user turn.
687 ResponseLanguage string
688 // ReasoningLanguage controls visible reasoning language preference. Empty/auto
689 // means no transient injection because the stable language policy already
690 // follows the conversation language.
691 ReasoningLanguage string
692 // SessionContextStatic carries boot-observed runtime facts that belong in a
693 // host user-turn snapshot rather than the cache-stable system prompt. Only
694 // Environment and Workspace are consumed; memory and skills stay live.
695 SessionContextStatic sessioncontext.Sections
696 // FileBranchesOnly keeps fork, branch, switch, and conversation rewind on
697 // separate session files even for schema-2 logs. Hosts that expose forks as
698 // independent conversations (desktop tabs and multi-session Serve) set it.
699 FileBranchesOnly bool
700 // DisableColdResumePrune suppresses the cold-resume cache-state notice.
701 // Resume never rewrites history regardless of this flag.
702 DisableColdResumePrune bool
703 // Shell is the interpreter user-invoked "!" commands run under, so /shell
704 // matches the agent's configured [tools.shell] choice. Zero value = auto.
705 Shell sandbox.Shell
706 // OnRemember, when set, is invoked with a new allow rule the user chose to
707 // persist to disk (e.g. "Bash(go test:*)"). The callback is wired into the
708 // permission Gate on EnableInteractiveApproval.
709 OnRemember func(rule string) RememberResult
710 // OnRememberPlanModeReadOnlyCommand persists a bash command prefix as trusted
711 // read-only when the user chooses "always allow" from the plan-mode trust
712 // prompt.
713 OnRememberPlanModeReadOnlyCommand func(prefix string) PlanModeReadOnlyCommandTrustResult
714 // OnPersistWriteAccess writes sandbox.allow_write and an optional permission
715 // rule to the workspace reasonix.toml as one transaction.
716 OnPersistWriteAccess PersistWriteAccessFunc
717 // WriteRoots is the session-scoped writable directory manager shared with
718 // built-in file tools and bash.
719 WriteRoots *sandbox.WritableRootSet
720 // BashSandboxEnforced is true when this session's bash tool actually wraps
721 // commands in an OS sandbox. Windows and bash=off leave this false so
722 // directory prompts are not implied for unisolated shell writes.
723 BashSandboxEnforced bool
724 // SessionRecoveryMeta lets a frontend attach scope/topic/profile metadata to
725 // an automatic recovery branch before it is written.
726 SessionRecoveryMeta func(SessionRecoveryRequest) agent.BranchMeta
727 // OnSessionRecovered is called after a stale runtime's transcript has been
728 // saved as a recovery branch, before the controller commits to that branch.
729 OnSessionRecovered func(SessionRecoveryInfo) error
730 // OnSessionTransition transfers write ownership before an intentional
731 // fork, branch, or switch publishes a different Session.
732 OnSessionTransition func(SessionTransitionInfo) error
733 // OnSessionRotation lets an identity-owning host durably reserve a fresh
734 // SessionID before /new or /clear publishes it. When installed, the host
735 // also owns clear archival; the controller never permanently deletes the
736 // source session.
737 OnSessionRotation func(context.Context, SessionRotationRequest) (SessionRotationPlan, error)
738 // ApprovalTimeout bounds how long a tool-approval or ask prompt blocks waiting
739 // for a user decision. Zero (default) waits forever — right for an interactive
740 // terminal. Bot/headless frontends set a positive value so an unanswered
741 // prompt can't wedge the session indefinitely (#4626, #4402).
742 ApprovalTimeout time.Duration
743 // Extensions is the frozen extension dispatcher for this controller
744 // generation (Extension Protocol v2, stage 6b1). Nil means no v2 runtime
745 // packages are installed: every extension wiring point takes an untouched
746 // fast path. Boot installs it through SetExtensions because sidecars (and
747 // therefore the dispatcher) only exist after snapshot assembly, which runs
748 // after New.
749 Extensions *dispatch.Dispatcher
750 // ProviderResolver is the build's merged provider catalog — extension
751 // sidecar providers folded over the config/broker base (stage 7). Nil when
752 // no v2 runtime sidecar declared providers; ProviderCatalog then returns
753 // nil and frontends enumerate providers from config alone, as before.
754 ProviderResolver provider.Resolver
755 // Ablation switches subsystems off for a benchmark arm. The zero value runs
756 // everything.
757 Ablation ablation.Set
758 // SessionTemp is the logical-session private temporary directory manager
759 // shared by sandboxed Bash calls. Nil creates a fresh Manager owned by this
760 // Controller. Hot rebuilds pass the previous Controller's Manager so the
761 // temporary directory survives model/settings swaps.
762 SessionTemp *sessiontemp.Manager
763 // PersistentShell is the session-scoped PTY used by ordinary foreground
764 // bash. Nil creates a fresh Manager owned by this Controller. Hot rebuilds
765 // pass the previous Controller's Manager so cwd and exported environment
766 // survive model/settings swaps.
767 PersistentShell *persistentshell.Manager
768 }
769
770 // New builds a Controller. A nil Sink becomes event.Discard; unless the caller
771 // already provided a goalUsageTee (NewGoalUsageTee), the sink is wrapped in one
772 // so billable usage can be accounted to Goal budgets.
773 func controllerSessionTemp(existing *sessiontemp.Manager) *sessiontemp.Manager {
774 if existing != nil {
775 return existing
776 }
777 return sessiontemp.New()
778 }
779
780 func controllerPersistentShell(existing *persistentshell.Manager) *persistentshell.Manager {
781 if existing != nil {
782 return existing
783 }
784 return persistentshell.New()
785 }
786
787 func New(opts Options) *Controller {
788 sink := opts.Sink
789 if nilutil.IsNil(sink) {
790 sink = event.Discard
791 }
792 usageTee, ok := sink.(*goalUsageTee)
793 if !ok {
794 usageTee = NewGoalUsageTee(sink).(*goalUsageTee)
795 sink = usageTee
796 }
797 pluginCtx := opts.PluginCtx
798 if pluginCtx == nil {
799 pluginCtx = context.Background()
800 }
801 runtimeOwner := runtimeOwnerOrDefault(opts.RuntimeOwner)
802 pluginCtx = extension.ContextWithRuntimeOwner(pluginCtx, runtimeOwner)
803 goalDriverCtx, goalDriverCancel := context.WithCancel(context.Background())
804 if opts.Hooks != nil {
805 opts.Hooks.SetSessionID(agent.BranchID(opts.SessionPath))
806 }
807 sessionRuntime, sessionBinding := bindInitialSessionRuntime(opts)
808 c := &Controller{
809 authentication: newAuthenticationGate(opts.Authentication, opts.ModelRef),
810 taskBudget: opts.TaskBudget,
811 goalTokenBudget: opts.GoalTokenBudget,
812 goalTokenLimit: opts.GoalTokenBudget,
813 goals: goalMachine{tokenBudget: opts.GoalTokenBudget},
814 runner: opts.Runner,
815 executor: opts.Executor,
816 guardianSess: opts.Guardian,
817 guardianPath: guardian.PathFor(opts.SessionPath),
818 goalUsageTee: usageTee,
819 sink: sink,
820 policy: opts.Policy,
821 subagentGate: opts.SubagentGate,
822 label: opts.Label,
823 selection: modelSelection{ref: opts.ModelRef, identity: opts.ModelIdentity},
824 resolveSessionModel: opts.ResolveSessionModel,
825 visionModel: strings.TrimSpace(opts.VisionModel),
826 visionProviderResolver: opts.VisionProviderResolver,
827 visionModelSelector: opts.VisionModelSelector,
828 modelCapabilityResolver: opts.ModelCapabilityResolver,
829 frozenImageInput: opts.FrozenImageInput,
830 imageCapabilityChanged: opts.ImageCapabilityChanged,
831 modelSettings: newControllerModelSettings(opts),
832 prompt: newControllerPromptState(opts.SystemPrompt, opts.Executor),
833 pinnedContextLoader: opts.PinnedContextLoader,
834 sessionContextStatic: opts.SessionContextStatic,
835 sessionDir: opts.SessionDir,
836 sessionPath: opts.SessionPath,
837 controllerSessionBinding: controllerSessionBinding{sessionService: opts.SessionService, sessionCreateService: opts.SessionCreateService, sessionRuntime: sessionRuntime, sessionBinding: sessionBinding, exclusiveSession: opts.ExclusiveSession, nativeLegacySession: opts.NativeLegacySession},
838 commands: atomic.Pointer[[]command.Command]{},
839 skills: newSkillSet(opts.Skills, opts.AllSkills, opts.SkillStore, opts.AllSkillStore),
840 disableImplicitSkillInvocation: opts.DisableImplicitSkillInvocation,
841 skillRunner: opts.SkillRunner,
842 readOnlySkillRunner: opts.ReadOnlySkillRunner,
843 skillProfile: opts.SkillProfile,
844 hooks: opts.Hooks,
845 memory: newMemoryManager(opts.Memory),
846 cleanup: opts.Cleanup,
847 responseLanguage: config.NormalizeLanguage(opts.ResponseLanguage),
848 reasoningLanguage: config.NormalizeReasoningLanguage(opts.ReasoningLanguage),
849 disableColdResumePrune: opts.DisableColdResumePrune,
850 headPolicy: sessionHeadPolicy{fileBranchesOnly: opts.FileBranchesOnly},
851 shell: opts.Shell,
852 onRemember: opts.OnRemember,
853 onRememberPlanModeReadOnlyCommand: opts.OnRememberPlanModeReadOnlyCommand,
854 writeAccess: newControllerWriteAccess(opts),
855 sessionRecoveryMeta: opts.SessionRecoveryMeta,
856 onSessionRecovered: opts.OnSessionRecovered,
857 onSessionTransition: opts.OnSessionTransition,
858 onSessionRotation: opts.OnSessionRotation,
859 balanceURL: opts.BalanceURL,
860 balanceKey: opts.BalanceKey,
861 balanceClient: opts.BalanceClient,
862 jobs: opts.Jobs,
863 background: controllerBackground{scope: opts.BackgroundScope, sink: opts.BackgroundSink,
864 candidate: opts.BackgroundScope != nil && opts.BackgroundScope.Manager.ReplacementInProgress()},
865 workspaceLease: opts.WorkspaceLease,
866 mcp: newMcpManager(opts.Host, opts.Registry, pluginCtx, opts.MCPHostProfile),
867 mcpDefaultCallTimeout: opts.MCPDefaultCallTimeout,
868 mcpConfigureSpec: opts.MCPConfigureSpec,
869 capabilityRuntime: opts.CapabilityRuntime,
870 ablation: opts.Ablation,
871 workspaceRoot: opts.WorkspaceRoot,
872 workspaceRepo: opts.WorkspaceRepo,
873 externalFolderToolRefs: opts.ExternalFolderToolRefs,
874 providerResolver: opts.ProviderResolver,
875 runtimeGeneration: opts.RuntimeGeneration,
876 runtimeOwner: runtimeOwner,
877 goalDriverControl: goalDriverControl{ctx: goalDriverCtx, cancel: goalDriverCancel},
878 approval: newApprovalManager(opts.Policy, ToolApprovalAsk, opts.ApprovalTimeout),
879 turns: turnLoop{phase: session.RuntimeIdle},
880 closeFinalized: make(chan struct{}),
881 }
882 c.authentication.initialForModel = opts.AuthenticationForModel
883 c.initializeOwnedResources(opts)
884 c.bindAttachmentService()
885 if opts.ImageRouteConfig != nil {
886 c.captureImageRoutes(opts.ImageRouteConfig)
887 }
888 return c
889 }
890
891 func (c *Controller) initializeOwnedResources(opts Options) {
892 if c.executor != nil {
893 c.executor.SetImageRequestResolver(c)
894 }
895 c.goalUsageTee.setLifecycleUsageRecorder(c.recordGoalLifecycleUsage)
896 c.installGoalLifecycle(opts.SessionRuntime)
897 c.managedSessionEvents.Store(opts.OnSessionTransition != nil)
898 c.permissionRevision.Store(1)
899 // Session-private temporary directory: reuse a shared Manager on hot
900 // rebuild, otherwise create one. Retain so ReleaseResources/Close drop the
901 // owner reference without racing a replacement Controller.
902 c.sessionTemp = controllerSessionTemp(opts.SessionTemp)
903 c.sessionTemp.Retain()
904 c.persistentShell = controllerPersistentShell(opts.PersistentShell)
905 c.persistentShell.Retain()
906 if strings.TrimSpace(opts.WorkspaceRoot) != "" {
907 c.legacyResearchArchive = legacyResearchArchive{store: autoresearch.NewStore(opts.WorkspaceRoot)}
908 }
909 if opts.Extensions != nil {
910 c.extensions = opts.Extensions
911 c.sink = newFrontendEventSink(c.sink, opts.Extensions)
912 if c.executor != nil {
913 c.executor.SetExtensions(opts.Extensions)
914 }
915 }
916 // Checkpoints: bind a store to the session and route writer pre-edits into it.
917 c.rebindCheckpoints(opts.SessionPath)
918 c.setActiveJobSession(opts.SessionPath)
919 c.rebindInbox()
920 // Observe Steer / unapplied-steer for durable inbox state transitions.
921 // Must wrap both the controller sink and the executor sink: agent.Steer
922 // emits on the executor path, TurnDone on the controller path.
923 c.sink = &inboxEventSink{inner: newTurnEventSink(c.sink, c), c: c}
924 if runner, ok := c.runner.(interface{ SetSink(event.Sink) }); ok {
925 runner.SetSink(c.sink)
926 }
927 // Establish mutation authority before any constructor-time session seed.
928 // A hot-rebuild candidate sharing an already-bound Runtime remains at
929 // generation zero and can restore from the projection without writing it.
930 c.bindExecutionControl()
931 if c.executor != nil {
932 c.executor.SetSink(c.sink)
933 c.executor.SetSessionCheckpointer(c)
934 if _, runtime, _ := c.v3Binding(); runtime != nil {
935 if runtime.StateSnapshot().Session.EventSequence == 0 {
936 if err := c.seedSessionEventsFromExecutor("session-open"); err != nil {
937 c.failTurnEventLedger(err)
938 }
939 }
940 c.restoreExecutorFromSessionEvents()
941 } else if err := c.seedSessionEventsFromExecutor("session-open"); err != nil {
942 c.failTurnEventLedger(err)
943 }
944 }
945 cmdsInit := opts.Commands
946 c.commands.Store(&cmdsInit)
947 if c.executor != nil {
948 c.wireMutationObserver()
949 c.executor.SetMemoryQueue(c)
950 }
951 // Task monitoring: record background-job lifecycle into the project-local
952 // task store so CLI, Desktop, scripts, and future clients observe the same
953 // state/event evidence. The recorder swallows its own failures — monitoring
954 // must never affect the agent pipeline. The session id is resolved lazily
955 // because the session path is only fixed once the first turn begins.
956 c.initializeTaskRecorder(opts.TaskStore)
957 c.initializeRuntimeState()
958 }
959
960 func (c *Controller) initializeTaskRecorder(store taskmonitor.WriteStore) {
961 if c.jobs == nil || c.workspaceRoot == "" {
962 return
963 }
964 if store == nil {
965 store = taskmonitor.NewFileStore(filepath.Join(".reasonix", "tasks"))
966 }
967 sessionID := func() string { return c.parentSessionID() }
968 if c.background.scope != nil {
969 sessionID = c.jobs.ActiveSessionID
970 }
971 recorder := taskmonitor.NewTaskRecorder(store, c.workspaceRoot, sessionID)
972 c.background.recorder = recorder
973 if c.background.scope == nil {
974 c.jobs.SetTaskRecorder(recorder)
975 }
976 }
977
978 // SetDisplayRecorder installs an optional hook used by frontends that persist a
979 // shorter user-facing transcript than the fully composed model prompt.
980 func (c *Controller) SetDisplayRecorder(fn func(content, display string)) {
981 c.mu.Lock()
982 defer c.mu.Unlock()
983 c.displayRecorder = fn
984 }
985
986 // SetExtensions installs the extension dispatcher after construction. Boot
987 // uses it because sidecars — and therefore the dispatcher — only exist after
988 // snapshot assembly, which runs after New. First non-nil install wins for the
989 // cold-start path; use ReplaceExtensions for generation-safe rebuild swaps.
990 // Nil is a no-op. The executor agent receives the same dispatcher (stage 6b2).
991 func (c *Controller) SetExtensions(d *dispatch.Dispatcher) {
992 if d == nil {
993 return
994 }
995 c.mu.Lock()
996 defer c.mu.Unlock()
997 if c.extensions != nil {
998 return
999 }
1000 c.installExtensionsLocked(d)
1001 }
1002
1003 // ReplaceExtensions atomically swaps the dispatcher for a reused controller
1004 // after a narrow rebuild. Updates sink strategy owner and executor together.
1005 func (c *Controller) ReplaceExtensions(d *dispatch.Dispatcher) {
1006 if c == nil || d == nil {
1007 return
1008 }
1009 c.mu.Lock()
1010 defer c.mu.Unlock()
1011 c.installExtensionsLocked(d)
1012 }
1013
1014 func (c *Controller) installExtensionsLocked(d *dispatch.Dispatcher) {
1015 c.extensions = d
1016 // Keep the inbox observer as the outermost sink so Steer/unapplied events
1017 // always update durable state, while still installing/updating the
1018 // frontendEventSink wrapper underneath for extension rulings.
1019 switch sink := c.sink.(type) {
1020 case *inboxEventSink:
1021 if lifecycle, ok := sink.inner.(*turnEventSink); ok {
1022 current := lifecycle.innerSnapshot()
1023 if existing, ok := current.(*frontendEventSink); ok {
1024 existing.setDispatcher(d)
1025 } else {
1026 lifecycle.setInner(newFrontendEventSink(current, d))
1027 }
1028 } else if existing, ok := sink.inner.(*frontendEventSink); ok {
1029 existing.setDispatcher(d)
1030 } else {
1031 sink.inner = newTurnEventSink(newFrontendEventSink(sink.inner, d), c)
1032 }
1033 case *frontendEventSink:
1034 sink.setDispatcher(d)
1035 // Ensure inbox observer stays outer.
1036 c.sink = &inboxEventSink{inner: newTurnEventSink(sink, c), c: c}
1037 default:
1038 c.sink = &inboxEventSink{inner: newTurnEventSink(newFrontendEventSink(c.sink, d), c), c: c}
1039 }
1040 if c.executor != nil {
1041 c.executor.SetExtensions(d)
1042 c.executor.SetSink(c.sink)
1043 }
1044 if runner, ok := c.runner.(interface{ SetSink(event.Sink) }); ok {
1045 runner.SetSink(c.sink)
1046 }
1047 }
1048
1049 // SetProviderResolver replaces the session's merged provider catalog (narrow
1050 // rebuild after sidecar Manager roll). Nil clears extension-hosted providers.
1051 func (c *Controller) SetProviderResolver(r provider.Resolver) {
1052 if c == nil {
1053 return
1054 }
1055 c.mu.Lock()
1056 c.providerResolver = r
1057 c.mu.Unlock()
1058 }
1059
1060 // SetOnSessionRecovered installs the ownership handoff invoked before the
1061 // controller commits to an automatically created recovery branch. Frontends
1062 // that acquire their session owner after controller construction (for example
1063 // reasonix serve) use this before publishing the controller.
1064 func (c *Controller) SetOnSessionRecovered(fn func(SessionRecoveryInfo) error) {
1065 if c == nil {
1066 return
1067 }
1068 c.mu.Lock()
1069 defer c.mu.Unlock()
1070 c.onSessionRecovered = fn
1071 }
1072
1073 func (c *Controller) sessionRecoveredHandler() func(SessionRecoveryInfo) error {
1074 c.mu.Lock()
1075 defer c.mu.Unlock()
1076 return c.onSessionRecovered
1077 }
1078
1079 func (c *Controller) recordDisplay(content, display string) {
1080 if strings.TrimSpace(display) == "" || content == display {
1081 return
1082 }
1083 c.mu.Lock()
1084 record := c.displayRecorder
1085 c.mu.Unlock()
1086 if record != nil {
1087 record(content, display)
1088 }
1089 }
1090
1091 // ToolContractEntries returns a stable snapshot of the executor's live tool
1092 // contract: provider-visible names, descriptions, canonical schemas, and
1093 // read-only flags. It is intended for diagnostics and regression tests.
1094 func (c *Controller) ToolContractEntries() []tool.ContractEntry {
1095 if c == nil {
1096 return nil
1097 }
1098 reg := c.mcp.registry()
1099 if reg == nil {
1100 return nil
1101 }
1102 return reg.ContractEntries()
1103 }
1104
1105 // AllToolContractEntries returns every registered tool, including those hidden
1106 // from the provider-visible schema and only reachable via use_capability.
1107 func (c *Controller) AllToolContractEntries() []tool.ContractEntry {
1108 if c == nil {
1109 return nil
1110 }
1111 reg := c.mcp.registry()
1112 if reg == nil {
1113 return nil
1114 }
1115 return reg.AllContractEntries()
1116 }
1117
1118 // ProviderCatalog returns the session's merged provider catalog: the config
1119 // (or broker) base plus every provider a live extension sidecar declared,
1120 // keyed by ref — extension refs carry their plugin/<plugin>/<provider>/<model>
1121 // namespace. Nil when no sidecar declared providers, so frontends can tell
1122 // "enumerate config only" apart from "the extension catalog is empty".
1123 func (c *Controller) ProviderCatalog() []provider.Descriptor {
1124 if c == nil {
1125 return nil
1126 }
1127 c.mu.Lock()
1128 r := c.providerResolver
1129 c.mu.Unlock()
1130 if r == nil {
1131 return nil
1132 }
1133 return r.Catalog()
1134 }
1135
1136 func (c *Controller) recordDisplayForNewUser(startMessages int, display string) {
1137 if strings.TrimSpace(display) == "" {
1138 return
1139 }
1140 msgs := c.History()
1141 if startMessages > len(msgs) {
1142 startMessages = len(msgs)
1143 }
1144 for _, m := range msgs[startMessages:] {
1145 if agent.IsUserAuthoredTurnMessage(m) {
1146 c.recordDisplay(m.Content, display)
1147 return
1148 }
1149 }
1150 }
1151
1152 func (c *Controller) markEditedForNewUser(startMessages int, original string) {
1153 if strings.TrimSpace(original) == "" || c.executor == nil {
1154 return
1155 }
1156 s := c.executor.Session()
1157 msgs := s.Snapshot()
1158 if startMessages > len(msgs) {
1159 startMessages = len(msgs)
1160 }
1161 for i := startMessages; i < len(msgs); i++ {
1162 if !agent.IsUserAuthoredTurnMessage(msgs[i]) {
1163 continue
1164 }
1165 if agent.UserMessageText(msgs[i]) == original {
1166 return
1167 }
1168 msgs[i].Edited = true
1169 msgs[i].Original = original
1170 // A periodic autosave may already contain this user message without its
1171 // local edit metadata. Classify the mutation atomically so the turn-end
1172 // save performs an owned rewrite instead of forking a bogus
1173 // same-revision recovery branch. Edited/Original are local-only display
1174 // metadata (provider requests ignore them), so this must not report a
1175 // cache-prefix change — ReplaceLocalMetadata, not Rewrite.
1176 s.ReplaceLocalMetadata(msgs)
1177 return
1178 }
1179 }
1180
1181 // ckptDir derives a session's checkpoint directory from its file path
1182 // (…/<id>.jsonl → …/<id>.ckpt). Empty path → empty (in-memory checkpoints).
1183 func ckptDir(sessionPath string) string {
1184 return store.SessionCheckpointDir(sessionPath)
1185 }
1186
1187 // rebindCheckpoints points the store at the (possibly new) session, loading any
1188 // checkpoints already on disk, and resets the turn boundaries. Called on
1189 // construction and whenever the session path changes (NewSession/Resume/SetSessionPath).
1190 // Also re-wires the mutation observer so capture targets the new store.
1191 func (c *Controller) rebindCheckpoints(sessionPath string) {
1192 if c.sessionEngineEnabled() {
1193 // Goal and runtime business state are v3 events. Legacy goal/checkpoint
1194 // sidecars must not become a second restore source in exclusive mode.
1195 c.goals.setStatePath("")
1196 c.checkpoints.rebind("", c.workspaceRoot, c.checkpointOptions()...)
1197 c.rebindTurnEvents(sessionPath)
1198 if c.executor != nil {
1199 c.wireMutationObserver()
1200 }
1201 return
1202 }
1203 c.goals.setStatePath(goalStatePath(sessionPath))
1204 c.checkpoints.rebind(ckptDir(sessionPath), c.workspaceRoot, c.checkpointOptions()...)
1205 c.rebindTurnEvents(sessionPath)
1206 if c.executor != nil {
1207 c.wireMutationObserver()
1208 }
1209 }
1210
1211 // commands (frontend → controller)
1212
1213 func (c *Controller) Send(input string) {
1214 c.SendWithRaw(input, input)
1215 }
1216
1217 // SendWithRaw starts a turn with separate model input and raw prompt text.
1218 func (c *Controller) SendWithRaw(input, raw string) {
1219 _, _ = c.submitIdentifiedWithSetup(SubmissionRequest{Input: input, Display: raw}, nil, func(admission turnAdmission) {
1220 c.runGuardedWithAdmission(func(ctx context.Context) error { return c.runGoalLoopWithRaw(ctx, input, raw) }, admission)
1221 })
1222 }
1223
1224 // planApprovalTool is the Tool name on the ApprovalRequest the controller emits
1225 // to gate a proposed plan. Frontends key their plan-approval UI on it (the
1226 // desktop renders a plan card; the chat TUI a plan banner).
1227 const planApprovalTool = "exit_plan_mode"
1228
1229 // PlanDecisionAction preserves the three user-owned meanings of the Plan card.
1230 // Revise and exit both deny execution at the approval gate, but they are not the
1231 // same product decision and must remain distinguishable in durable receipts.
1232 type PlanDecisionAction string
1233
1234 const (
1235 PlanDecisionStartExecution PlanDecisionAction = "start_execution"
1236 PlanDecisionRevisePlan PlanDecisionAction = "revise_plan"
1237 PlanDecisionExitPlan PlanDecisionAction = "exit_plan"
1238 )
1239
1240 // SandboxEscapeApprovalTool is the internal Tool name used for one-shot approval
1241 // to rerun a shell command without the OS sandbox after the sandbox failed.
1242 const SandboxEscapeApprovalTool = "sandbox_escape"
1243
1244 // ManagedConfigWriteApprovalTool is the internal Tool name used for per-write
1245 // approval when a file tool targets a Reasonix-managed config file outside the
1246 // workspace write roots. It is a fresh human decision: config files control
1247 // providers, sandbox rules, permissions, and MCP servers for future sessions,
1248 // so YOLO/auto approval must never answer it.
1249 const ManagedConfigWriteApprovalTool = "config_write"
1250
1251 // planApprovedMessage is the follow-up turn sent once the user approves a plan.
1252 // Approval grants the plan scope; the model owns any fresh todo list it chooses
1253 // to write during the execution turn.
1254 const planApprovedMessage = "Plan approved — plan mode is off. Implement the approved plan and user feedback. Explicit scope, permission and sandbox restrictions still apply. Update todos to reflect actual progress. Use the plan’s checks and acceptance notes as task instructions, and report what you changed and verified."
1255
1256 // runTurn runs one model turn, then applies the plan-approval gate. This is the
1257 // single, frontend-agnostic plan flow: in Plan the model is instructed to
1258 // research and write its plan as a normal answer, while any tool calls still use
1259 // the active Permissions/Sandbox path.
1260 // When the turn ends with a text proposal, the controller asks the user to
1261 // approve (reusing the ApprovalRequest channel both frontends already render);
1262 // on approval it exits plan mode and continues straight into execution; on
1263 // rejection it stays in plan mode so the
1264 // next turn can revise. Plan mode is only ever set interactively, so the headless
1265 // `Run` path (which doesn't call this) never blocks on a prompt.
1266 func (c *Controller) runTurn(ctx context.Context, input string) error {
1267 return c.runGoalLoopWithRaw(ctx, input, input)
1268 }
1269
1270 func (c *Controller) runTurnWithRaw(ctx context.Context, input, raw string) error {
1271 return c.runTurnWithRawDisplay(ctx, input, raw, "")
1272 }
1273
1274 func (c *Controller) runGoalLoopWithRaw(ctx context.Context, input, raw string) error {
1275 return c.runGoalLoopWithRawDisplay(ctx, input, raw, "")
1276 }
1277
1278 // withTurnFormat binds a structured-output format to the turn context
1279 // (empty is a no-op). Extracted from the runGoalLoop closure so tests can
1280 // assert the format actually reaches the agent request path.
1281 func (c *Controller) withTurnFormat(ctx context.Context, format string) context.Context {
1282 if format == "" {
1283 return ctx
1284 }
1285 return agent.WithResponseFormat(ctx, format)
1286 }
1287
1288 func (c *Controller) runGoalLoopWithRawDisplay(ctx context.Context, input, raw, display string) error {
1289 // Structured-output format is bound to the submitted turn (passed via
1290 // submitHTTPWithFormat → submitCommandOrTurn → runGoalLoop closure);
1291 // no global one-shot slot to race across concurrent requests.
1292 return newTurnOrchestrator(c).runGoalLoopWithRawDisplay(ctx, input, raw, display)
1293 }
1294
1295 func (c *Controller) runEditedGoalLoopWithRawDisplay(ctx context.Context, input, raw, display, original string) error {
1296 return newTurnOrchestrator(c).runEditedGoalLoopWithRawDisplay(ctx, input, raw, display, original)
1297 }
1298
1299 func (c *Controller) runTurnWithRawDisplay(ctx context.Context, input, raw, display string) error {
1300 return newTurnOrchestrator(c).runTurnWithRawDisplay(ctx, input, raw, display)
1301 }
1302
1303 func (c *Controller) runSubagentSkillSlash(sk skill.Skill, task, raw, display string, admission turnAdmission) {
1304 sk = c.skills.prepare(sk)
1305 c.runGuardedWithAdmission(func(ctx context.Context) error {
1306 planMode := c.PlanMode()
1307 runner := c.skillRunner
1308 if runner == nil {
1309 return fmt.Errorf("subagent skill runner is unavailable for /%s", sk.Name)
1310 }
1311 return newTurnOrchestrator(c).runSubagentSkillGoalLoop(ctx, sk, task, raw, display, runner, planMode)
1312 }, admission)
1313 }
1314
1315 func (c *Controller) stopGoal(status string) {
1316 path, data, ok := c.goals.stop(status)
1317 c.persistGoalState(path, data, ok)
1318 }
1319
1320 // lastAssistantText returns the content of the most recent assistant message with
1321 // non-empty text — the model's final answer for the turn (its plan, in plan mode).
1322 func lastAssistantText(msgs []provider.Message) string {
1323 for _, msg := range slices.Backward(msgs) {
1324 if msg.Role == provider.RoleAssistant && strings.TrimSpace(msg.Content) != "" {
1325 return msg.Content
1326 }
1327 }
1328 return ""
1329 }
1330
1331 // Submit is the one-call entry for a simple frontend: it takes raw user input
1332 // and does everything — slash-command dispatch, @-reference expansion, plan-mode
1333 // composition — emitting all output as events. The HTTP/SSE server uses this so
1334 // a browser client only POSTs the typed line.
1335 //
1336 // Slash commands route to the matching primitive: /compact, /new, and /clear
1337 // run their session op and emit a Notice; /mcp__server__prompt and custom /commands
1338 // resolve to a turn; an unknown slash emits a Notice. Anything else is a normal
1339 // turn with its @-references resolved first.
1340 func (c *Controller) Submit(input string) {
1341 c.submit(input, "", "")
1342 }
1343
1344 // SubmitHTTP accepts input from the unauthenticated localhost HTTP frontend. It
1345 // deliberately omits the trusted TUI-only "!cmd" shell shortcut and resolves file
1346 // references only through the controller's workspace root.
1347 func (c *Controller) SubmitHTTP(input string) {
1348 c.submitHTTP(input, "")
1349 }
1350
1351 // SubmitDisplay runs input as a turn while remembering the user-facing display
1352 // text for transcript replay when controller-side composition expands input.
1353 func (c *Controller) SubmitDisplay(display, input string) {
1354 c.submit(input, display, "")
1355 }
1356
1357 // SubmitInvocationDisplay executes composer-selected invocation entities
1358 // independently of slash-command parsing. Plain string submit entry points keep
1359 // their existing behavior for CLI, HTTP, and backward-compatible clients.
1360 func (c *Controller) SubmitInvocationDisplay(display, input string, invocations []InvocationRequest) {
1361 c.submitInvocations(input, display, invocations)
1362 }
1363
1364 func (c *Controller) submitInvocations(input, display string, requests []InvocationRequest) {
1365 _, _ = c.submitIdentifiedWithSetup(SubmissionRequest{Input: input, Display: display, Invocations: requests}, nil, func(admission turnAdmission) {
1366 c.submitInvocationsLocked(input, display, requests, admission)
1367 })
1368 }
1369
1370 func (c *Controller) submitInvocationsLocked(input, display string, requests []InvocationRequest, admission turnAdmission) {
1371 if len(requests) == 0 {
1372 c.submitLocked(input, display, "", admission)
1373 return
1374 }
1375 prepared, err := c.prepareInvocationTurn(input, requests)
1376 if err != nil {
1377 c.notice(err.Error())
1378 return
1379 }
1380 c.runGuardedWithAdmission(func(ctx context.Context) error {
1381 return c.runPreparedInvocationTurn(ctx, prepared, input, input, display, nil)
1382 }, admission)
1383 }
1384
1385 type preparedInvocationTurn struct {
1386 composed string
1387 subagents []skill.Skill
1388 inlineSkillNames []string
1389 }
1390
1391 func (c *Controller) prepareInvocationTurn(input string, requests []InvocationRequest) (preparedInvocationTurn, error) {
1392 ordered := append([]InvocationRequest(nil), requests...)
1393 sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].Offset < ordered[j].Offset })
1394 inline := make([]skill.Skill, 0, len(ordered))
1395 subagents := make([]skill.Skill, 0, len(ordered))
1396 for _, request := range ordered {
1397 sk, _, ok := c.resolveSkillInvocation("/" + strings.TrimSpace(request.Name))
1398 if !ok {
1399 return preparedInvocationTurn{}, fmt.Errorf("unknown invocation: /%s", strings.TrimSpace(request.Name))
1400 }
1401 kind := "skill"
1402 if sk.RunAs == skill.RunSubagent {
1403 kind = "subagent"
1404 }
1405 if strings.TrimSpace(request.Kind) != "" && request.Kind != kind {
1406 return preparedInvocationTurn{}, fmt.Errorf("invocation /%s is %s, not %s", sk.SlashName(), kind, request.Kind)
1407 }
1408 if sk.RunAs == skill.RunSubagent {
1409 subagents = append(subagents, sk)
1410 } else {
1411 inline = append(inline, sk)
1412 }
1413 }
1414
1415 if strings.TrimSpace(input) == "" && len(subagents) > 0 {
1416 return preparedInvocationTurn{}, fmt.Errorf("subagent invocation requires a task")
1417 }
1418 inlineSkillNames := make([]string, 0, len(inline))
1419 for _, sk := range inline {
1420 inlineSkillNames = append(inlineSkillNames, sk.Name)
1421 }
1422 // A lone inline skill takes the typed text as its arguments, as "/name task" does.
1423 if len(inline) == 1 && len(subagents) == 0 {
1424 return preparedInvocationTurn{composed: c.skills.renderInvocation(inline[0], strings.TrimSpace(input)), inlineSkillNames: inlineSkillNames}, nil
1425 }
1426 parts := make([]string, 0, len(inline)+1)
1427 for _, sk := range inline {
1428 parts = append(parts, c.skills.renderInvocation(sk, ""))
1429 }
1430 if strings.TrimSpace(input) != "" {
1431 parts = append(parts, input)
1432 }
1433 return preparedInvocationTurn{composed: strings.Join(parts, "\n\n"), subagents: subagents, inlineSkillNames: inlineSkillNames}, nil
1434 }
1435
1436 func (c *Controller) runPreparedInvocationTurn(
1437 ctx context.Context,
1438 prepared preparedInvocationTurn,
1439 input, raw, display string,
1440 frozenImages []string,
1441 ) error {
1442 ctx = withInvokedSkills(ctx, prepared.inlineSkillNames)
1443 if len(prepared.subagents) == 0 {
1444 return c.runGoalLoopWithFrozenImagesRawDisplay(ctx, prepared.composed, raw, display, frozenImages)
1445 }
1446 runner := c.skillRunner
1447 if runner == nil {
1448 return fmt.Errorf("subagent skill runner is unavailable")
1449 }
1450 return newTurnOrchestrator(c).runSubagentSkillTurnsGoalLoop(
1451 ctx,
1452 prepared.subagents,
1453 prepared.composed,
1454 input,
1455 display,
1456 runner,
1457 c.PlanMode(),
1458 frozenImages,
1459 )
1460 }
1461
1462 // SubmitEditedDisplay is SubmitDisplay for an inline-edited prompt. The model
1463 // sees input; the saved user message also keeps the pre-edit prompt as local UI
1464 // metadata so the edit survives session rewrites.
1465 func (c *Controller) SubmitEditedDisplay(display, input, original string) {
1466 c.submit(input, display, original)
1467 }
1468
1469 // SubmitUserTurn starts a normal model turn without interpreting shell or slash
1470 // commands. It still resolves references, so callers can submit trusted
1471 // user-authored prompt text without expanding the command surface.
1472 func (c *Controller) SubmitUserTurn(input, display string) {
1473 _, _ = c.submitIdentifiedWithSetup(SubmissionRequest{Input: input, Display: display}, nil, func(admission turnAdmission) {
1474 c.runRefTurnWithAdmission(input, display, admission)
1475 })
1476 }
1477
1478 func (c *Controller) submit(input, display, editedOriginal string) {
1479 if isSessionManagementSubmission(input) {
1480 c.submissions.mu.Lock()
1481 defer c.releaseSubmissionAdmission()
1482 c.submitLocked(input, display, editedOriginal, turnAdmission{})
1483 return
1484 }
1485 _, _ = c.submitIdentifiedWithSetup(SubmissionRequest{Input: input, Display: display, Original: editedOriginal}, nil, func(admission turnAdmission) {
1486 c.submitLocked(input, display, editedOriginal, admission)
1487 })
1488 }
1489
1490 func (c *Controller) submitLocked(input, display, editedOriginal string, admission turnAdmission) {
1491 trimmed := strings.TrimSpace(input)
1492 if note, ok := MemoryQuickAddNote(trimmed); ok {
1493 c.rememberProjectNote(note)
1494 return
1495 }
1496 if note, ok := RememberCommandNote(trimmed); ok {
1497 c.rememberProjectNote(note)
1498 return
1499 }
1500 if c.applyGoalCommandWithAdmission(trimmed, display, admission) {
1501 return
1502 }
1503 if strings.HasPrefix(trimmed, "!") {
1504 c.RunShell(trimmed[1:])
1505 return
1506 }
1507 c.submitCommandOrTurn(trimmed, input, display, false, editedOriginal, "", admission)
1508 }
1509
1510 func (c *Controller) submitHTTP(input, display string) {
1511 c.submitHTTPWithFormat(input, display, "")
1512 }
1513
1514 func (c *Controller) submitHTTPWithFormat(input, display, format string) {
1515 if isSessionManagementSubmission(input) {
1516 c.submissions.mu.Lock()
1517 defer c.releaseSubmissionAdmission()
1518 c.submitHTTPWithFormatLocked(input, display, format, turnAdmission{})
1519 return
1520 }
1521 _, _ = c.submitIdentifiedWithSetup(SubmissionRequest{Input: input, Display: display, HTTP: true, Format: format}, nil, func(admission turnAdmission) {
1522 c.submitHTTPWithFormatLocked(input, display, format, admission)
1523 })
1524 }
1525
1526 func (c *Controller) submitHTTPWithFormatLocked(input, display, format string, admission turnAdmission) {
1527 trimmed := strings.TrimSpace(input)
1528 if note, ok := MemoryQuickAddNote(trimmed); ok {
1529 c.rememberProjectNote(note)
1530 return
1531 }
1532 if note, ok := RememberCommandNote(trimmed); ok {
1533 c.rememberProjectNote(note)
1534 return
1535 }
1536 if c.applyGoalCommandWithAdmission(trimmed, display, admission) {
1537 return
1538 }
1539 if strings.HasPrefix(trimmed, "!") {
1540 c.notice("shell commands are unavailable from this frontend")
1541 return
1542 }
1543 c.submitCommandOrTurn(trimmed, input, display, true, "", format, admission)
1544 }
1545
1546 func (c *Controller) submitCommandOrTurnReady(trimmed, input, display string, scopedRefsOnly bool, editedOriginal, format string, admission turnAdmission) {
1547 runRefTurn := func(input, display string) {
1548 c.runRefTurnWithFormat(input, display, format, admission)
1549 }
1550 runRefTurnWithRefs := func(input, refLine, display string) {
1551 c.runRefTurnWithRefsFormat(input, refLine, display, format, admission)
1552 }
1553 runGoalLoop := func(ctx context.Context, input, raw, display string) error {
1554 return c.runGoalLoopWithRawDisplay(c.withTurnFormat(ctx, format), input, raw, display)
1555 }
1556 if scopedRefsOnly {
1557 runRefTurn = func(input, display string) {
1558 c.runScopedRefTurnWithFormat(input, display, format, admission)
1559 }
1560 runRefTurnWithRefs = func(input, refLine, display string) {
1561 c.runScopedRefTurnWithRefsFormat(input, refLine, display, format, admission)
1562 }
1563 }
1564 if strings.TrimSpace(editedOriginal) != "" {
1565 runRefTurn = func(input, display string) {
1566 c.runEditedRefTurnWithFormat(input, display, editedOriginal, format, admission)
1567 }
1568 runRefTurnWithRefs = func(input, refLine, display string) {
1569 c.runEditedRefTurnWithRefsFormat(input, refLine, display, editedOriginal, format, admission)
1570 }
1571 runGoalLoop = func(ctx context.Context, input, raw, display string) error {
1572 return c.runEditedGoalLoopWithRawDisplay(ctx, input, raw, display, editedOriginal)
1573 }
1574 }
1575 if id, guidance, ok := ParseProtocolRecoveryCommand(trimmed); ok {
1576 c.submitProtocolRecoveryLocked(id, guidance, admission)
1577 return
1578 }
1579 if c.submitFinalReadinessCommand(trimmed, display, admission) {
1580 return
1581 }
1582 switch {
1583 case trimmed == "/compact" || strings.HasPrefix(trimmed, "/compact "):
1584 focus := strings.TrimSpace(strings.TrimPrefix(trimmed, "/compact"))
1585 // Register synchronously before returning the management-command receipt.
1586 // This removes the window in which the command looked complete while a
1587 // new turn could still enter before compaction claimed the session.
1588 if err := c.startCompactAsync(focus); err != nil {
1589 c.notice("compaction failed: " + err.Error())
1590 }
1591 case trimmed == "/context":
1592 c.noticeDetail(c.ContextReport())
1593 case trimmed == "/new":
1594 c.runSessionVerb(c.NewSession, "new session", "new session failed: ")
1595 case trimmed == "/clear":
1596 c.runSessionVerb(c.ClearSession, "context cleared", "clear context failed: ")
1597 case strings.HasPrefix(trimmed, "/mcp__"):
1598 c.runGuardedWithAdmission(func(ctx context.Context) error {
1599 sent, found, err := c.MCPPrompt(ctx, trimmed)
1600 if err != nil {
1601 return err
1602 }
1603 if !found {
1604 c.notice("unknown command: " + trimmed)
1605 return nil
1606 }
1607 return runGoalLoop(ctx, sent, sent, display)
1608 }, admission)
1609 case SlashCodeCommentLine(trimmed):
1610 // Slash-prefixed code comments are prompt text, not slash commands.
1611 runRefTurn(input, display)
1612 case strings.HasPrefix(trimmed, "/"):
1613 if ref, ok := FileRefLine(trimmed); ok {
1614 runRefTurn(ref, display)
1615 return
1616 }
1617 if ref, ok := SlashPathLineRef(trimmed, c.workspaceRoot); ok {
1618 runRefTurnWithRefs(input, ref, display)
1619 return
1620 }
1621 if SlashPathLikeLine(trimmed) {
1622 runRefTurn(input, display)
1623 return
1624 }
1625 // Management verbs (/model /memory /skills /hooks /mcp) emit a Notice, so
1626 // Submit-based frontends (desktop, HTTP) get them with no extra wiring.
1627 // The chat TUI handles these itself with richer output.
1628 fields := strings.Fields(trimmed)
1629 switch fields[0] {
1630 case "/tree":
1631 c.notice(c.BranchTreeText())
1632 return
1633 case "/branch":
1634 args := strings.TrimSpace(strings.TrimPrefix(trimmed, fields[0]))
1635 if turn, name, fromTurn, err := ParseBranchTarget(args); err != nil {
1636 c.notice(err.Error())
1637 } else if fromTurn {
1638 if _, err := c.ForkNamed(turn-1, name); err != nil {
1639 c.notice(err.Error())
1640 }
1641 } else {
1642 if _, err := c.Branch(name); err != nil {
1643 c.notice(err.Error())
1644 }
1645 }
1646 return
1647 case "/switch":
1648 ref := strings.TrimSpace(strings.TrimPrefix(trimmed, fields[0]))
1649 if _, err := c.SwitchBranch(ref); err != nil {
1650 c.notice(err.Error())
1651 }
1652 return
1653 case "/rewind":
1654 args := strings.TrimSpace(strings.TrimPrefix(trimmed, fields[0]))
1655 turn, scope, err := parseRewind(args, c.Checkpoints())
1656 if err != nil {
1657 c.notice("usage: /rewind [turn] [code|conversation|both]")
1658 return
1659 }
1660 if err := c.Rewind(turn, scope); err != nil {
1661 c.notice(err.Error())
1662 }
1663 return
1664 case "/plan-exec":
1665 c.applyPlanExec(trimmed, display)
1666 return
1667 case "/prometheus":
1668 c.applyPrometheus(trimmed, display, admission)
1669 return
1670 }
1671 if c.managementNotice(trimmed) {
1672 return
1673 }
1674 if IsBuiltinDocsSlash(fields[0], c.Commands(), c.SlashSkills()) {
1675 query := strings.TrimSpace(strings.TrimPrefix(trimmed, fields[0]))
1676 if query == "" {
1677 text, err := DocsCommandOverviewFor(fields[0])
1678 if err != nil {
1679 c.notice("docs: " + err.Error())
1680 } else {
1681 c.notice(text)
1682 }
1683 return
1684 }
1685 c.runGuardedWithAdmission(func(ctx context.Context) error {
1686 sent, err := docsCommandPrompt(ctx, query)
1687 if err != nil {
1688 return fmt.Errorf("docs: %w", err)
1689 }
1690 return runGoalLoop(ctx, sent, sent, display)
1691 }, admission)
1692 return
1693 }
1694 // A custom command wins over a skill of the same name; both resolve to a
1695 // turn. Built-ins and their explicit Reasonix namespace are handled above.
1696 if sent, ok := c.CustomCommand(trimmed); ok {
1697 c.runGuardedWithAdmission(func(ctx context.Context) error {
1698 return runGoalLoop(ctx, sent, sent, display)
1699 }, admission)
1700 return
1701 }
1702 if sk, task, ok := c.resolveSkillInvocation(trimmed); ok {
1703 if sk.RunAs == skill.RunSubagent {
1704 if strings.TrimSpace(task) == "" {
1705 c.notice("usage: /" + sk.Name + " <task>")
1706 return
1707 }
1708 c.runSubagentSkillSlash(sk, task, trimmed, display, admission)
1709 return
1710 }
1711 sent := c.skills.renderInvocation(sk, task)
1712 c.runGuardedWithAdmission(func(ctx context.Context) error {
1713 return runGoalLoop(withInvokedSkills(ctx, []string{sk.Name}), sent, input, display)
1714 }, admission)
1715 return
1716 }
1717 // Unknown slash input is prose more often than a typo ("/etc/hosts
1718 // looks wrong", pasted paths, half-remembered commands) — send it as a
1719 // regular message instead of dead-ending the submission, with a notice
1720 // so real typos are still visible (#5756).
1721 c.notice("unknown command: " + trimmed + " — sent as a regular message")
1722 runRefTurn(input, display)
1723 default:
1724 runRefTurn(input, display)
1725 }
1726 }
1727
1728 func (c *Controller) rememberProjectNote(note string) {
1729 if note == "" {
1730 c.notice("nothing to remember")
1731 return
1732 }
1733 if path, err := c.QuickAdd(memory.ScopeProject, note); err != nil {
1734 c.notice("memory: " + err.Error())
1735 } else {
1736 c.notice("remembered → " + path)
1737 }
1738 }
1739
1740 // applyPlanExec is a command tombstone. The old path coupled Plan approval,
1741 // todo state and Goal continuation and is intentionally absent from the runtime.
1742 func (c *Controller) applyPlanExec(_, _ string) {
1743 c.notice("/plan-exec is retired; approve the Plan, then let the model create a fresh todo list for the new turn")
1744 }
1745
1746 // prometheusPrompt is the strategic planner system prompt.
1747 const prometheusPrompt = "You are Prometheus, a strategic planner. Interview the user one question at a time. Cover: scope, modules, files, constraints, tests. When ready, output a numbered plan with each step tagged by module. Read the current goal with get_goal, then call update_goal with its exact ID/revision and action complete. Do not implement.\n\nFor independent research directions, use parallel_tasks before planning."
1748
1749 // applyPrometheus starts an interactive planning interview, inspired by OMO's
1750 // Prometheus agent. It enters goal mode with a structured interview prompt.
1751 func (c *Controller) applyPrometheus(input, display string, admission turnAdmission) {
1752 args := strings.TrimSpace(strings.TrimPrefix(input, "/prometheus"))
1753 if args == "" || args == "--strict" {
1754 c.notice("usage: /prometheus <your task description>")
1755 return
1756 }
1757 strict := false
1758 if strings.HasPrefix(args, "--strict ") {
1759 strict = true
1760 args = strings.TrimPrefix(args, "--strict ")
1761 }
1762 prompt := prometheusPrompt + "\n\n## User request\n\n" + args + "\n\nBegin the interview by asking your first clarifying question."
1763 c.SetPlanMode(false)
1764 c.SetGoal("plan: " + ShortGoalForNotice(args))
1765 c.GoalStrict(strict)
1766 c.notice("prometheus: starting planning interview")
1767 if c.runner != nil {
1768 c.runGuardedWithAdmission(func(ctx context.Context) error {
1769 return c.runGoalLoopWithRawDisplay(ctx, prompt, prompt, display)
1770 }, admission)
1771 }
1772 }
1773
1774 // shellTimeout is the maximum time a user-invoked "!command" may run. Matches
1775 // the bash tool's timeout so behaviour is consistent across invocation paths.
1776 const shellTimeout = 120 * time.Second
1777
1778 // shellWaitDelay bounds how long cmd.Run() waits after context cancellation for
1779 // the child's pipes to drain, matching the bash tool's WaitDelay.
1780 const shellWaitDelay = 5 * time.Second
1781
1782 func shellCommandPreview(command string) string {
1783 command = strings.TrimSpace(strings.ReplaceAll(command, "\n", " "))
1784 const max = 48
1785 r := []rune(command)
1786 if len(r) > max {
1787 return string(r[:max]) + "…"
1788 }
1789 return command
1790 }
1791
1792 // RunShell executes a shell command directly (bypassing the model) and streams
1793 // the output as ToolDispatch/ToolProgress/ToolResult events. It uses the same
1794 // bash-tool infrastructure (shell resolution, timeout) and shares the runGuarded
1795 // lock with model turns — only one can run at a time. User-invoked "!" commands
1796 // run without the OS sandbox (the user typed the command explicitly).
1797 func (c *Controller) RunShell(command string) {
1798 c.runShell(command, turnAdmission{})
1799 }
1800
1801 func (c *Controller) runShell(command string, admission turnAdmission) {
1802 command = strings.TrimSpace(command)
1803 if command == "" {
1804 c.notice(i18n.M.ShellExecEmpty)
1805 return
1806 }
1807 c.runGuardedWithAdmission(func(ctx context.Context) error {
1808 sh := c.shell
1809 if sh.Path == "" {
1810 sh = sandbox.ResolveShell("", "", nil)
1811 }
1812 argv, _ := sandbox.Command(sandbox.Spec{}, sh, command) // false = unsandboxed (user invoked)
1813
1814 preview := []rune(command)
1815 if len(preview) > 32 {
1816 preview = preview[:32]
1817 }
1818 id := "shell-" + string(preview)
1819 diagnosticPreview := shellCommandPreview(command)
1820 desc := shellrun.DescriptorFromShell(sh)
1821 toolName := "bash"
1822 if sh.Kind == sandbox.ShellPowerShell {
1823 toolName = "pwsh"
1824 }
1825
1826 if err := event.EmitChecked(c.sink, event.Event{
1827 Kind: event.ToolDispatch,
1828 Tool: event.Tool{
1829 ID: id,
1830 Name: toolName,
1831 Args: fmt.Sprintf(`{"command":%q}`, command),
1832 Execution: &event.ShellExecution{
1833 Kind: desc.Kind, Shell: desc.Shell, ShellVersion: desc.ShellVersion,
1834 Platform: desc.Platform, SupportsAndAnd: desc.SupportsAndAnd,
1835 State: tool.ShellStateRunning,
1836 },
1837 },
1838 }); err != nil {
1839 return fmt.Errorf("persist shell dispatch: %w", err)
1840 }
1841
1842 start := time.Now()
1843 res := shellrun.RunForeground(ctx, shellrun.Request{
1844 Argv: argv,
1845 Dir: c.workspaceRoot,
1846 Env: shellrun.LoginEnvironment(ctx, os.Environ(), sh.Path),
1847 Timeout: shellTimeout,
1848 WaitDelay: shellWaitDelay,
1849 CommandPreview: diagnosticPreview,
1850 ShellKind: sh.Kind.String(),
1851 ShellPath: sh.Path,
1852 Source: "user_shell",
1853 Track: true,
1854 Progress: func(chunk string) {
1855 c.sink.Emit(event.Event{
1856 Kind: event.ToolProgress,
1857 Tool: event.Tool{ID: id, Output: chunk},
1858 })
1859 },
1860 })
1861 durationMs := time.Since(start).Milliseconds()
1862 ex := &event.ShellExecution{
1863 Kind: desc.Kind, Shell: desc.Shell, ShellVersion: desc.ShellVersion,
1864 Platform: desc.Platform, SupportsAndAnd: desc.SupportsAndAnd,
1865 State: res.State, FailurePhase: res.FailurePhase,
1866 OutputTail: res.OutputTail, DurationMs: durationMs,
1867 MutationRisk: tool.ShellMutationNone,
1868 Verification: tool.ShellVerificationNotVerification,
1869 }
1870 if res.ExitCode != nil {
1871 code := *res.ExitCode
1872 ex.ExitCode = &code
1873 }
1874 switch res.State {
1875 case tool.ShellStateCompleted:
1876 ex.MutationRisk = tool.ShellMutationNone
1877 case tool.ShellStateNotRun:
1878 ex.MutationRisk = tool.ShellMutationNotStarted
1879 case tool.ShellStateFailed:
1880 if res.FailurePhase == tool.ShellPhaseLaunch {
1881 ex.MutationRisk = tool.ShellMutationNotStarted
1882 } else {
1883 ex.MutationRisk = tool.ShellMutationMayBePartial
1884 }
1885 case tool.ShellStateTimedOut, tool.ShellStateCancelled:
1886 ex.MutationRisk = tool.ShellMutationMayBePartial
1887 }
1888
1889 errText := ""
1890 switch res.State {
1891 case tool.ShellStateCancelled:
1892 errText = i18n.M.TurnCancelled
1893 case tool.ShellStateTimedOut:
1894 errText = fmt.Sprintf(i18n.M.ShellExecTimeoutFmt, shellTimeout)
1895 case tool.ShellStateFailed, tool.ShellStateNotRun:
1896 if res.Err != nil {
1897 errText = fmt.Sprintf(i18n.M.ShellExecFailedFmt, res.Err)
1898 }
1899 }
1900 c.sink.Emit(event.Event{
1901 Kind: event.ToolResult,
1902 Tool: event.Tool{
1903 ID: id, Name: "bash", Output: res.Combined, Err: errText,
1904 DurationMs: durationMs, Execution: ex,
1905 },
1906 })
1907 return nil
1908 }, admission)
1909 }
1910
1911 // runRefTurn resolves a line's @references into a context block and starts a
1912 // turn with it prepended (or the raw line when nothing resolved).
1913 func (c *Controller) runRefTurn(input, display string) {
1914 c.runRefTurnWithAdmission(input, display, turnAdmission{})
1915 }
1916
1917 func (c *Controller) runRefTurnWithAdmission(input, display string, admission turnAdmission) {
1918 c.runRefTurnWithRefs(input, input, display, admission)
1919 }
1920
1921 // runRefTurnWithFormat runs a reference turn with a structured-output
1922 // format bound to its context (symmetric with runGoalLoop's withTurnFormat
1923 // injection — format is a property of every accepted turn, not just the
1924 // plain-goal path; review #7234 binds format to the accepted turn).
1925 func (c *Controller) runRefTurnWithFormat(input, display, format string, admission turnAdmission) {
1926 c.runPreparedRefTurn(input, input, display, "", c.resolveUnscopedRefsForTurn, func(ctx context.Context) context.Context {
1927 return c.withTurnFormat(ctx, format)
1928 }, admission)
1929 }
1930
1931 func (c *Controller) runScopedRefTurnWithFormat(input, display, format string, admission turnAdmission) {
1932 c.runPreparedRefTurn(input, input, display, "", c.resolveScopedRefsForTurn, func(ctx context.Context) context.Context {
1933 return c.withTurnFormat(ctx, format)
1934 }, admission)
1935 }
1936
1937 func (c *Controller) runRefTurnWithRefsFormat(input, refLine, display, format string, admission turnAdmission) {
1938 c.runPreparedRefTurn(input, refLine, display, "", c.resolveUnscopedRefsForTurn, func(ctx context.Context) context.Context {
1939 return c.withTurnFormat(ctx, format)
1940 }, admission)
1941 }
1942
1943 func (c *Controller) runScopedRefTurnWithRefsFormat(input, refLine, display, format string, admission turnAdmission) {
1944 c.runPreparedRefTurn(input, refLine, display, "", c.resolveScopedRefsForTurn, func(ctx context.Context) context.Context {
1945 return c.withTurnFormat(ctx, format)
1946 }, admission)
1947 }
1948
1949 func (c *Controller) runEditedRefTurnWithFormat(input, display, original, format string, admission turnAdmission) {
1950 c.runPreparedRefTurn(input, input, display, original, c.resolveUnscopedRefsForTurn, func(ctx context.Context) context.Context {
1951 return c.withTurnFormat(ctx, format)
1952 }, admission)
1953 }
1954
1955 func (c *Controller) runEditedRefTurnWithRefsFormat(input, refLine, display, original, format string, admission turnAdmission) {
1956 c.runPreparedRefTurn(input, refLine, display, original, c.resolveUnscopedRefsForTurn, func(ctx context.Context) context.Context {
1957 return c.withTurnFormat(ctx, format)
1958 }, admission)
1959 }
1960
1961 // runRefTurnWithRefs resolves references from refLine while preserving input as
1962 // the user's actual prompt text. This lets compiler diagnostics such as
1963 // "/path/File.kt:12: error" attach @/path/File.kt without rewriting the error.
1964 func (c *Controller) runRefTurnWithRefs(input, refLine, display string, admission turnAdmission) {
1965 c.runRefTurnWithResolver(input, refLine, display, c.resolveUnscopedRefsForTurn, admission)
1966 }
1967
1968 func (c *Controller) runRefTurnWithResolver(input, refLine, display string, resolve func(context.Context, string) resolvedReferences, admission turnAdmission) {
1969 c.runPreparedRefTurn(input, refLine, display, "", resolve, func(ctx context.Context) context.Context { return ctx }, admission)
1970 }
1971
1972 func (c *Controller) runRefTurnWithResolverSync(ctx context.Context, input, refLine, display, original string, resolve func(context.Context, string) resolvedReferences) error {
1973 resolved := resolve(ctx, refLine)
1974 return c.runResolvedRefTurnSync(ctx, input, display, original, resolved)
1975 }
1976
1977 func (c *Controller) runResolvedRefTurnSync(ctx context.Context, input, display, original string, resolved resolvedReferences) error {
1978 if len(resolved.imageErrs) > 0 {
1979 return ImageReferenceFailures(resolved.imageErrs)
1980 }
1981 for _, e := range resolved.errs {
1982 c.notice(e)
1983 }
1984 sent := input
1985 if resolved.block != "" {
1986 sent = "Referenced context:\n\n" + resolved.block + "\n\n" + input
1987 }
1988 if strings.TrimSpace(original) != "" {
1989 return c.runEditedGoalLoopWithFrozenImagesRawDisplay(ctx, sent, input, display, original, resolved.images)
1990 }
1991 return c.runGoalLoopWithFrozenImagesRawDisplay(ctx, sent, input, display, resolved.images)
1992 }
1993
1994 // notice emits an informational Notice event.
1995 func (c *Controller) notice(text string) {
1996 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: text})
1997 }
1998
1999 func (c *Controller) noticeDetail(text, detail string) {
2000 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: text, Detail: detail})
2001 }
2002
2003 // Run executes a turn synchronously, returning the agent's error. Used by the
2004 // headless `reasonix run` path, where the Sink renders to stdout and the caller
2005 // just needs the exit status — no TurnDone event, no cancel bookkeeping.
2006 func (c *Controller) runReady(ctx context.Context, input string) (err error) {
2007 ctx = extension.ContextWithRuntimeOwner(ctx, c.RuntimeOwner())
2008 if c.RuntimePhase() == RuntimePhaseDraining {
2009 c.emitDrainingNotice()
2010 return ErrRuntimeDraining
2011 }
2012 c.maybeSessionStart(ctx)
2013 parentSession := c.parentSessionID()
2014 ctx = agent.WithParentSession(ctx, parentSession)
2015 ctx = jobs.WithSession(ctx, parentSession)
2016 rawInput := input
2017 ctx = c.withTurnImages(ctx, rawInput)
2018 ctx = agent.WithRawUserInput(ctx, rawInput)
2019 input = c.Compose(input)
2020 // input.receive: same interception seam as the orchestrated turn — the
2021 // composed headless input crosses the extension chain before it enters
2022 // the session.
2023 input, blocked, interceptErr := c.interceptInputReceive(ctx, input)
2024 if interceptErr != nil {
2025 return interceptErr
2026 }
2027 if blocked {
2028 return nil
2029 }
2030 startMessages := c.messageCount()
2031 var marker agent.InFlightTurnMeta
2032 defer func() { c.finishInFlightTurn(startMessages, marker) }()
2033 c.beginCheckpoint(ctx, rawInput)
2034 if c.guardianSess != nil {
2035 c.guardianSess.ResetTurn()
2036 }
2037 if c.hooks.Enabled() {
2038 c.mu.Lock()
2039 c.turn++
2040 turn := c.turn
2041 c.mu.Unlock()
2042 if block, _ := c.hooks.PromptSubmit(ctx, input, turn); block {
2043 return nil
2044 }
2045 defer func() { c.hooks.StopResult(context.Background(), lastAssistantText(c.History()), turn, err) }()
2046 }
2047 marker = c.markInFlightTurn(startMessages, true)
2048 ctx = c.withTurnContext(ctx, true)
2049 ctx = c.withPlannerTurnMetadata(ctx, rawInput, false, startMessages)
2050 modelInput := c.withCapabilityRoute(ctx, input, rawInput)
2051 modelInput, ctx, err = c.prepareVisionTurn(ctx, modelInput, agent.SubagentImageCandidates(ctx))
2052 if err != nil {
2053 return err
2054 }
2055 err = c.runModelTurn(ctx, modelInput)
2056 return err
2057 }
2058
2059 // beginRotation claims the session-rotation gate. It fails if a turn is running
2060 // or another rotation is already in progress, so the caller holds exclusive
2061 // rights to swap the executor session from the check here through endRotation.
2062 // This closes the TOCTOU window that a bare `if c.running` check left open:
2063 // between that check and the actual SetSession, a turn could start and then be
2064 // yanked out from under the run loop.
2065 func (c *Controller) beginRotation() error {
2066 c.mu.Lock()
2067 defer c.mu.Unlock()
2068 if c.bodyActiveLocked() || c.finalizingLocked() {
2069 return errTurnRunningRotation
2070 }
2071 if c.maintenance != nil {
2072 return ErrMaintenanceBusy
2073 }
2074 if c.rotating {
2075 return errRotationInProgress
2076 }
2077 c.rotating = true
2078 return nil
2079 }
2080
2081 // CancelRequested reports whether Cancel has been requested for the active turn.
2082 func (c *Controller) CancelRequested() bool {
2083 c.mu.Lock()
2084 defer c.mu.Unlock()
2085 return c.cancelRequestedLocked()
2086 }
2087
2088 // PendingPrompt reports whether the current turn is blocked waiting for a user
2089 // approval, plan approval, memory approval, or ask-tool answer.
2090 func (c *Controller) PendingPrompt() bool {
2091 return len(c.promptOwner.Identities()) > 0
2092 }
2093
2094 // RuntimeStatus reports the active work owned by the foreground controller.
2095 func (c *Controller) RuntimeStatus() RuntimeStatus {
2096 snapshot := c.RuntimeStateSnapshot()
2097 _, _, _, replayAfterSeq := c.turnEventRuntimeStatus()
2098 return RuntimeStatus{
2099 Running: snapshot.Running,
2100 PendingPrompt: snapshot.PendingPrompt,
2101 BackgroundJobs: snapshot.BackgroundJobs,
2102 CancelRequested: snapshot.CancelRequested,
2103 Cancellable: snapshot.Cancellable,
2104 TurnID: snapshot.TurnID,
2105 Status: snapshot.TurnStatus,
2106 TurnEventSeq: snapshot.TurnEventSeq,
2107 ReplayAfterSeq: replayAfterSeq,
2108 }
2109 }
2110
2111 // Turn returns the current turn number (0 before the first submit).
2112 func (c *Controller) Turn() int {
2113 c.mu.Lock()
2114 defer c.mu.Unlock()
2115 return c.turn
2116 }
2117
2118 func (c *Controller) recordDecisionReceipt(pending pendingApproval, outcome string) {
2119 if c == nil || c.executor == nil || pending.reply == nil {
2120 return
2121 }
2122 kind := pending.kind
2123 if kind == "" {
2124 kind = "tool"
2125 if pending.tool == planApprovalTool {
2126 kind = "plan"
2127 }
2128 }
2129 receipt := &provider.DecisionReceipt{
2130 ID: pending.id,
2131 Kind: kind,
2132 Tool: strings.TrimSpace(pending.tool),
2133 Subject: clipUTF8(strings.TrimSpace(pending.subject), 240),
2134 Outcome: strings.TrimSpace(outcome),
2135 }
2136 // Keep the receipt bounded and provider-excluded even when an older caller
2137 // omits optional approval metadata.
2138 c.executor.Session().AddDecisionReceipt(receipt)
2139 c.sink.Emit(event.Event{
2140 Kind: event.Notice,
2141 Code: event.NoticeCodeDecisionReceipt,
2142 Level: event.LevelInfo,
2143 Text: "Decision recorded: " + receipt.Outcome,
2144 DecisionReceipt: receipt,
2145 })
2146 }
2147
2148 // EnableInteractiveApproval swaps the executor's gate for one that routes
2149 // approval decisions to the frontend via ApprovalRequest events, and wires the
2150 // controller in as the executor's Asker so the `ask` tool can question the user.
2151 // Interactive frontends (chat, desktop) call this; the headless run keeps the
2152 // silent gate and a nil asker from setup.
2153 func (c *Controller) EnableInteractiveApproval() {
2154 trustGate := planModeReadOnlyTrustApprover{c}
2155 escapeApprover := sandboxEscapeApprover{c}
2156 configApprover := managedConfigWriteApprover{c}
2157 c.writeAccess.interactive = true
2158 if c.executor != nil {
2159 c.executor.SetGate(c.newInteractiveGate())
2160 c.executor.SetPlanModeReadOnlyTrustGate(trustGate)
2161 c.executor.SetSandboxEscapeApprover(escapeApprover)
2162 c.executor.SetConfigWriteApprover(configApprover)
2163 c.executor.SetWriteAccessGate(c)
2164 c.executor.SetWriteRoots(c.writeAccess.roots)
2165 c.executor.SetPermissionPresetProvider(c.ToolApprovalMode)
2166 c.executor.SetAsker(c)
2167 c.executor.SetInteractionBroker(c)
2168 }
2169 if setter, ok := c.runner.(interface {
2170 SetPlanModeReadOnlyTrustGate(agent.PlanModeReadOnlyTrustGate)
2171 }); ok {
2172 setter.SetPlanModeReadOnlyTrustGate(trustGate)
2173 }
2174 if setter, ok := c.runner.(interface {
2175 SetSandboxEscapeApprover(sandbox.EscapeApprover)
2176 }); ok {
2177 setter.SetSandboxEscapeApprover(escapeApprover)
2178 }
2179 if setter, ok := c.runner.(interface {
2180 SetConfigWriteApprover(tool.ConfigWriteApprover)
2181 }); ok {
2182 setter.SetConfigWriteApprover(configApprover)
2183 }
2184 if setter, ok := c.runner.(interface {
2185 SetWriteAccessGate(agent.WriteAccessGate)
2186 }); ok {
2187 setter.SetWriteAccessGate(c)
2188 }
2189 if setter, ok := c.runner.(interface{ SetPermissionPresetProvider(func() string) }); ok {
2190 setter.SetPermissionPresetProvider(c.ToolApprovalMode)
2191 }
2192 if setter, ok := c.runner.(interface {
2193 SetWriteRoots(*sandbox.WritableRootSet)
2194 }); ok {
2195 setter.SetWriteRoots(c.writeAccess.roots)
2196 }
2197 if setter, ok := c.runner.(interface {
2198 SetPlannerPlanApprover(agent.PlannerPlanApprover)
2199 }); ok {
2200 setter.SetPlannerPlanApprover(plannerPlanApprover{c: c})
2201 }
2202 // The planner holds the real ask tool, so it reaches the same approval
2203 // surface the executor does instead of a parallel prose-question path.
2204 if setter, ok := c.runner.(interface{ SetAsker(agent.Asker) }); ok {
2205 setter.SetAsker(c)
2206 }
2207 if setter, ok := c.runner.(interface{ SetInteractionBroker(mcpinteraction.Broker) }); ok {
2208 setter.SetInteractionBroker(c)
2209 }
2210 }
2211
2212 type plannerPlanApprover struct {
2213 c *Controller
2214 }
2215
2216 func (p plannerPlanApprover) RunWithPlannerApproval(ctx context.Context, plan string, run func(context.Context) error) error {
2217 c := p.c
2218 allow, _, err := c.requestApprovalWithReason(ctx, planApprovalTool, "", nil, "Planner requested host approval before execution.")
2219 if err != nil {
2220 return err
2221 }
2222 if !allow {
2223 return nil
2224 }
2225 c.approval.setPlanAutoApprove(true)
2226 defer c.approval.setPlanAutoApprove(false)
2227 if err := run(ctx); err != nil {
2228 return err
2229 }
2230 return nil
2231 }
2232
2233 func (c *Controller) newInteractiveGate() *permission.Gate {
2234 policy := c.policy
2235 mode := c.approval.mode()
2236 switch mode {
2237 case ToolApprovalWorkspaceWrite, ToolApprovalDangerFullAccess:
2238 policy.Mode = permission.Allow
2239 case ToolApprovalDontAsk:
2240 policy.Mode = permission.Deny
2241 default:
2242 policy.Mode = permission.Ask
2243 }
2244 // SessionAllow must not cover fresh-human tools: it is checked before Ask,
2245 // so `--allowed-tools remember` would skip the prompt. Interactive Auto and
2246 // YOLO treat remember/forget as ordinary policy decisions; Auto still
2247 // preserves an explicit configured Ask rule, while YOLO bypasses it.
2248 policy.SessionAllow = rulesWithoutFreshHumanApproval(policy.SessionAllow)
2249 if mode != ToolApprovalWorkspaceWrite && mode != ToolApprovalDangerFullAccess {
2250 policy.Ask = append(policy.Ask,
2251 permission.Rule{Tool: memoryRememberTool},
2252 permission.Rule{Tool: memoryForgetTool},
2253 )
2254 }
2255 // The OS sandbox, rather than shell syntax heuristics, owns the write
2256 // boundary for all three presets. Explicit ask and deny rules still win.
2257 var approver permission.Approver = gateApprover{c}
2258 if mode == ToolApprovalDontAsk {
2259 approver = denyPermissionApprover{}
2260 }
2261 gate := permission.NewGate(policy, approver)
2262 gate.OnRemember = func(rule string) {
2263 if c.onRemember != nil {
2264 _ = c.onRemember(rule)
2265 }
2266 }
2267 return gate
2268 }
2269
2270 func (c *Controller) allowLowRiskRemember(args json.RawMessage) bool {
2271 mem := c.Memory()
2272 if mem != nil {
2273 if assessment := memory.AssessRememberWrite(mem.Store, args); assessment.AutoAllow {
2274 c.memory.authorizeAutoRemember(args)
2275 return true
2276 }
2277 }
2278 c.memory.revokeAutoRemember(args)
2279 return false
2280 }
2281
2282 func (c *Controller) newHeadlessGate(mode string) *freshHumanHeadlessGate {
2283 gate := BuildHeadlessApprovalGate(c.policy, mode)
2284 gate.allowLowRiskFreshAction = func(toolName string, args json.RawMessage) bool {
2285 return toolName == memoryRememberTool && c.allowLowRiskRemember(args)
2286 }
2287 return gate
2288 }
2289
2290 type denyPermissionApprover struct{}
2291
2292 func (denyPermissionApprover) Approve(context.Context, string, string, json.RawMessage) (bool, bool, error) {
2293 return false, false, nil
2294 }
2295
2296 // rulesWithoutFreshHumanApproval drops any session-allow rule that targets a
2297 // tool requiring fresh human approval, so an explicit allowlist cannot bypass
2298 // the always-prompt contract for those tools.
2299 func rulesWithoutFreshHumanApproval(rules []permission.Rule) []permission.Rule {
2300 if len(rules) == 0 {
2301 return rules
2302 }
2303 filtered := make([]permission.Rule, 0, len(rules))
2304 for _, r := range rules {
2305 if RequiresFreshHumanApprovalTool(r.Tool) {
2306 continue
2307 }
2308 filtered = append(filtered, r)
2309 }
2310 return filtered
2311 }
2312
2313 // ApplyHeadlessApprovalMode configures the executor gate for a non-interactive
2314 // (`reasonix run`) session from an explicit --permission-mode. Unlike
2315 // EnableInteractiveApproval it installs no blocking approver, asker, or
2316 // fresh-approval prompt: there is no key loop to answer them, and the default
2317 // infinite approval timeout would wedge the run forever on an Ask rule, the
2318 // `ask` tool, or a sandbox/config approval. Modes map straight onto a headless
2319 // gate, and each preserves the interactive contract as closely as a run with no
2320 // one to prompt allows:
2321 //
2322 // - auto: auto-approve the writer fallback (Mode=Allow) but PRESERVE explicit
2323 // ask rules. Interactive auto prompts on those (it never auto-approves them);
2324 // headless can't prompt, so a would-ask decision fails closed (deny) rather
2325 // than running silently. Only bypass may run such a command unattended.
2326 // - yolo/bypassPermissions: skip ordinary approval-gated decisions (nil
2327 // approver); deny rules and fresh decisions still fail closed.
2328 // - dontAsk: deny anything that would ask, and deny the writer fallback too.
2329 //
2330 // Deny rules and fresh-human tools (memory, plan, sandbox, config) stay enforced
2331 // by the gate for every mode. The only exception is a controller-assessed,
2332 // create-only project/reference memory; every other memory write remains denied.
2333 func (c *Controller) ApplyHeadlessApprovalMode(mode string) {
2334 mode = normalizeToolApprovalMode(mode)
2335 c.permissionStateMu.Lock()
2336 defer c.permissionStateMu.Unlock()
2337 c.approval.setMode(mode)
2338 if c.subagentGate != nil {
2339 c.subagentGate.Update(mode)
2340 }
2341 c.writeAccess.interactive = false
2342 if c.executor != nil {
2343 c.executor.SetGate(c.newHeadlessGate(mode))
2344 c.executor.SetWriteAccessGate(c)
2345 c.executor.SetWriteRoots(c.writeAccess.roots)
2346 c.executor.SetPermissionPresetProvider(c.ToolApprovalMode)
2347 }
2348 }
2349
2350 func (c *Controller) refreshInteractiveGate() {
2351 if c.executor != nil {
2352 c.executor.SetGate(c.newInteractiveGate())
2353 }
2354 }
2355
2356 // TrySteer queues mid-turn guidance only when the active agent turn accepts it.
2357 func (c *Controller) TrySteer(text string) bool {
2358 c.mu.Lock()
2359 exec := c.executor
2360 running := c.bodyActiveLocked()
2361 c.mu.Unlock()
2362 return running && exec != nil && exec.Steer(text)
2363 }
2364
2365 // Steer is the compatibility path for callers that cannot observe admission.
2366 // Interactive hosts should call TrySteer so a rejected steer remains in their
2367 // draft/queue and can be retried as a regular follow-up.
2368 func (c *Controller) Steer(text string) {
2369 if c.TrySteer(text) {
2370 return
2371 }
2372 // No active turn accepted the steer: the frontend's runningRef was stale,
2373 // the turn exited between our running check and the enqueue, or no
2374 // executor is bound yet. Deliver it as a regular turn instead.
2375 c.submitSteerFallback(text)
2376 }
2377
2378 // submitSteerFallback records steer text that no active turn accepted as
2379 // unapplied guidance, not as a new task. This compatibility path deliberately
2380 // never opens a provider turn: replaying stale historical guidance as the
2381 // user's current request caused unintended code changes (#7045).
2382 func (c *Controller) submitSteerFallback(text string) admissionResult {
2383 return c.runGuardedOrPark(func(context.Context) error {
2384 if c.executor != nil {
2385 c.executor.RecordUnappliedSteer(text)
2386 }
2387 return nil
2388 })
2389 }
2390
2391 // SteerConsumed returns true when the steer queue is empty after the last consume.
2392 func (c *Controller) SteerConsumed() bool {
2393 c.mu.Lock()
2394 exec := c.executor
2395 c.mu.Unlock()
2396 if exec != nil {
2397 return exec.SteerConsumed()
2398 }
2399 return true
2400 }
2401
2402 // Ask implements agent.Asker: it emits an AskRequest and blocks until
2403 // AnswerQuestion(ID, …) answers or ctx is cancelled. Multiple requests may be
2404 // outstanding; the frontend presents the shared pending list one at a time.
2405 // Unlike tool-approval gates, Ask is NOT bypassed in YOLO mode — the `ask`
2406 // tool exists to get a genuine user decision, and YOLO only auto-approves
2407 // tool calls; it must not answer the user's questions for them.
2408 func (c *Controller) Ask(ctx context.Context, questions []event.AskQuestion) ([]event.AskAnswer, error) {
2409 c.approval.promptEmitMu.Lock()
2410 id, reply := c.approval.registerAsk(questions)
2411 c.registerOwnedPrompt(id, PromptAsk)
2412 turnID, _, _, _ := c.turnEventRuntimeStatus()
2413 _, runtimeEpoch := c.promptIdentitySnapshot()
2414 if identity := c.bindOwnedPromptRouting(id, turnID, runtimeEpoch); identity.TurnID != "" {
2415 turnID = identity.TurnID
2416 }
2417 if err := event.EmitChecked(c.sink, event.Event{Kind: event.AskRequest, TurnID: turnID, ItemID: id, Ask: event.Ask{ID: id, Questions: questions, TurnID: turnID}}); err != nil {
2418 c.approval.promptEmitMu.Unlock()
2419 c.cancelOwnedPrompt(id)
2420 return nil, fmt.Errorf("persist ask request: %w", err)
2421 }
2422 c.approval.markAskEmitted(id)
2423 c.approval.promptEmitMu.Unlock()
2424
2425 waitCtx, cancelWait := c.approval.waitContext(ctx)
2426 defer cancelWait()
2427
2428 select {
2429 case ans := <-reply:
2430 return ans, nil
2431 case <-waitCtx.Done():
2432 c.cancelOwnedPrompt(id)
2433 return nil, waitCtx.Err()
2434 }
2435 }
2436
2437 // AnswerQuestion resolves a pending AskRequest by ID with the user's selections.
2438 // Unknown/expired IDs are ignored.
2439 func (c *Controller) AnswerQuestion(id string, answers []event.AskAnswer) {
2440 _ = c.AnswerQuestionChecked(id, answers)
2441 }
2442
2443 // AnswerQuestionChecked persists the prompt transition before releasing the
2444 // agent loop. A failed ledger write leaves the prompt pending and retryable.
2445 func (c *Controller) AnswerQuestionChecked(id string, answers []event.AskAnswer) error {
2446 defer c.refreshRuntimeState(event.Event{})
2447 return c.answerQuestionCheckedLocked(id, answers)
2448 }
2449
2450 func (c *Controller) answerQuestionCheckedLocked(id string, answers []event.AskAnswer) error {
2451 pending, ok, err := c.approval.resolveAskAfter(id, func(p pendingAsk) error {
2452 return c.emitTurnEventChecked(event.Event{Kind: event.PromptAnswered, ItemID: id, InteractionState: string(PromptAnswered), Status: event.TurnInProgress})
2453 })
2454 if err != nil {
2455 return err
2456 }
2457 if ok {
2458 c.promptOwner.MarkIDTerminal(id, PromptAnswered)
2459 // An answer batch with no selections is the explicit "skip and continue
2460 // chat" path. End the current turn instead of feeding a prose dismissal
2461 // back to the model and trusting it not to ask again (#6869).
2462 if !askAnswersHaveSelection(answers) {
2463 c.mu.Lock()
2464 activeTurn := c.turns.cancel != nil
2465 c.mu.Unlock()
2466 if activeTurn {
2467 c.cancelLocked()
2468 return nil
2469 }
2470 }
2471 c.recordAskDecisionReceipt(id, pending, answers)
2472 pending.reply <- answers // buffered, never blocks
2473 }
2474 return nil
2475 }
2476
2477 func (c *Controller) recordAskDecisionReceipt(id string, pending pendingAsk, answers []event.AskAnswer) {
2478 if c == nil || c.executor == nil {
2479 return
2480 }
2481 selected := make(map[string][]string, len(answers))
2482 for _, answer := range answers {
2483 selected[answer.QuestionID] = append([]string(nil), answer.Selected...)
2484 }
2485 parts := make([]string, 0, len(pending.questions))
2486 for _, question := range pending.questions {
2487 answer := strings.TrimSpace(strings.Join(selected[question.ID], ", "))
2488 if answer == "" {
2489 answer = "—"
2490 }
2491 prompt := strings.TrimSpace(question.Prompt)
2492 if prompt == "" {
2493 prompt = strings.TrimSpace(question.Header)
2494 }
2495 if prompt == "" {
2496 prompt = question.ID
2497 }
2498 parts = append(parts, prompt+": "+answer)
2499 }
2500 receipt := &provider.DecisionReceipt{
2501 ID: id,
2502 Kind: "ask",
2503 Subject: clipUTF8(strings.Join(parts, " · "), 240),
2504 Outcome: "answered",
2505 }
2506 c.executor.Session().AddDecisionReceipt(receipt)
2507 c.sink.Emit(event.Event{
2508 Kind: event.Notice,
2509 Code: event.NoticeCodeDecisionReceipt,
2510 Level: event.LevelInfo,
2511 Text: "Decision recorded: answered",
2512 DecisionReceipt: receipt,
2513 })
2514 }
2515
2516 func askAnswersHaveSelection(answers []event.AskAnswer) bool {
2517 for _, answer := range answers {
2518 if len(answer.Selected) > 0 {
2519 return true
2520 }
2521 }
2522 return false
2523 }
2524
2525 // ReplayPendingPrompts re-emits the ApprovalRequest / AskRequest event for every
2526 // prompt currently blocking the run loop. A frontend that reconnected or reloaded
2527 // after the original event has no way to rebuild its approval/ask modal otherwise,
2528 // so the blocked gate goroutine stays stuck forever while the session shows a
2529 // "waiting" status with no actionable prompt. All outstanding interactions
2530 // are replayed from the same registry; the frontend presents them in order.
2531 func (c *Controller) ReplayPendingPrompts() {
2532 c.approval.promptEmitMu.Lock()
2533 noApprovals := c.replayPendingPromptsTo(c.sink)
2534 c.approval.promptEmitMu.Unlock()
2535 if noApprovals {
2536 // Retained compatibility hook; live Auto Guard cards are ordinary approvals.
2537 c.ReplayUnresolvedRecoveries()
2538 }
2539 }
2540
2541 // ReplayPendingPromptsTo re-emits pending prompts to one frontend sink. Serve
2542 // uses this for a newly attached SSE client so existing browsers do not receive
2543 // duplicate approval/ask cards when another client reconnects.
2544 func (c *Controller) ReplayPendingPromptsTo(sink event.Sink) {
2545 c.approval.promptEmitMu.Lock()
2546 defer c.approval.promptEmitMu.Unlock()
2547 c.replayPendingPromptsTo(sink)
2548 }
2549
2550 // ReplayPendingPromptsWith performs an SSE connection handoff while prompt
2551 // registration and emission are paused. The factory must subscribe the new
2552 // client and return a sink that targets it; this closes the attach race where
2553 // the original prompt could otherwise land between Subscribe and replay.
2554 func (c *Controller) ReplayPendingPromptsWith(sinkFactory func() event.Sink) {
2555 if sinkFactory == nil {
2556 return
2557 }
2558 c.approval.promptEmitMu.Lock()
2559 defer c.approval.promptEmitMu.Unlock()
2560 c.replayPendingPromptsTo(sinkFactory())
2561 }
2562
2563 func (c *Controller) replayPendingPromptsTo(sink event.Sink) bool {
2564 approvals, asks := c.approval.snapshotPrompts()
2565 interactions := c.approval.snapshotMCPInteractions()
2566 c.emitPendingPrompts(sink, approvals, asks, interactions)
2567 return len(approvals) == 0
2568 }
2569
2570 func (c *Controller) emitPendingPrompts(sink event.Sink, approvals []event.Approval, asks []event.Ask, interactions []event.MCPInteraction) {
2571 if sink == nil {
2572 return
2573 }
2574 for _, a := range approvals {
2575 if identity, ok := c.promptOwner.Identity(a.ID); ok {
2576 a.TurnID = identity.TurnID
2577 }
2578 e := c.approvalRequestEvent(a)
2579 e.Replayed = true
2580 sink.Emit(e)
2581 }
2582 for _, a := range asks {
2583 if identity, ok := c.promptOwner.Identity(a.ID); ok {
2584 a.TurnID = identity.TurnID
2585 }
2586 sink.Emit(event.Event{Kind: event.AskRequest, TurnID: a.TurnID, ItemID: a.ID, Ask: a, Replayed: true})
2587 }
2588 for _, i := range interactions {
2589 if identity, ok := c.promptOwner.Identity(i.ID); ok {
2590 i.TurnID = identity.TurnID
2591 }
2592 sink.Emit(event.Event{Kind: event.MCPInteractionRequest, TurnID: i.TurnID, ItemID: i.ID, MCPInteraction: i, Replayed: true})
2593 }
2594 }
2595
2596 // SetPlanMode flips the executor's plan-first workflow flag without touching the
2597 // cache-stable system/tool prefix, and remembers the state so Compose can prepend
2598 // the plan-mode marker to outgoing user turns.
2599 func (c *Controller) SetPlanMode(v bool) {
2600 c.applyPlanMode(v)
2601 }
2602
2603 // SetAgentPreset accepts retired role inputs for compatibility. Recognized
2604 // values no longer change runtime behavior.
2605 func (c *Controller) SetAgentPreset(preset string) {
2606 if c == nil {
2607 return
2608 }
2609 if p, err := agentpreset.Normalize(preset); err == nil {
2610 _ = c.SetQualityFloor(string(p))
2611 }
2612 }
2613
2614 // AgentPreset returns the fixed compatibility label.
2615 func (c *Controller) AgentPreset() string {
2616 return string(agentpreset.Standard)
2617 }
2618
2619 // SetResponseLanguage updates the final-answer language preference for
2620 // subsequent turns.
2621 func (c *Controller) SetResponseLanguage(lang string) {
2622 mode := config.NormalizeLanguage(lang)
2623 c.mu.Lock()
2624 c.responseLanguage = mode
2625 c.mu.Unlock()
2626 if setter, ok := c.runner.(interface{ SetResponseLanguage(string) }); ok {
2627 setter.SetResponseLanguage(mode)
2628 } else if c.executor != nil {
2629 c.executor.SetResponseLanguage(mode)
2630 }
2631 }
2632
2633 // SetReasoningLanguage updates the visible reasoning language preference for
2634 // subsequent turns.
2635 func (c *Controller) SetReasoningLanguage(lang string) {
2636 mode := config.NormalizeReasoningLanguage(lang)
2637 c.mu.Lock()
2638 c.reasoningLanguage = mode
2639 c.mu.Unlock()
2640 if setter, ok := c.runner.(interface{ SetReasoningLanguage(string) }); ok {
2641 setter.SetReasoningLanguage(mode)
2642 } else if c.executor != nil {
2643 c.executor.SetReasoningLanguage(mode)
2644 }
2645 }
2646
2647 // PlanMode reports whether outgoing turns currently receive the plan-mode
2648 // marker.
2649 func (c *Controller) PlanMode() bool {
2650 c.mu.Lock()
2651 defer c.mu.Unlock()
2652 return c.sessionSettings.planMode
2653 }
2654
2655 // GoalStrict enables or disables strict goal mode. Since the structured
2656 // protocol, every complete claim is validated against host readiness and an
2657 // incomplete-todo intercept can never be overridden, so the flag is persisted
2658 // for compatibility with older frontends but no longer changes FSM behavior.
2659 func (c *Controller) GoalStrict(strict bool) {
2660 if c.sessionEngineEnabled() {
2661 return
2662 }
2663 path, data, ok := c.goals.setStrict(strict)
2664 c.persistGoalState(path, data, ok)
2665 }
2666
2667 // SetGoal stores a session-scoped active goal. Compose injects it into outgoing
2668 // user turns, not the system prompt or tool schema, so it does not disturb the
2669 // cache-stable prefix.
2670 func (c *Controller) SetGoal(goal string) {
2671 c.SetGoalWithResearchMode(goal, GoalResearchAuto)
2672 }
2673
2674 // LoadInactiveGoal restores a legacy metadata-only objective without starting
2675 // execution or writing a sidecar during read-only history access.
2676 func (c *Controller) LoadInactiveGoal(goal string) {
2677 c.goals.mu.Lock()
2678 defer c.goals.mu.Unlock()
2679 c.goals.installGoalLocked(strings.TrimSpace(goal), ClassifyGoalBudget(goal))
2680 c.goals.disarmed = true
2681 }
2682
2683 // SetGoalDurable updates the Goal only when its sidecar can be replaced
2684 // atomically.
2685 func (c *Controller) SetGoalDurable(goal string) error {
2686 if c.sessionEngineEnabled() {
2687 goal = strings.TrimSpace(goal)
2688 current, err := c.goalLifecycleView()
2689 if err != nil {
2690 return err
2691 }
2692 if goal == "" {
2693 if current == nil {
2694 return nil
2695 }
2696 _, err = c.applyHostGoalMutation(context.Background(), "clear", func(machine *goaldomain.Machine) (*goaldomain.View, error) {
2697 if clearErr := machine.Clear(current.Ref()); clearErr != nil {
2698 return nil, clearErr
2699 }
2700 return nil, nil
2701 })
2702 if err == nil {
2703 c.resetGoalResourceBudget()
2704 }
2705 return err
2706 }
2707 if current != nil && current.Objective == goal && current.Phase == goaldomain.PhaseActive && current.Activation == goaldomain.ActivationArmed {
2708 return nil
2709 }
2710 _, err = c.applyHostGoalMutation(context.Background(), "set", func(machine *goaldomain.Machine) (*goaldomain.View, error) {
2711 created, createErr := machine.Replace(goaldomain.CreateRequest{Objective: goal})
2712 return &created, createErr
2713 })
2714 if err == nil {
2715 c.resetGoalResourceBudget()
2716 }
2717 return err
2718 }
2719 snapshot := c.goals.capture()
2720 legacySnapshot, hadLegacySnapshot := c.legacyRestoreSnapshot()
2721 resolved, setup := c.resolveGoalText(goal, GoalResearchAuto)
2722 var path string
2723 var data []byte
2724 var persist bool
2725 if setup.blockReason != "" {
2726 path, data, persist = c.goals.setLegacyArchiveBlockedWithTaskID(resolved, setup.budgetClass, setup.blockReason, setup.legacyTaskID)
2727 c.replaceLegacyRestore(legacyGoalRestore{taskID: setup.legacyTaskID, epoch: c.goals.continuationToken(), explicit: setup.explicit})
2728 } else {
2729 path, data, persist = c.goals.set(resolved, setup.budgetClass)
2730 c.replaceLegacyRestore(legacyGoalRestore{})
2731 }
2732 if persist {
2733 if err := c.goals.writeStateErr(path, data); err != nil {
2734 c.goals.restore(snapshot)
2735 if hadLegacySnapshot {
2736 legacySnapshot.epoch = c.goals.continuationToken()
2737 c.replaceLegacyRestore(legacySnapshot)
2738 } else {
2739 c.replaceLegacyRestore(legacyGoalRestore{})
2740 }
2741 return err
2742 }
2743 }
2744 if setup.notice != "" {
2745 c.notice(setup.notice)
2746 }
2747 if setup.blockReason != "" {
2748 c.notice("legacy research archive resume failed: " + setup.blockReason)
2749 }
2750 return nil
2751 }
2752
2753 func (c *Controller) SetGoalWithResearchMode(goal string, researchMode GoalResearchMode) {
2754 if c.sessionEngineEnabled() {
2755 if err := c.SetGoalDurable(goal); err != nil {
2756 c.notice("goal: " + err.Error())
2757 }
2758 return
2759 }
2760 resolved, setup := c.resolveGoalText(goal, researchMode)
2761 if setup.notice != "" {
2762 c.notice(setup.notice)
2763 }
2764 var path string
2765 var data []byte
2766 var ok bool
2767 if setup.blockReason != "" {
2768 path, data, ok = c.goals.setLegacyArchiveBlockedWithTaskID(resolved, setup.budgetClass, setup.blockReason, setup.legacyTaskID)
2769 c.replaceLegacyRestore(legacyGoalRestore{taskID: setup.legacyTaskID, epoch: c.goals.continuationToken(), explicit: setup.explicit})
2770 c.notice("legacy research archive resume failed: " + setup.blockReason)
2771 } else {
2772 path, data, ok = c.goals.set(resolved, setup.budgetClass)
2773 c.replaceLegacyRestore(legacyGoalRestore{})
2774 }
2775 c.persistGoalState(path, data, ok)
2776 }
2777
2778 // goalSetSetup is the resolved objective and budget class after archive lookup.
2779 type goalSetSetup struct {
2780 budgetClass string
2781 notice string
2782 blockReason string
2783 legacyTaskID string
2784 explicit bool
2785 }
2786
2787 func (c *Controller) resolveGoalText(goal string, researchMode GoalResearchMode) (string, goalSetSetup) {
2788 setup := goalSetSetup{budgetClass: budgetClassForLegacyMode(goal, researchMode)}
2789 legacy := c.prepareLegacyResearchTask(goal)
2790 if !legacy.explicit {
2791 return goal, setup
2792 }
2793 setup.notice, setup.blockReason, setup.legacyTaskID, setup.explicit = legacy.notice, legacy.blockReason, legacy.taskID, legacy.explicit
2794 if legacy.blockReason != "" {
2795 return goal, setup
2796 }
2797 setup.budgetClass = budgetClassResearch
2798 return legacy.goal, setup
2799 }
2800
2801 // ResumeGoal re-enters a recoverable blocked/stopped Goal without resetting its
2802 // delivery evidence scope or accumulated usage statistics.
2803 func (c *Controller) ResumeGoal() bool {
2804 if c.sessionEngineEnabled() {
2805 current, err := c.goalLifecycleView()
2806 if err != nil || current == nil {
2807 return false
2808 }
2809 _, err = c.applyHostGoalMutation(context.Background(), "resume", func(machine *goaldomain.Machine) (*goaldomain.View, error) {
2810 resumed, resumeErr := machine.Resume(current.Ref(), true)
2811 return &resumed, resumeErr
2812 })
2813 if err != nil {
2814 return false
2815 }
2816 if current.BlockedReason != nil && current.BlockedReason.Code == "resource-budget" && c.goalTokenBudget > 0 {
2817 c.goalResourceMu.Lock()
2818 c.goalTokenLimit += c.goalTokenBudget
2819 c.goalBudgetExtensions++
2820 c.goalResourceMu.Unlock()
2821 }
2822 c.kickGoalDriver()
2823 return true
2824 }
2825 if handled, resumed := c.retryBlockedLegacyGoal(); handled {
2826 return resumed
2827 }
2828 spentBudget := c.goals.runtimeView().StopCause == stopCauseBudgetSpend
2829 path, data, persist, resumed := c.goals.resume()
2830 if !resumed {
2831 return false
2832 }
2833 c.persistGoalState(path, data, persist)
2834 if c.executor != nil {
2835 if spentBudget {
2836 c.executor.ResetTaskBudget()
2837 }
2838 c.executor.RestoreDeliveryCheckpoint(c.goals.deliveryState())
2839 }
2840 return true
2841 }
2842
2843 // PauseGoal suspends a running Goal without losing its Delivery checkpoint or
2844 // runtime history; ResumeGoal restores it. Returns false when no
2845 // running Goal exists.
2846 func (c *Controller) PauseGoal() bool {
2847 if c.sessionEngineEnabled() {
2848 current, err := c.goalLifecycleView()
2849 if err != nil || current == nil || current.Phase != goaldomain.PhaseActive {
2850 return false
2851 }
2852 // Revoke automatic execution before persistence or cancellation can block.
2853 c.disarmGoalLifecycle("user-paused")
2854 _, err = c.applyHostGoalMutation(context.Background(), "pause", func(machine *goaldomain.Machine) (*goaldomain.View, error) {
2855 paused, pauseErr := machine.Pause(current.Ref())
2856 return &paused, pauseErr
2857 })
2858 if err != nil {
2859 return false
2860 }
2861 c.goalDriverMu.Lock()
2862 activeGoalRound := c.goalDriverActive != nil
2863 c.goalDriverMu.Unlock()
2864 if activeGoalRound {
2865 c.Cancel()
2866 }
2867 c.notice(i18n.M.GoalPaused)
2868 return true
2869 }
2870 if !c.goals.active() {
2871 return false
2872 }
2873 path, data, ok := c.goals.pauseFor(stopCauseManual, i18n.M.GoalPausedReason)
2874 c.persistGoalState(path, data, ok)
2875 c.notice(i18n.M.GoalPaused)
2876 return true
2877 }
2878
2879 // GoalRuntime returns the active Goal's usage/runtime summary for frontends.
2880 func (c *Controller) GoalRuntime() GoalRuntimeView {
2881 if c.sessionEngineEnabled() {
2882 view, _ := c.goalLifecycleView()
2883 if view == nil {
2884 return GoalRuntimeView{}
2885 }
2886 limit := 0
2887 if view.MaxGoalRounds != nil {
2888 limit = int(*view.MaxGoalRounds)
2889 }
2890 c.goalResourceMu.Lock()
2891 used, requests, tokenLimit, extensions := c.goalTokensUsed, c.goalRequestsUsed, c.goalTokenLimit, c.goalBudgetExtensions
2892 c.goalResourceMu.Unlock()
2893 return GoalRuntimeView{TurnsUsed: int(view.RoundsStarted), TurnsLimit: limit, TokensUsed: used,
2894 RequestsUsed: requests, WorkDurationMs: view.WorkDurationMs, TokensLimit: tokenLimit, StopCause: view.StopReason, BudgetExtensions: extensions}
2895 }
2896 return c.goals.runtimeView()
2897 }
2898
2899 func (c *Controller) ClearGoal() {
2900 if c.sessionEngineEnabled() {
2901 c.disarmGoalLifecycle("cleared")
2902 _ = c.SetGoalDurable("")
2903 c.goalDriverMu.Lock()
2904 activeGoalRound := c.goalDriverActive != nil
2905 c.goalDriverMu.Unlock()
2906 if activeGoalRound {
2907 c.Cancel()
2908 }
2909 return
2910 }
2911 c.SetGoal("")
2912 }
2913
2914 func (c *Controller) Goal() string {
2915 if c.sessionEngineEnabled() {
2916 view, _ := c.goalLifecycleView()
2917 if view == nil {
2918 return ""
2919 }
2920 return view.Objective
2921 }
2922 return c.goals.goalText()
2923 }
2924
2925 func (c *Controller) GoalStatus() string {
2926 if c.sessionEngineEnabled() {
2927 view, err := c.goalLifecycleView()
2928 if err != nil || view == nil {
2929 return GoalStatusStopped
2930 }
2931 switch view.Phase {
2932 case goaldomain.PhaseComplete:
2933 return GoalStatusComplete
2934 case goaldomain.PhaseBlocked:
2935 return GoalStatusBlocked
2936 case goaldomain.PhaseActive:
2937 if view.Activation == goaldomain.ActivationArmed {
2938 return GoalStatusRunning
2939 }
2940 }
2941 return GoalStatusStopped
2942 }
2943 return c.goals.statusForDisplay()
2944 }
2945
2946 // Compact runs one compaction pass on the executor's session on demand.
2947 // instructions is optional `/compact <focus>` guidance steering what to keep.
2948 func (c *Controller) Compact(ctx context.Context, instructions string) error {
2949 ctx = c.withAuthentication(ctx)
2950 if err := c.authentication.admissionError(); err != nil {
2951 return err
2952 }
2953 if c.executor == nil {
2954 return nil
2955 }
2956 op, runCtx, err := c.beginMaintenance(ctx, "compact")
2957 if err != nil {
2958 return err
2959 }
2960 return c.executeMaintenance(op, runCtx, func(work context.Context) error {
2961 return c.executor.CompactNow(work, instructions)
2962 })
2963 }
2964
2965 // maybeSessionStart fires the SessionStart hook exactly once per session, lazily
2966 // on the first turn — by then the sink/notify is wired, and a resumed session
2967 // fires it too (its first post-resume turn).
2968 func (c *Controller) maybeSessionStart(ctx context.Context) {
2969 c.hooks.SetSessionID(c.parentSessionID())
2970 c.mu.Lock()
2971 if c.startedOnce {
2972 c.mu.Unlock()
2973 return
2974 }
2975 c.startedOnce = true
2976 c.mu.Unlock()
2977 c.enqueueHookContexts(c.hooks.SessionStart(ctx))
2978 c.extensionSessionEvent(extension.PointSessionStart, dispatch.PhaseStart, c.SessionPath())
2979 }
2980
2981 // NewSession snapshots the current conversation, rotates to a fresh file, and
2982 // resets the executor to a clean session carrying the same base system prompt.
2983 // Session-owned pinned context intentionally starts empty. It ends the old
2984 // session and starts the new one for lifecycle hooks.
2985 func (c *Controller) NewSession() error {
2986 if c.executor == nil {
2987 return nil
2988 }
2989 // Claim the rotation gate for the whole snapshot-then-swap sequence. A bare
2990 // `if c.running` check released before Snapshot() left a window where a turn
2991 // could start during the snapshot and then have its live session replaced by
2992 // the SetSession below. Submit ("/new") and the bot gateway call this
2993 // asynchronously, so the gate is load-bearing, not defensive.
2994 if err := c.beginRotation(); err != nil {
2995 return err
2996 }
2997 defer c.endRotation()
2998 if c.NativeLegacySession() && c.SessionService() != nil {
2999 oldPath := c.SessionPath()
3000 c.flushRecoveryPersistence(oldPath)
3001 if err := c.Snapshot(); err != nil {
3002 return err
3003 }
3004 if err := c.extensionSessionPhase(context.Background(), extension.PointSessionRotate, dispatch.PhaseRotate, oldPath); err != nil {
3005 return err
3006 }
3007 c.hooks.SessionEnd(context.Background(), "new")
3008 c.extensionSessionEvent(extension.PointSessionEnd, dispatch.PhaseEnd, oldPath)
3009 plan := SessionRotationPlan{}
3010 if c.onSessionRotation != nil {
3011 var err error
3012 plan, err = c.onSessionRotation(context.Background(), SessionRotationRequest{SourcePath: c.SessionPath(), Reason: "new"})
3013 if err != nil {
3014 return err
3015 }
3016 }
3017 ref, err := c.bindFreshSessionWithCommit(context.Background(), plan.CreateOptions, plan.Commit)
3018 if err == nil {
3019 c.startExclusiveSession(ref, "new")
3020 }
3021 return err
3022 }
3023 if c.sessionEngineEnabled() {
3024 return c.rotateExclusiveSession(false)
3025 }
3026 // Retire asynchronous recovery writes before Snapshot publishes the final
3027 // old-session checkpoint. Otherwise an earlier write can outlive the path
3028 // rotation (or process teardown) and race cleanup of the old session.
3029 oldPath := c.SessionPath()
3030 c.flushRecoveryPersistence(oldPath)
3031 if err := c.Snapshot(); err != nil {
3032 return err
3033 }
3034 // session.rotate: the session_policy owner rules on the rotation before
3035 // anything is torn down, so its failure (required-class) aborts the
3036 // rotation cleanly. SessionPath is the file being rotated away from; the
3037 // fresh path arrives with the session.start event below.
3038 if err := c.extensionSessionPhase(context.Background(), extension.PointSessionRotate, dispatch.PhaseRotate, oldPath); err != nil {
3039 return err
3040 }
3041 c.hooks.SessionEnd(context.Background(), "clear")
3042 c.extensionSessionEvent(extension.PointSessionEnd, dispatch.PhaseEnd, oldPath)
3043 freshPath := oldPath
3044 if c.sessionDir != "" {
3045 freshPath = agent.NewSessionPath(c.sessionDir, c.label)
3046 }
3047 freshSession := agent.NewSession(c.basePrompt())
3048 commitTransition, err := c.prepareSessionTransition(freshPath, "new", freshSession)
3049 if err != nil {
3050 return fmt.Errorf("bind new session: %w", err)
3051 }
3052 // Hold snapshotMu across the swap so an in-flight save cannot pair the old
3053 // path with the fresh session (or the fresh path with the old session).
3054 c.snapshotMu.Lock()
3055 commitTransition.publish()
3056 c.bindExecutorProjection(c.SessionPath(), false)
3057 if c.guardianSess != nil {
3058 c.guardianSess.Reset()
3059 }
3060 c.ResetPlannerSession()
3061 c.rebindCheckpoints(freshPath)
3062 seedErr := c.seedSessionEventsFromExecutor("session-new")
3063 c.resetRecoveryForNewSession(freshPath)
3064 c.rotateSessionTemp()
3065 c.snapshotMu.Unlock()
3066 // Old session keeps its inbox (paused); the fresh session starts empty.
3067 c.pauseInboxOnRotate()
3068 c.rebindInbox()
3069 // A new session starts with no active goal: without this, a running goal's
3070 // text kept injecting into the fresh session's first turns. The old
3071 // session's goal-state sidecar was persisted before the rotation and stays
3072 // intact, so resuming it restores its goal; the cleared state below lands
3073 // on the NEW path (rebindCheckpoints just moved it).
3074 c.ClearGoal()
3075 c.mu.Lock()
3076 c.startedOnce = true // NewSession fires SessionStart itself; don't re-fire on the next turn
3077 c.mu.Unlock()
3078 c.hooks.SetSessionID(c.parentSessionID())
3079 c.enqueueHookContexts(c.hooks.SessionStart(context.Background(), "clear"))
3080 c.extensionSessionEvent(extension.PointSessionStart, dispatch.PhaseStart, c.SessionPath())
3081 c.clearSessionWriteAccess()
3082 if seedErr != nil {
3083 return fmt.Errorf("seed new session events: %w", seedErr)
3084 }
3085 return nil
3086 }
3087
3088 func (c *Controller) hasUnfinishedSessionJobs(sessionPath string) bool {
3089 if c.jobs == nil {
3090 return false
3091 }
3092 return c.jobs.HasUnfinishedForSession(agent.BranchID(sessionPath))
3093 }
3094
3095 func removeSessionArtifacts(path string) error {
3096 if path == "" {
3097 return nil
3098 }
3099 if err := jobs.RemoveArtifacts(path); err != nil {
3100 return err
3101 }
3102 remove := []string{path}
3103 // Sidecars include the event log — the authoritative transcript. Leaving
3104 // it behind would both leak the cleared conversation and let LoadSession
3105 // resurrect it on the recycled path. The guardian transcript saves through
3106 // the same session layer, so its sidecars are swept too.
3107 remove = append(remove, store.SessionSidecarFiles(path)...)
3108 remove = append(remove, guardian.PathFor(path), guardian.CursorPathFor(path))
3109 remove = append(remove, store.SessionSidecarFiles(guardian.PathFor(path))...)
3110 for _, p := range remove {
3111 if p == "" {
3112 continue
3113 }
3114 if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
3115 return err
3116 }
3117 }
3118 if err := sessioninbox.RemoveDir(path); err != nil && !os.IsNotExist(err) {
3119 return err
3120 }
3121 if dir := ckptDir(path); dir != "" {
3122 if err := os.RemoveAll(dir); err != nil && !os.IsNotExist(err) {
3123 return err
3124 }
3125 }
3126 if err := agent.DeleteSubagentsByParent(filepath.Dir(path), agent.BranchID(path)); err != nil {
3127 return err
3128 }
3129 if err := agent.ClearCleanupPending(path); err != nil {
3130 return err
3131 }
3132 return nil
3133 }
3134
3135 // RemoveSessionArtifacts removes a transcript and every durable artifact owned
3136 // by it. Remote runtimes use this when a newly-created fork fails before it can
3137 // be registered as a live session.
3138 func RemoveSessionArtifacts(path string) error {
3139 return removeSessionArtifacts(path)
3140 }
3141
3142 // ReconcileCleanupPending retries physical cleanup for logically removed
3143 // sessions that were left behind by a previous process.
3144 func ReconcileCleanupPending(dir string) error {
3145 return agent.ReconcileCleanupPending(dir, func(item agent.CleanupPendingInfo) error {
3146 return removeSessionArtifacts(item.SessionPath)
3147 })
3148 }
3149
3150 // RewindScope selects what a Rewind restores.
3151 type RewindScope int
3152
3153 const (
3154 RewindCode RewindScope = iota // files only
3155 RewindConversation // message log only
3156 RewindBoth // both
3157 )
3158
3159 // Checkpoints lists the session's rewind points (one per user turn), oldest first.
3160 //
3161 // Each Meta.Prompt is reduced to what the user typed. A checkpoint opens with
3162 // the composed turn, so the stored prompt can carry the plan-mode marker and
3163 // transient blocks; every consumer of this list is a label (the rewind picker,
3164 // the desktop change list, the workbench projection) and the picker also
3165 // restores the prompt into the composer, so composed text must not reach them.
3166 // Stripping on read rather than only on write keeps checkpoints already on disk
3167 // readable — they were recorded composed.
3168 func (c *Controller) Checkpoints() []checkpoint.Meta {
3169 metas := c.checkpoints.list()
3170 for i := range metas {
3171 metas[i].Prompt = StripComposePrefixes(metas[i].Prompt)
3172 }
3173 return metas
3174 }
3175
3176 func (c *Controller) CheckpointFileState(path string) (checkpoint.FileState, bool) {
3177 return c.checkpoints.fileState(path)
3178 }
3179
3180 func (c *Controller) CheckpointTurnsByMessageIndex() map[int]int {
3181 return c.checkpoints.turnsByMessageIndex()
3182 }
3183
3184 // rewindFail emits the error as a Warn notice (so a frontend that swallows the
3185 // returned error — e.g. the desktop bridge's .catch — still shows the user why
3186 // the rewind did nothing) and returns it.
3187 func (c *Controller) rewindFail(err error) error {
3188 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: err.Error()})
3189 return err
3190 }
3191
3192 // Rewind is implemented in rewind.go (transactional conversation+file restore).
3193
3194 // SummarizeFrom and SummarizeUpTo preserve the historical turn-index API while
3195 // changing only the model-visible context projection. The canonical transcript
3196 // and checkpoint boundaries remain available for rewind, undo, and fork.
3197 func (c *Controller) SummarizeFrom(ctx context.Context, turn int) error {
3198 return c.summarizeAt(ctx, turn, true)
3199 }
3200
3201 func (c *Controller) SummarizeUpTo(ctx context.Context, turn int) error {
3202 return c.summarizeAt(ctx, turn, false)
3203 }
3204
3205 func (c *Controller) summarizeAt(ctx context.Context, turn int, from bool) error {
3206 ctx = c.withAuthentication(ctx)
3207 if err := c.authentication.admissionError(); err != nil {
3208 return err
3209 }
3210 if c.executor == nil {
3211 return c.rewindFail(fmt.Errorf("checkpoints unavailable"))
3212 }
3213 kind := "summarize_up_to"
3214 if from {
3215 kind = "summarize_from"
3216 }
3217 op, runCtx, err := c.beginMaintenance(ctx, kind)
3218 if err != nil {
3219 return c.rewindFail(err)
3220 }
3221 boundary, hasBound := c.checkpoints.boundary(turn)
3222 if !hasBound {
3223 err = fmt.Errorf("summarize unavailable for turn %d (resumed session)", turn)
3224 _ = c.executeMaintenance(op, runCtx, func(context.Context) error { return err })
3225 return c.rewindFail(err)
3226 }
3227 err = c.executeMaintenance(op, runCtx, func(work context.Context) error {
3228 if from {
3229 return c.executor.SummarizeFrom(work, boundary)
3230 }
3231 return c.executor.SummarizeUpTo(work, boundary)
3232 })
3233 if err != nil {
3234 return c.rewindFail(err)
3235 }
3236 return nil
3237 }
3238
3239 // Resume seeds the session from a loaded transcript and pins the active file to
3240 // its path so auto-save keeps appending there.
3241 //
3242 // When the controller already has a different non-empty session path, Resume
3243 // rotates the private temporary generation so the loaded conversation cannot
3244 // see the previous session's temporary files. Same-path Resume (hot rebuild
3245 // migration via AdoptHistory) keeps the generation.
3246 func (c *Controller) Resume(s *agent.Session, path string) {
3247 if c.NativeLegacySession() && strings.TrimSpace(path) != "" {
3248 if service := c.SessionService(); service != nil {
3249 ref, found, err := service.ExistingCanonicalForLegacy(path, s)
3250 if err != nil {
3251 c.failTurnEventLedger(err)
3252 return
3253 }
3254 if found {
3255 if _, err := c.OpenSession(context.Background(), ref); err != nil {
3256 c.failTurnEventLedger(err)
3257 }
3258 return
3259 }
3260 }
3261 }
3262 if c.sessionEngineEnabled() {
3263 if _, runtime, _ := c.v3Binding(); runtime != nil && strings.TrimSpace(path) == "" {
3264 c.restoreExecutorFromSessionEvents()
3265 return
3266 }
3267 if strings.TrimSpace(path) == "" {
3268 if _, err := c.BindFreshSession(context.Background(), ""); err != nil {
3269 c.failTurnEventLedger(err)
3270 }
3271 return
3272 }
3273 if _, statErr := os.Stat(path); os.IsNotExist(statErr) {
3274 if _, err := c.BindFreshSession(context.Background(), ""); err != nil {
3275 c.failTurnEventLedger(err)
3276 return
3277 }
3278 if s != nil && len(s.Snapshot()) > 0 {
3279 if err := c.replaceSessionEventProjection(context.Background(), "fresh-resume", s.Snapshot()); err != nil {
3280 c.failTurnEventLedger(err)
3281 } else {
3282 c.restoreExecutorFromSessionEvents()
3283 }
3284 }
3285 return
3286 }
3287 if err := c.ResumeNativeSession(s, path); err != nil {
3288 slog.Warn("controller: resume native legacy session", "path", path, "err", err)
3289 c.failTurnEventLedger(err)
3290 }
3291 return
3292 }
3293 // See snapshotMu: the swap must not interleave with an in-flight save.
3294 // recoverInterruptedTurn and maybeColdResumePrune snapshot on their own,
3295 // so they stay outside the locked section (snapshotMu is not reentrant).
3296 prevPath := c.SessionPath()
3297 c.snapshotMu.Lock()
3298 if c.executor != nil {
3299 c.executor.SetSession(s)
3300 }
3301 c.mu.Lock()
3302 c.sessionPath = path
3303 c.guardianPath = guardian.PathFor(path)
3304 c.mu.Unlock()
3305 c.bindExecutorProjection(path, true)
3306 c.ResetPlannerSession()
3307 c.setActiveJobSession(path)
3308 c.rebindCheckpoints(path)
3309 if err := c.seedSessionEventsFromExecutor("legacy-resume"); err != nil {
3310 slog.Warn("controller: import resumed transcript into v3", "err", err)
3311 }
3312 if err := c.importLegacyResumeOverPlaceholder(s); err != nil {
3313 slog.Warn("controller: replace placeholder v3 history from legacy resume", "err", err)
3314 }
3315 if err := c.adoptResumeSystemPrompt(s); err != nil {
3316 slog.Warn("controller: record refreshed system prompt in v3", "err", err)
3317 }
3318 // A host-managed replacement is deliberately unbound until its final lease
3319 // handoff. Keep the exact carried transcript on that private candidate; the
3320 // successful BindSessionWriteAuthority call publishes it to the shared v3
3321 // projection. Restoring the currently-active projection here would erase the
3322 // carried tail before the candidate had any chance to become authoritative.
3323 if c.sessionEventCommitAllowed() {
3324 c.restoreExecutorFromSessionEvents()
3325 }
3326 migPath, migData, migrated, legacy := c.goals.restoreFromState(path)
3327 if !c.restorePendingLegacyGoal(legacy) && migrated {
3328 c.persistGoalState(migPath, migData, true)
3329 }
3330 if c.executor != nil {
3331 c.executor.RestoreDeliveryCheckpoint(c.goals.deliveryState())
3332 }
3333 c.loadGuardianSession()
3334 c.loadRecoveryState(path)
3335 if shouldRotateSessionTempOnResume(prevPath, path) {
3336 c.rotateSessionTemp()
3337 }
3338 c.snapshotMu.Unlock()
3339 c.rebindInbox()
3340 c.recoverCheckpointTransactions()
3341 c.recoverInterruptedTurn(path)
3342 c.maybeColdResumePrune(path)
3343 // session.load: Resume has no failure channel, so the session_policy
3344 // strategy is advisory this stage — a required-class failure is surfaced
3345 // as a warning and the load stands. The event still carries the final
3346 // (possibly owner-adjusted) phase payload.
3347 if err := c.extensionSessionPhase(context.Background(), extension.PointSessionLoad, dispatch.PhaseLoad, path); err != nil {
3348 c.extensionWarn("session policy failed at session.load", err)
3349 }
3350 }
3351
3352 func shouldRotateSessionTempOnResume(prevPath, nextPath string) bool {
3353 prevPath = strings.TrimSpace(prevPath)
3354 nextPath = strings.TrimSpace(nextPath)
3355 if prevPath == "" || nextPath == "" {
3356 return false
3357 }
3358 return filepath.Clean(prevPath) != filepath.Clean(nextPath)
3359 }
3360
3361 func (c *Controller) loadGuardianSession() {
3362 if c.guardianSess == nil {
3363 return
3364 }
3365 c.guardianSess.Reset()
3366 path := c.guardianPath
3367 if path == "" {
3368 return
3369 }
3370 if err := c.guardianSess.Load(path); err != nil && !os.IsNotExist(err) {
3371 slog.Warn("controller: load guardian session", "err", err)
3372 }
3373 }
3374
3375 // ResetPlannerSession clears the planner's conversation history so the next
3376 // plan starts fresh. In dual-model (Plan+Execute) mode, this prevents stale
3377 // planner output from a previous session or tab from contaminating the current
3378 // executor's handoff. Safe to call on a single-model controller (no-op).
3379 func (c *Controller) ResetPlannerSession() {
3380 runner, ok := c.runner.(plannerSessionResetter)
3381 if ok {
3382 runner.ResetPlannerSession()
3383 }
3384 }
3385
3386 // cacheColdAfter resolves how long the active provider keeps a prompt prefix
3387 // cached. A session idle longer than this resumes against a cold cache, so a
3388 // history rewrite at that moment costs no extra cache misses — it only shrinks
3389 // the full-price first request. The TTL is vendor-aware: DeepSeek/unknown
3390 // 24h (legacy default deliberately preserved), DashScope 5m, Anthropic 5m.
3391 // Users can override per-provider
3392 // with cache_ttl_minutes in config.toml.
3393 func (c *Controller) cacheColdAfter() time.Duration {
3394 if c.testCacheColdAfter != 0 {
3395 if c.testCacheColdAfter == -1 {
3396 return 0
3397 }
3398 return c.testCacheColdAfter
3399 }
3400 // 查询路径只读:LoadForRootReadOnly 不触发配置迁移写盘(评审 #7168
3401 // 第 4 点);失败时保守回退 24h(DeepSeek/未知 vendor 默认),避免
3402 // 把 cache TTL 过期误当成历史改写信号(resume 只记录 warm/cold/unknown)。
3403 cfg, err := config.LoadForRootReadOnly(c.workspaceRoot)
3404 if err != nil {
3405 return 24 * time.Hour
3406 }
3407 ref := c.selection.ref
3408 if ref == "" {
3409 ref = cfg.DefaultModel
3410 }
3411 entry, ok := cfg.ResolveModel(ref)
3412 if !ok {
3413 return 24 * time.Hour
3414 }
3415 return entry.EffectiveCacheTTL()
3416 }
3417
3418 // Snapshot writes the executor's conversation to the active session file. No-op
3419 // when the executor is absent or the session has never been used (no user
3420 // interaction). Returns errNoSessionPath when there IS content but no resolved
3421 // path, so a misconfigured deployment surfaces instead of dropping data.
3422 // Called after every turn so a crash loses at most one in-flight prompt.
3423 func (c *Controller) Snapshot() error {
3424 return c.snapshot(false, false, false)
3425 }
3426
3427 // SnapshotForShutdown performs the final session snapshot. Only when the
3428 // compatibility file lock stays held for the full bounded wait does it fall
3429 // back: a schema-2 log takes the unsaved tail without the lock, a schema-1
3430 // session gets a distinct recovery branch. Other snapshot errors retain their
3431 // normal behavior and remain visible to the caller.
3432 func (c *Controller) SnapshotForShutdown() error {
3433 return c.snapshot(false, false, true)
3434 }
3435
3436 // SnapshotActivity writes the active conversation and marks the session as
3437 // recently active. Use it only after a real user/model turn changes the
3438 // transcript; switch/close snapshots should call Snapshot so they do not reorder
3439 // recent-session pickers.
3440 func (c *Controller) SnapshotActivity() error {
3441 return c.snapshot(true, false, false)
3442 }
3443
3444 // SnapshotRewrite persists an intentional history rewrite, such as rewind or
3445 // manual compaction. Ordinary autosave paths should use Snapshot so stale
3446 // controllers cannot overwrite a newer transcript.
3447 func (c *Controller) SnapshotRewrite() error {
3448 return c.snapshot(false, true, false)
3449 }
3450
3451 func (c *Controller) snapshot(markActivity, forceRewrite, shutdownRecovery bool) error {
3452 _, err := c.snapshotWithDurability(markActivity, forceRewrite, shutdownRecovery)
3453 return err
3454 }
3455
3456 // snapshotWithDurability reports whether the canonical transcript reached disk
3457 // even when a later sidecar update failed. Callers that guard a crash marker
3458 // need this distinction: a metadata error must not make a complete transcript
3459 // look like an in-memory-only turn.
3460 func (c *Controller) snapshotWithDurability(markActivity, forceRewrite, shutdownRecovery bool) (bool, error) {
3461 c.snapshotMu.Lock()
3462 defer c.snapshotMu.Unlock()
3463
3464 c.mu.Lock()
3465 path := c.sessionPath
3466 modelRef := c.selection.ref
3467 c.mu.Unlock()
3468 if c.executor == nil {
3469 return false, nil
3470 }
3471 s := c.executor.Session()
3472 if !s.HasContent() {
3473 // Nothing to persist yet (e.g. a fresh session with only a system
3474 // prompt) — staying quiet here is correct, not a data-loss path.
3475 return false, nil
3476 }
3477 if !s.HasSystemMessage() {
3478 // The session has user/assistant/tool messages but no leading system
3479 // prompt. Persisting it would create a session file that, when
3480 // reloaded, has no agent-identity contract — the model falls back to
3481 // its training-data defaults, giving wrong answers to identity
3482 // queries ("who are you?"). Log the anomaly so the root cause
3483 // (typically an empty sysPrompt reaching NewSession) can be
3484 // diagnosed, then refuse to write a corrupted transcript.
3485 slog.Warn("controller: refusing to snapshot session with content but no system message",
3486 "label", c.Label(), "session_dir", c.SessionDir(), "message_count", len(s.Snapshot()))
3487 return false, nil
3488 }
3489 if c.sessionEngineEnabled() {
3490 if _, runtime, _ := c.v3Binding(); runtime == nil || c.sessionEventStore() == nil {
3491 return false, errors.New("exclusive v3 controller has no bound session runtime")
3492 }
3493 // Export/switch/shutdown callers ask for durability explicitly. The
3494 // transcript, Goal, Plan, Todo and runtime facts already live in the one
3495 // event sequence; no legacy transcript or business sidecar is refreshed.
3496 if _, err := c.flushSessionEvents(context.Background()); err != nil {
3497 return false, err
3498 }
3499 return true, nil
3500 }
3501 if path == "" {
3502 // There IS content but nowhere to write it: this silently dropped whole
3503 // bot conversations (#4414). Surface it loudly instead of returning nil
3504 // so the missing session path can be diagnosed and fixed at the source.
3505 slog.Warn("controller: session has content but no session path; conversation will not be persisted",
3506 "label", c.Label(), "session_dir", c.SessionDir())
3507 return false, errNoSessionPath
3508 }
3509 // Snapshot is an explicit persistence request (session switch, export or
3510 // shutdown), so it is also a v3 semantic checkpoint. Live events normally
3511 // remain eligible for the 200 ms write-behind window; callers asking for a
3512 // snapshot must receive a durable receipt before the rebuildable legacy
3513 // transcript cache is refreshed.
3514 if _, err := c.flushSessionEvents(context.Background()); err != nil {
3515 return false, err
3516 }
3517 // session.save: the session_policy owner rules on the impending save; a
3518 // failure (required-class) vetoes the write. The event goes out after a
3519 // successful save carrying the final payload. The early no-content and
3520 // no-path returns above are not saves and stay unobserved. Conflict
3521 // recovery below may rewrite the path; the phase payload reports the path
3522 // the save targeted.
3523 savePayload, strategyErr := c.extensionSessionStrategy(context.Background(), extension.PointSessionSave, dispatch.PhaseSave, path)
3524 if strategyErr != nil {
3525 return false, strategyErr
3526 }
3527 err, forceRewrite := persistSessionSnapshot(s, path, forceRewrite)
3528 if authoritySaveError(err) {
3529 // Missing/stale authority must not enter diverged/recovery. Frontends
3530 // rebind the lease or surface the typed error.
3531 return false, err
3532 }
3533 if err != nil {
3534 if shutdownRecovery && errors.Is(err, agent.ErrSessionFileLockHeld) {
3535 recoveredPath, recoverErr := c.recoverShutdownSave(s, path, err, forceRewrite)
3536 if recoverErr != nil {
3537 return false, recoverErr
3538 }
3539 path = recoveredPath
3540 s = c.executor.Session()
3541 err = nil
3542 }
3543 }
3544 if err != nil {
3545 if errors.Is(err, agent.ErrSessionExternallyRemoved) {
3546 recoveredPath, recoverErr := c.recoverExternallyRemovedSession(path, err)
3547 if recoverErr != nil {
3548 return false, recoverErr
3549 }
3550 path = recoveredPath
3551 s = c.executor.Session()
3552 err = nil
3553 }
3554 }
3555 if err != nil {
3556 if !errors.Is(err, agent.ErrSessionSnapshotConflict) {
3557 return false, err
3558 }
3559 recoveredPath, outcome, recoverErr := c.recoverSnapshotConflict(path, err, forceRewrite)
3560 if recoverErr != nil {
3561 if shutdownRecovery && errors.Is(recoverErr, agent.ErrSessionFileLockHeld) {
3562 recoveredPath, recoverErr = c.recoverShutdownSave(s, path, recoverErr, forceRewrite)
3563 if recoverErr != nil {
3564 return false, recoverErr
3565 }
3566 path = recoveredPath
3567 s = c.executor.Session()
3568 } else {
3569 return false, recoverErr
3570 }
3571 } else {
3572 if outcome == conflictDropped {
3573 return false, nil
3574 }
3575 // Whatever recovery did — adopted the disk transcript, isolated the
3576 // depth-capped copy, or forked — the rewrite baseline lives on
3577 // the session object and was advanced by the save that succeeded, so
3578 // there is nothing to re-anchor here.
3579 path = recoveredPath
3580 s = c.executor.Session()
3581 }
3582 }
3583 // Persist guardian session so the prefix cache stays warm after restart.
3584 if gp := c.guardianPath; c.guardianSess != nil && gp != "" {
3585 if gerr := c.guardianSess.Save(gp); gerr != nil {
3586 slog.Warn("controller: guardian snapshot", "err", gerr)
3587 }
3588 }
3589 c.emitHeadEvents()
3590 transcriptDurable := true
3591 // Persist recovery gate state so unresolved checkpoints survive restart.
3592 c.saveRecoveryState(path)
3593 // Record the listing-only sidecar fields (model, preview, user-turn count)
3594 // straight from the in-memory conversation, so the sidebar and resume picker
3595 // never have to decode the whole .jsonl just to show them. markActivity bumps
3596 // UpdatedAt exactly like the previous TouchBranchMeta did; false preserves it
3597 // like SetBranchModelPreserveUpdated. The single write subsumes the old
3598 // EnsureBranchMeta / SetBranchModel / TouchBranchMeta sequence.
3599 preview, turns := agent.SessionPreviewFromMessages(s.Snapshot())
3600 if err := updateSessionModelProjection(s, path, modelRef, c.selection.identity, preview, turns, markActivity); err != nil && !listingDeferredAfterUnlockedAppend(s, path, err) {
3601 return transcriptDurable, err
3602 }
3603 c.extensionSessionPayloadEvent(extension.PointSessionSave, savePayload)
3604 return transcriptDurable, nil
3605 }
3606
3607 func updateSessionModelProjection(s *agent.Session, path, modelRef, identity, preview string, turns int, markActivity bool) error {
3608 persisted, ok := s.PersistedState(path)
3609 if !ok {
3610 return fmt.Errorf("session persistence baseline missing after save")
3611 }
3612 var err error
3613 if s.WriteAuthorityRequired() {
3614 _, err = agent.UpdateOwnedSessionListingProjectionIfCurrent(path, modelRef, identity, preview, turns, markActivity, persisted, s.WriteAuthority())
3615 } else {
3616 _, err = agent.UpdateSessionListingProjectionIfCurrent(path, modelRef, identity, preview, turns, markActivity, persisted)
3617 }
3618 return err
3619 }
3620
3621 func (c *Controller) recoverExternallyRemovedSession(path string, saveErr error) (string, error) {
3622 if c.executor == nil || strings.TrimSpace(path) == "" {
3623 return "", saveErr
3624 }
3625 const reason = "session removed while open"
3626 req := SessionRecoveryRequest{OriginalPath: path, Reason: reason, Mode: "external-removal"}
3627 meta := agent.BranchMeta{}
3628 if c.sessionRecoveryMeta != nil {
3629 meta = c.sessionRecoveryMeta(req)
3630 }
3631 info, err := c.executor.Session().SaveConflictRecoveryBranch(agent.RecoveryBranchOptions{
3632 OriginalPath: path,
3633 Reason: reason,
3634 BranchMeta: meta,
3635 })
3636 if err != nil {
3637 return "", fmt.Errorf("preserve externally removed session: %w", err)
3638 }
3639 if err := c.commitRecoveredSession(path, reason, info); err != nil {
3640 return "", err
3641 }
3642 appendSnapshotConflictDiagnostic(path, "external-removal", "moved_to_stable_recovery", saveErr, info.Path, info.Existing)
3643 slog.Warn("controller: active session was removed externally; moved runtime to stable recovery path",
3644 "path", path, "recovery", info.Path, "existing", info.Existing)
3645 c.sink.Emit(sessionRecoveryNotice(event.NoticeCodeSessionRecoveryForked,
3646 "the open session file was removed outside Reasonix; your active conversation was preserved as one recovery copy"))
3647 return info.Path, nil
3648 }
3649
3650 // snapshotConflictLogAttrs flattens a snapshot-conflict error into slog attrs.
3651 // Field reports of #6069-class "session changed on disk" spam are only
3652 // diagnosable when the logs say which trigger fired and what the revision
3653 // ledger looked like, so every recoverSnapshotConflict outcome logs these.
3654 func snapshotConflictLogAttrs(saveErr error, path, mode string) []any {
3655 attrs := []any{"path", path, "mode", mode}
3656 var conflict *agent.SessionSnapshotConflictError
3657 if errors.As(saveErr, &conflict) && conflict != nil {
3658 attrs = append(attrs,
3659 "kind", string(conflict.Kind),
3660 "disk_messages", conflict.ExistingMessages,
3661 "snapshot_messages", conflict.SnapshotMessages,
3662 "base_revision", conflict.BaseRevision,
3663 "disk_revision", conflict.DiskRevision,
3664 )
3665 }
3666 return attrs
3667 }
3668
3669 // conflictOutcome is recoverSnapshotConflict's declared result. Callers act
3670 // on it directly instead of re-deriving what happened from path or session
3671 // pointer comparisons — the misclassification that broke the depth-cap
3672 // rewrite baseline (#6120) hid in exactly that inference.
3673 type conflictOutcome int
3674
3675 const (
3676 // conflictDropped: nothing was recovered and the disk transcript could
3677 // not be adopted; this snapshot was deliberately dropped.
3678 conflictDropped conflictOutcome = iota
3679 // conflictAdoptedDisk: the executor session object was replaced by the
3680 // newer disk transcript; adoptDiskSession already reset its baselines.
3681 conflictAdoptedDisk
3682 // conflictForkedBranch: the same in-memory session moved to a freshly
3683 // forked recovery branch path.
3684 conflictForkedBranch
3685 )
3686
3687 func sessionRecoveryNotice(code, text string) event.Event {
3688 return event.Event{
3689 Kind: event.Notice,
3690 Level: event.LevelWarn,
3691 Audience: event.NoticeAudienceOperator,
3692 Code: code,
3693 Text: text,
3694 }
3695 }
3696
3697 func (c *Controller) recoverSnapshotConflict(path string, saveErr error, forceRewrite bool) (string, conflictOutcome, error) {
3698 if c.executor == nil || strings.TrimSpace(path) == "" {
3699 return "", conflictDropped, saveErr
3700 }
3701 mode := "snapshot"
3702 if forceRewrite {
3703 mode = "rewrite"
3704 }
3705 logAttrs := snapshotConflictLogAttrs(saveErr, path, mode)
3706 if kind, ok := agent.SnapshotConflictKind(saveErr); ok && kind == agent.SessionSnapshotConflictStalePrefix {
3707 if c.adoptDiskSession(path) {
3708 appendSnapshotConflictDiagnostic(path, mode, "adopted_newer_disk_transcript", saveErr, "", false)
3709 slog.Warn("controller: snapshot conflict; adopted newer disk transcript", logAttrs...)
3710 c.sink.Emit(sessionRecoveryNotice(event.NoticeCodeSessionRecoveryAdopted,
3711 "session changed on disk; adopted the newer transcript"))
3712 return path, conflictAdoptedDisk, nil
3713 }
3714 }
3715 reason := "snapshot conflict"
3716 if forceRewrite {
3717 reason = "rewrite conflict"
3718 }
3719 req := SessionRecoveryRequest{OriginalPath: path, Reason: reason, Mode: mode}
3720 meta := agent.BranchMeta{}
3721 if c.sessionRecoveryMeta != nil {
3722 meta = c.sessionRecoveryMeta(req)
3723 }
3724 baseRevision, diskRevision := snapshotConflictRevisions(saveErr)
3725 info, err := c.executor.Session().SaveRecoveryBranch(agent.RecoveryBranchOptions{
3726 OriginalPath: path,
3727 Reason: reason,
3728 BranchMeta: meta,
3729 BaseRevision: baseRevision,
3730 DiskRevision: diskRevision,
3731 })
3732 if err != nil {
3733 if errors.Is(err, agent.ErrSessionRecoveryNotNeeded) {
3734 if c.adoptDiskSession(path) {
3735 appendSnapshotConflictDiagnostic(path, mode, "recovery_not_needed_adopted_disk_transcript", saveErr, "", false)
3736 slog.Warn("controller: snapshot conflict; recovery not needed, adopted disk transcript", logAttrs...)
3737 c.sink.Emit(sessionRecoveryNotice(event.NoticeCodeSessionRecoveryAdoptedCovered,
3738 "session changed on disk; adopted the newer transcript (local changes already covered)"))
3739 return path, conflictAdoptedDisk, nil
3740 }
3741 // Nothing was recovered AND the disk transcript could not be
3742 // adopted: the snapshot is silently dropped. Leave a trace so
3743 // "my last turns vanished" reports can be tied to this path.
3744 appendSnapshotConflictDiagnostic(path, mode, "recovery_not_needed_adopt_failed", saveErr, "", false)
3745 slog.Warn("controller: snapshot conflict; recovery not needed but disk transcript could not be adopted", logAttrs...)
3746 return "", conflictDropped, nil
3747 }
3748 return "", conflictDropped, fmt.Errorf("recover stale session snapshot: %w", err)
3749 }
3750 if err := c.commitRecoveredSession(path, reason, info); err != nil {
3751 return "", conflictDropped, err
3752 }
3753 appendSnapshotConflictDiagnostic(path, mode, "forked_recovery_branch", saveErr, info.Path, info.Existing)
3754 slog.Warn("controller: snapshot conflict; forked recovery branch",
3755 append(logAttrs, "recovery", info.Path, "existing", info.Existing)...)
3756 c.sink.Emit(sessionRecoveryNotice(event.NoticeCodeSessionRecoveryForked,
3757 "session changed on disk; unsaved local transcript was saved as a conflict copy"))
3758 return info.Path, conflictForkedBranch, nil
3759 }
3760
3761 func (c *Controller) recoverShutdownSnapshot(path string, saveErr error) (string, error) {
3762 if c.executor == nil || strings.TrimSpace(path) == "" {
3763 return "", saveErr
3764 }
3765 const reason = "shutdown session file lock timeout"
3766 req := SessionRecoveryRequest{OriginalPath: path, Reason: reason, Mode: "shutdown"}
3767 meta := agent.BranchMeta{}
3768 if c.sessionRecoveryMeta != nil {
3769 meta = c.sessionRecoveryMeta(req)
3770 }
3771 info, err := c.executor.Session().SaveShutdownRecoveryBranch(agent.RecoveryBranchOptions{
3772 OriginalPath: path,
3773 Reason: reason,
3774 BranchMeta: meta,
3775 })
3776 if err != nil {
3777 return "", fmt.Errorf("save shutdown recovery branch: %w", err)
3778 }
3779 if err := c.commitRecoveredSession(path, reason, info); err != nil {
3780 return "", err
3781 }
3782 appendSnapshotConflictDiagnostic(path, "shutdown", "forked_file_lock_recovery", saveErr, info.Path, info.Existing)
3783 slog.Warn("controller: shutdown snapshot lock timed out; forked recovery branch",
3784 "path", path, "recovery", info.Path, "existing", info.Existing)
3785 c.sink.Emit(sessionRecoveryNotice(event.NoticeCodeSessionShutdownRecoveryForked,
3786 "session file stayed busy during shutdown; unsaved transcript was saved as a recovery copy"))
3787 return info.Path, nil
3788 }
3789
3790 func (c *Controller) commitRecoveredSession(originalPath, reason string, info agent.RecoveryBranchInfo) error {
3791 commit := &sessionRecoveryCommit{}
3792 recoveryInfo := SessionRecoveryInfo{
3793 OriginalPath: originalPath,
3794 RecoveryPath: info.Path,
3795 Existing: info.Existing,
3796 Reason: reason,
3797 BaseRevision: info.Meta.BaseRevision,
3798 DiskRevision: info.Meta.DiskRevision,
3799 Meta: info.Meta,
3800 commit: commit,
3801 }
3802 if onSessionRecovered := c.sessionRecoveredHandler(); onSessionRecovered != nil {
3803 if err := onSessionRecovered(recoveryInfo); err != nil {
3804 return fmt.Errorf("commit recovered session: %w", err)
3805 }
3806 }
3807 c.mu.Lock()
3808 c.sessionPath = info.Path
3809 c.guardianPath = guardian.PathFor(info.Path)
3810 c.mu.Unlock()
3811 // Recovery branch is a new lineage path. Load an inherited projection
3812 // sidecar when present so the model view stays compressed across the fork.
3813 c.bindExecutorProjection(info.Path, true)
3814 c.setActiveJobSession(info.Path)
3815 c.rebindCheckpoints(info.Path)
3816 c.transplantInFlightTurnMarker(originalPath, info.Path)
3817 commit.publish()
3818 return nil
3819 }
3820
3821 func (c *Controller) adoptDiskSession(path string) bool {
3822 loaded, err := agent.LoadSession(path)
3823 if err != nil || loaded == nil {
3824 return false
3825 }
3826 c.executor.SetSession(loaded)
3827 c.bindExecutorProjection(path, true)
3828 c.ResetPlannerSession()
3829 c.rebindCheckpoints(path)
3830 c.setActiveJobSession(path)
3831 return true
3832 }
3833
3834 func (c *Controller) messageCount() int {
3835 if c.executor == nil {
3836 return 0
3837 }
3838 return c.executor.Session().Len()
3839 }
3840
3841 // stripTurnMessagesAfter truncates the executor's session to keep only messages
3842 // before the given index, discarding an incomplete synthetic turn (the synthetic
3843 // user prompt plus every assistant/tool message that followed).
3844 func (c *Controller) stripTurnMessagesAfter(idx int) {
3845 if c.executor == nil {
3846 return
3847 }
3848 msgs := c.executor.Session().Snapshot()
3849 if len(msgs) <= idx {
3850 // Compaction may have removed the entire synthetic workset. The
3851 // explicit turn identities still need retraction from display history.
3852 c.replaceSessionAfterCancel(msgs)
3853 return
3854 }
3855 c.replaceSessionAfterCancel(msgs[:idx])
3856 }
3857
3858 // stripInterruptedSyntheticTurnMessagesAfter relocates a synthetic turn after
3859 // an in-turn compaction has rewritten the pre-turn message index, then drops
3860 // that whole controller-created turn.
3861 func (c *Controller) stripInterruptedSyntheticTurnMessagesAfter(idx int) {
3862 if c.executor == nil {
3863 return
3864 }
3865 msgs := c.executor.Session().Snapshot()
3866 startedAt := c.inFlightTurnStartedAt()
3867 if start, ok := resolveInterruptedTurnStart(msgs, idx, false, startedAt, provider.Message{}); ok {
3868 idx = start
3869 }
3870 c.stripTurnMessagesAfter(idx)
3871 }
3872
3873 // stripCancelledVisibleTurnMessagesAfterWithFallback preserves the real user
3874 // prompt and fully paired tool rounds from a cancelled visible turn. Unsafe
3875 // assistant/tool fragments are retained as provider-excluded display history.
3876 // It also covers coordinator
3877 // cancellation before the executor has appended the visible user message. The
3878 // orchestrator owns that input, so it supplies the exact message rather than
3879 // letting cancellation infer the current turn from older transcript history.
3880 func (c *Controller) stripCancelledVisibleTurnMessagesAfterWithFallback(idx int, fallback provider.Message) {
3881 c.stripCancelledVisibleTurnMessagesAfterWithFallbackAt(idx, fallback, c.inFlightTurnStartedAt())
3882 }
3883
3884 func (c *Controller) stripCancelledVisibleTurnMessagesAfterWithFallbackAt(idx int, fallback provider.Message, startedAt time.Time) {
3885 if c.executor == nil {
3886 return
3887 }
3888 before := c.executor.Session().Snapshot()
3889 next := planCancelledMessages(before, idx, fallback, startedAt, c.executor.CanReplayAssistantMessage, c.ledgerTailEvidence())
3890 if next != nil {
3891 c.replaceSessionAfterCancelFrom(before, next)
3892 }
3893 }
3894
3895 func (c *Controller) inFlightTurnStartedAt() time.Time {
3896 path := c.SessionPath()
3897 if path == "" {
3898 return time.Time{}
3899 }
3900 meta, ok, err := agent.LoadBranchMeta(path)
3901 if err != nil || !ok || meta.InFlightTurn == nil {
3902 return time.Time{}
3903 }
3904 return meta.InFlightTurn.StartedAt
3905 }
3906
3907 // resolveInterruptedTurnStart turns the pre-run array index into a stable
3908 // boundary after compaction. New user messages carry a creation timestamp set
3909 // after the marker, and graceful cleanup also has the exact composed prompt as
3910 // a fallback. We only fall back to the legacy index when it still points at a
3911 // plausible turn-start user message, keeping recovery data-safe for older
3912 // sidecars without timestamps.
3913 func resolveInterruptedTurnStart(msgs []provider.Message, idx int, preserveUser bool, startedAt time.Time, fallback provider.Message) (int, bool) {
3914 fallbackContent := ""
3915 if agent.IsUserAuthoredTurnMessage(fallback) {
3916 fallbackContent = StripComposePrefixes(fallback.Content)
3917 }
3918 matchesKind := func(m provider.Message) bool {
3919 if m.Role != provider.RoleUser || agent.IsPinnedContextRevision(m) {
3920 return false
3921 }
3922 if preserveUser {
3923 if !agent.IsUserAuthoredTurnMessage(m) {
3924 return false
3925 }
3926 if fallbackContent != "" && StripComposePrefixes(m.Content) != fallbackContent {
3927 return false
3928 }
3929 }
3930 return true
3931 }
3932 startedMillis := startedAt.UnixMilli()
3933 if !startedAt.IsZero() {
3934 for i, m := range msgs {
3935 if matchesKind(m) && m.CreatedAt >= startedMillis {
3936 return i, true
3937 }
3938 }
3939 }
3940 // Tests/headless runners may not persist an in-flight sidecar. The exact
3941 // graceful fallback still distinguishes the current visible turn; search
3942 // backward so a repeated prompt selects the newest occurrence.
3943 if fallbackContent != "" {
3944 for i, msg := range slices.Backward(msgs) {
3945 if matchesKind(msg) {
3946 return i, true
3947 }
3948 }
3949 }
3950 if idx >= 0 && idx < len(msgs) && matchesKind(msgs[idx]) {
3951 return idx, true
3952 }
3953 return 0, false
3954 }
3955
3956 func (c *Controller) hasInterruptedDisplayAfter(idx int, fallback provider.Message) bool {
3957 if c.executor == nil {
3958 return false
3959 }
3960 msgs := c.executor.Session().Snapshot()
3961 if start, ok := resolveInterruptedTurnStart(msgs, idx, true, c.inFlightTurnStartedAt(), fallback); ok {
3962 idx = start
3963 }
3964 idx = max(0, min(idx, len(msgs)))
3965 for _, m := range msgs[idx:] {
3966 if m.LocalOnly && m.InterruptedTurn != nil {
3967 return true
3968 }
3969 }
3970 return false
3971 }
3972
3973 func completeToolTurnEnd(msgs []provider.Message, i int) (int, bool) {
3974 if i < 0 || i >= len(msgs) {
3975 return i, false
3976 }
3977 m := msgs[i]
3978 if m.LocalOnly || m.Role != provider.RoleAssistant || len(m.ToolCalls) == 0 {
3979 return i, false
3980 }
3981 end := i + 1
3982 for end < len(msgs) && msgs[end].Role == provider.RoleTool && !msgs[end].LocalOnly {
3983 end++
3984 }
3985 results := msgs[i+1 : end]
3986 if len(results) != len(m.ToolCalls) {
3987 return i, false
3988 }
3989 for k, call := range m.ToolCalls {
3990 if strings.TrimSpace(call.Name) == "" || (call.Arguments != "" && !json.Valid([]byte(call.Arguments))) {
3991 return i, false
3992 }
3993 if results[k].ToolCallID != call.ID || results[k].Name != call.Name {
3994 return i, false
3995 }
3996 }
3997 return end, true
3998 }
3999
4000 func interruptedToolSummary(call provider.ToolCall) provider.InterruptedToolSummary {
4001 summary := provider.InterruptedToolSummary{
4002 ID: call.ID, Name: strings.TrimSpace(call.Name), Added: call.Added, Removed: call.Removed,
4003 }
4004 addFile := func(path string) {
4005 path = strings.TrimSpace(path)
4006 if path == "" || path == "/dev/null" || len(summary.Files) >= 8 {
4007 return
4008 }
4009 if slices.Contains(summary.Files, path) {
4010 return
4011 }
4012 summary.Files = append(summary.Files, path)
4013 }
4014 var args map[string]any
4015 if json.Unmarshal([]byte(call.Arguments), &args) == nil {
4016 for _, key := range []string{"path", "file", "file_path", "filename"} {
4017 if value, ok := args[key].(string); ok && strings.TrimSpace(value) != "" {
4018 addFile(value)
4019 }
4020 }
4021 }
4022 for line := range strings.SplitSeq(call.Diff, "\n") {
4023 line = strings.TrimSpace(line)
4024 switch {
4025 case strings.HasPrefix(line, "+++ b/"):
4026 addFile(strings.TrimPrefix(line, "+++ b/"))
4027 case strings.HasPrefix(line, "--- a/"):
4028 addFile(strings.TrimPrefix(line, "--- a/"))
4029 case strings.HasPrefix(line, "*** Update File: "):
4030 addFile(strings.TrimPrefix(line, "*** Update File: "))
4031 case strings.HasPrefix(line, "*** Add File: "):
4032 addFile(strings.TrimPrefix(line, "*** Add File: "))
4033 case strings.HasPrefix(line, "*** Delete File: "):
4034 addFile(strings.TrimPrefix(line, "*** Delete File: "))
4035 }
4036 }
4037 return summary
4038 }
4039
4040 func (c *Controller) replaceSessionAfterCancel(msgs []provider.Message) {
4041 if c.executor == nil {
4042 return
4043 }
4044 c.replaceSessionAfterCancelFromScoped(c.executor.Session().Snapshot(), msgs, true)
4045 }
4046
4047 func (c *Controller) replaceLegacySessionAfterCancelLocked(msgs []provider.Message) {
4048 // The whole cleanup is a save/recovery handoff like snapshot's: hold
4049 // snapshotMu from the in-memory truncation onward. Truncating outside the
4050 // lock would let an in-flight save capture the shortened transcript, read
4051 // the longer partial autosave on disk as a stale-prefix conflict, and
4052 // adopt it back into the executor — silently undoing the cancel cleanup
4053 // before the flush below could persist it.
4054 c.executor.Session().Replace(append([]provider.Message(nil), msgs...))
4055 // The mid-turn autosave may have already written a partial transcript to
4056 // disk. snapshotActivityIfChanged skips the write when messageCount()
4057 // returns to startMessages, so flush the cleaned transcript here. SaveRewrite
4058 // still checks that this controller owns the current on-disk baseline before
4059 // overwriting it, and also covers the edge case where the strip leaves only a
4060 // system message (HasContent() == false). The path is read under the lock so
4061 // an in-flight recovery retarget cannot leave it stale.
4062 c.mu.Lock()
4063 path := c.sessionPath
4064 c.mu.Unlock()
4065 if path != "" {
4066 if err := c.executor.Session().SaveRewrite(path); err != nil {
4067 if errors.Is(err, agent.ErrSessionSnapshotConflict) {
4068 if _, outcome, recoverErr := c.recoverSnapshotConflict(path, err, true); recoverErr != nil {
4069 slog.Warn("controller: post-cancel transcript recovery", "err", recoverErr)
4070 } else if outcome == conflictDropped {
4071 slog.Warn("controller: post-cancel transcript dropped after conflict", "path", path)
4072 }
4073 } else {
4074 slog.Warn("controller: post-cancel transcript flush", "err", err)
4075 }
4076 }
4077 }
4078 }
4079
4080 func (c *Controller) snapshotActivityIfChanged(startMessages int) (bool, error) {
4081 if c.messageCount() <= startMessages {
4082 return true, nil
4083 }
4084 return c.snapshotWithDurability(true, false, false)
4085 }
4086
4087 // SetSessionPath rebinds auto-save without changing the current session
4088 // preference. Callers creating a genuinely fresh conversation should use
4089 // SetFreshSessionPath; callers resuming history should use Resume.
4090 func (c *Controller) SetSessionPath(p string) {
4091 if c.sessionEngineEnabled() {
4092 // Path-based execution rebinding is intentionally unavailable. Hosts use
4093 // ContinueLegacySession for imports or publish an exact SessionRuntime.
4094 slog.Warn("controller: ignored legacy path rebind for exclusive v3 session", "path", p)
4095 return
4096 }
4097 c.setSessionPath(p, false)
4098 }
4099
4100 // SetFreshSessionPath binds a path that is known to belong to a newly-created
4101 // session and samples the configured new-session recovery default.
4102 func (c *Controller) SetFreshSessionPath(p string) {
4103 if service, _, exclusive := c.v3Binding(); exclusive && service != nil {
4104 if _, err := c.BindFreshSession(context.Background(), ""); err != nil {
4105 c.failTurnEventLedger(err)
4106 }
4107 return
4108 }
4109 c.setSessionPath(p, true)
4110 }
4111
4112 func (c *Controller) setSessionPath(p string, fresh bool) {
4113 defer c.refreshRuntimeState(event.Event{})
4114 // See snapshotMu: the swap must not interleave with an in-flight save.
4115 c.snapshotMu.Lock()
4116 c.mu.Lock()
4117 c.sessionPath = p
4118 c.guardianPath = guardian.PathFor(p)
4119 c.mu.Unlock()
4120 // Fresh paths clear projection; rebinds keep/load the target sidecar.
4121 c.bindExecutorProjection(p, !fresh)
4122 c.setActiveJobSession(p)
4123 c.rebindCheckpoints(p)
4124 // A path binding is the ownership boundary for the typed session log. Seed
4125 // the exact current transcript before any subsequent runtime or UI event can
4126 // make an otherwise empty v3 projection look authoritative. This covers the
4127 // initial EnsureSessionPath path as well as compatibility callers that bind
4128 // an already-loaded transcript without going through Resume.
4129 if err := c.seedSessionEventsFromExecutor("session-path-bind"); err != nil {
4130 slog.Warn("controller: seed bound session events", "path", p, "err", err)
4131 c.failTurnEventLedger(err)
4132 }
4133 if fresh {
4134 c.resetRecoveryForNewSession(p)
4135 // A newly-created conversation must not share the previous logical
4136 // session's temporary files (e.g. after EnsureSessionPath on a
4137 // controller that already ran commands).
4138 c.rotateSessionTemp()
4139 } else {
4140 c.loadRecoveryState(p)
4141 }
4142 c.snapshotMu.Unlock()
4143 c.rebindInbox()
4144 if !fresh {
4145 c.recoverCheckpointTransactions()
4146 }
4147 }
4148
4149 func (c *Controller) setActiveJobSession(sessionPath string) {
4150 if c.jobs != nil {
4151 // A candidate borrows the registry without changing its active owner.
4152 // Same-session replacement preserves the already bound artifact path.
4153 if c.background.scope != nil && c.jobs.ReplacementInProgress() {
4154 return
4155 }
4156 c.jobs.SetActiveSessionPath(agent.BranchID(sessionPath), sessionPath)
4157 }
4158 }
4159
4160 // SessionDir reports the directory new session files land in ("" disables
4161 // persistence), so the caller can decide whether to mint a path.
4162 func (c *Controller) SessionDir() string { return c.sessionDir }
4163
4164 // SessionPath reports the file the current conversation auto-saves to ("" when
4165 // persistence is disabled), so a history view can mark the active session.
4166 func (c *Controller) SessionPath() string {
4167 c.mu.Lock()
4168 defer c.mu.Unlock()
4169 return c.sessionPath
4170 }
4171
4172 // SessionRef returns the immutable v3 execution identity. The legacy path is
4173 // intentionally absent from this contract and may only remain as an import or
4174 // display locator while hosts complete their catalog transition.
4175 func (c *Controller) SessionRef() (session.SessionRef, bool) {
4176 _, runtime, _ := c.v3Binding()
4177 if runtime == nil {
4178 return session.SessionRef{}, false
4179 }
4180 return runtime.Ref(), true
4181 }
4182
4183 func (c *Controller) parentSessionID() string {
4184 if ref, ok := c.SessionRef(); ok {
4185 return ref.SessionID
4186 }
4187 return agent.BranchID(c.SessionPath())
4188 }
4189
4190 // History returns the executor's current message log (for repopulating a
4191 // resumed frontend's view).
4192 func (c *Controller) History() []provider.Message {
4193 if c.executor == nil {
4194 return nil
4195 }
4196 if snapshot, ok := c.sessionEventSnapshot(); ok && snapshot.EventSequence > 0 {
4197 if c.sessionEngineEnabled() {
4198 // Controller.History is the provider workset compatibility API used by
4199 // rebuilds and model switches. Durable UI history is deliberately
4200 // separate and flows through SessionService.Query/TranscriptReplay.
4201 return append([]provider.Message(nil), snapshot.Projection.ModelMessages...)
4202 }
4203 projected := snapshot.Projection.ModelMessages
4204 if store := c.sessionEventStore(); store != nil {
4205 // The retired path-bound compatibility store still owns its complete
4206 // persisted transcript. Its provider projection intentionally strips
4207 // host-origin metadata, so explicit history reads use the stored view.
4208 projected = store.Snapshot().Projection.Messages
4209 }
4210 current := c.executor.Session().Snapshot()
4211 // Compatibility runners and an interrupted pre-v3 caller can still leave
4212 // a live, unsaved message tail in the legacy Session cache. Keep that tail
4213 // visible without inferring or persisting business state from it. Normal
4214 // agent execution records exact messages first, so this branch disappears
4215 // as the remaining compatibility callers are retired.
4216 if len(current) > len(projected) && (len(projected) == 0 || reflect.DeepEqual(current[:len(projected)], projected)) {
4217 return current
4218 }
4219 return append([]provider.Message(nil), projected...)
4220 }
4221 return c.executor.Session().Snapshot() // copy — a turn may be appending concurrently
4222 }
4223
4224 // SessionHasUnsavedChanges tells desktop history whether it may safely refresh
4225 // an idle view from the durable WAL. A failed or contended save can leave the
4226 // controller with a newer in-memory transcript; replacing that view from disk
4227 // would hide the user's latest turn until the next retry.
4228 func (c *Controller) SessionHasUnsavedChanges() bool {
4229 if c == nil || c.executor == nil {
4230 return false
4231 }
4232 if snapshot, ok := c.sessionEventSnapshot(); ok && snapshot.EventSequence > 0 {
4233 // The v3 projection is the authoritative transcript. A mismatch identifies
4234 // obsolete compatibility code that bypassed the explicit event recorder;
4235 // checkpoints deliberately do not infer or mirror that unrecorded tail.
4236 current := c.executor.Session().Snapshot()
4237 return snapshot.EventSequence > snapshot.DurableSequence ||
4238 snapshot.PersistenceStatus == "failed" ||
4239 snapshot.PersistenceStatus == "uncertain" ||
4240 !reflect.DeepEqual(snapshot.Projection.ModelMessages, current)
4241 }
4242 return c.executor.Session().HasUnsavedChanges(c.SessionPath())
4243 }
4244
4245 // HistoryLen returns the number of messages in the live log.
4246 func (c *Controller) HistoryLen() int {
4247 if c.executor == nil {
4248 return 0
4249 }
4250 return c.executor.Session().Len()
4251 }
4252
4253 // HistoryWindow returns a copy of the messages in [start, end) of the live
4254 // log. Paging frontends use it to convert a display window without copying
4255 // the whole history.
4256 func (c *Controller) HistoryWindow(start, end int) []provider.Message {
4257 if c.executor == nil {
4258 return []provider.Message{}
4259 }
4260 return c.executor.Session().MessageRange(start, end)
4261 }
4262
4263 // SessionPersistedState exposes the session's persistence baseline for the
4264 // controller's current session path, so a paging frontend can validate a
4265 // display-index sidecar against the live session.
4266 func (c *Controller) SessionPersistedState() (agent.PersistedState, bool) {
4267 if c.executor == nil {
4268 return agent.PersistedState{}, false
4269 }
4270 return c.executor.Session().PersistedState(c.SessionPath())
4271 }
4272
4273 // ContextSnapshot returns (usedTokens, contextWindow) for the gauge. usedTokens
4274 // is what the next request will send, measured the way the compaction trigger
4275 // measures it, so the gauge and the trigger can never disagree. Both zero means
4276 // no data yet — a gauge hides itself.
4277 func (c *Controller) ContextSnapshot() (int, int) {
4278 if c.executor == nil {
4279 return 0, 0
4280 }
4281 return c.executor.ContextUsedTokens(), c.executor.ContextWindow()
4282 }
4283
4284 // CompactRatio returns the auto-compaction threshold as a fraction of the window
4285 // (0 when the executor is unset). The status line shows headroom against it.
4286 func (c *Controller) CompactRatio() float64 {
4287 if c.executor == nil {
4288 return 0
4289 }
4290 return c.executor.CompactRatio()
4291 }
4292
4293 // LastUsage returns the most recent turn's token telemetry (nil before the first
4294 // turn), so frontends can derive the prompt cache-hit rate for the status line.
4295 func (c *Controller) LastUsage() *provider.Usage {
4296 if c.executor == nil {
4297 return nil
4298 }
4299 return c.executor.LastUsage()
4300 }
4301
4302 // SessionCache returns cumulative cache hit/miss prompt tokens for the session,
4303 // so a frontend can render the aggregate (session-wide) cache-hit rate — steadier
4304 // than the single-turn rate and unaffected by compaction.
4305 func (c *Controller) SessionCache() (hit, miss int) {
4306 if c.executor == nil {
4307 return 0, 0
4308 }
4309 return c.executor.SessionCache()
4310 }
4311
4312 // Todos returns the committed event projection used by every frontend. The
4313 // executor's mutable copy is only a tool-loop convenience and cannot override
4314 // a failed or superseded durable commit.
4315 func (c *Controller) Todos() []evidence.TodoItem {
4316 var todos []event.Todo
4317 if ledger := c.turnEventLedger(); ledger != nil {
4318 todos, _ = ledger.TodoState()
4319 } else {
4320 todos, _ = c.volatileTodoState()
4321 }
4322 out := make([]evidence.TodoItem, len(todos))
4323 for i, todo := range todos {
4324 out[i] = evidence.TodoItem{Content: todo.Content, Status: todo.Status}
4325 }
4326 return out
4327 }
4328
4329 // Balance queries the active provider's wallet balance, or (nil, nil) when the
4330 // provider declares no balance_url — so a caller treats "not configured" and
4331 // "fetched" the same and just omits the readout when nil.
4332 func (c *Controller) Balance(ctx context.Context) (*billing.Balance, error) {
4333 if strings.TrimSpace(c.balanceURL) == "" {
4334 return nil, nil
4335 }
4336 ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
4337 defer cancel()
4338 return billing.FetchWithClient(ctx, c.balanceClient, c.balanceURL, c.balanceKey)
4339 }
4340
4341 // Host returns the running MCP host (nil when no plugins), for frontends that
4342 // list servers / resolve MCP prompts.
4343 func (c *Controller) Host() *plugin.Host { return c.mcp.hostRef() }
4344
4345 // Commands returns the loaded custom slash commands.
4346 func (c *Controller) Commands() []command.Command {
4347 if p := c.commands.Load(); p != nil {
4348 return *p
4349 }
4350 return nil
4351 }
4352
4353 // ReloadCommands rescans all command directories and hot-swaps the slash_command
4354 // tool and the internal command slice — no MCP restart, no hook rerun.
4355 func (c *Controller) ReloadCommands(ctx context.Context) error {
4356 select {
4357 case <-ctx.Done():
4358 return ctx.Err()
4359 default:
4360 }
4361 cmds, loadErr := command.LoadRoots(config.CommandRootsForRoot(c.workspaceRoot)...)
4362 var cmdSkills []skill.Skill
4363 if !c.disableImplicitSkillInvocation {
4364 cmdSkills = c.SlashSkills()
4365 }
4366
4367 entries := make([]command.SlashEntry, 0, len(cmdSkills)+len(cmds))
4368 for _, sk := range cmdSkills {
4369
4370 entries = append(entries, command.SlashEntry{
4371 Name: sk.SlashName(),
4372 Description: sk.Description,
4373 Render: func(args []string) string { return c.skills.renderInvocation(sk, strings.Join(args, " ")) },
4374 })
4375 }
4376 for _, cmd := range cmds {
4377 if cmd.Hidden {
4378 continue
4379 }
4380
4381 entries = append(entries, command.SlashEntry{
4382 Name: cmd.Name,
4383 Description: cmd.Description,
4384 ArgHint: cmd.ArgHint,
4385 Render: func(args []string) string { return cmd.Render(args) },
4386 })
4387 }
4388 c.mcp.registerTool(command.NewSlashCommandTool(entries))
4389 cmdSlice := cmds
4390 c.commands.Store(&cmdSlice)
4391 return loadErr
4392 }
4393
4394 // Skills returns the discoverable skills (for the slash menu and `/skills`).
4395 // When a live Store is available, scan it on demand so skills installed during
4396 // this session appear without rewriting the cache-stable system prompt.
4397 // Executor returns the underlying agent when present (nil for pure runners).
4398 func (c *Controller) Executor() *agent.Agent {
4399 if c == nil {
4400 return nil
4401 }
4402 return c.executor
4403 }
4404
4405 func (c *Controller) Skills() []skill.Skill {
4406 return c.skills.list()
4407 }
4408
4409 // ImplicitSkillInvocationEnabled reports whether skills are exposed to the
4410 // model for automatic discovery and invocation. Explicit /skill handling is
4411 // independent of this model-facing capability.
4412 func (c *Controller) ImplicitSkillInvocationEnabled() bool {
4413 return c != nil && !c.disableImplicitSkillInvocation
4414 }
4415
4416 // SlashSkills returns the user-visible skill directory. Plugin skills use
4417 // package-qualified names while Skills keeps bare model/run_skill identifiers.
4418 func (c *Controller) SlashSkills() []skill.Skill {
4419 return c.skills.slashList()
4420 }
4421
4422 // AllSkills returns every discoverable skill, including disabled ones, for
4423 // management surfaces that need to re-enable a hidden skill.
4424 func (c *Controller) AllSkills() []skill.Skill {
4425 return c.skills.listAll()
4426 }
4427
4428 // LoadSkill reads the selected skill body without expanding every catalog
4429 // candidate. It is intentionally outside the shared capability interface:
4430 // management surfaces may opt into body loading, while search/list stay
4431 // metadata-only and cache-stable.
4432 func (c *Controller) LoadSkill(name string) (skill.Skill, bool) {
4433 return c.skills.load(name)
4434 }
4435
4436 // DisabledSkills returns all discoverable skills that are disabled in config.
4437 func (c *Controller) DisabledSkills() []skill.Skill {
4438 cfg, err := config.Load()
4439 if err != nil {
4440 return nil
4441 }
4442 var out []skill.Skill
4443 for _, sk := range c.AllSkills() {
4444 if cfg.IsSkillDisabled(sk.Name) {
4445 out = append(out, sk)
4446 }
4447 }
4448 return out
4449 }
4450
4451 // SkillEnabled reports whether a discoverable skill is enabled.
4452 func (c *Controller) SkillEnabled(name string) bool {
4453 cfg, err := config.Load()
4454 if err != nil {
4455 return true
4456 }
4457 return !cfg.IsSkillDisabled(name)
4458 }
4459
4460 // SetSkillEnabled persists a skill enable/disable preference. The caller should
4461 // rebuild the controller for the prompt/tool registry to reflect it immediately.
4462 func (c *Controller) SetSkillEnabled(name string, enabled bool) error {
4463 found := false
4464 for _, sk := range c.AllSkills() {
4465 if config.SkillNameKey(sk.Name) == config.SkillNameKey(name) {
4466 name = sk.Name
4467 found = true
4468 break
4469 }
4470 }
4471 if !found {
4472 return fmt.Errorf("unknown skill: %s", name)
4473 }
4474 // Serialize the load-modify-save against other in-process user-config
4475 // editors so concurrent writers (bot mapping persistence, desktop
4476 // settings) don't drop this toggle or lose their own fields.
4477 unlock := config.LockUserConfigEdits()
4478 defer unlock()
4479 cfg := config.LoadForEdit(config.UserConfigPath())
4480 if err := cfg.SetSkillEnabled(name, enabled); err != nil {
4481 return err
4482 }
4483 return cfg.SaveTo(config.UserConfigPath())
4484 }
4485
4486 // CreateSkill writes a new skill file at the given scope and returns its
4487 // path. Skills()/AllSkills()/RunSkill() read the live store on demand, so the
4488 // new skill is usable (by name) immediately with no rebuild and appears in the
4489 // next real user turn's live session-context catalog. Rebuilds remain necessary
4490 // when the tool registry or enabled-skill configuration changes.
4491 func (c *Controller) CreateSkill(name string, scope skill.Scope, content string) (string, error) {
4492 w := c.skills.writer()
4493 if w == nil {
4494 return "", fmt.Errorf("no writable skill store in this session")
4495 }
4496 return w.CreateWithContent(name, scope, content)
4497 }
4498
4499 // UpdateSkill overwrites an existing user-authored skill file in place. See
4500 // skill.Store.UpdateContent for the builtin-refusal and scope-match rules.
4501 func (c *Controller) UpdateSkill(name string, scope skill.Scope, content string) error {
4502 w := c.skills.writer()
4503 if w == nil {
4504 return fmt.Errorf("no writable skill store in this session")
4505 }
4506 return w.UpdateContent(name, scope, content)
4507 }
4508
4509 // DeleteSkill removes a user-authored skill file at the given scope. See
4510 // skill.Store.Delete for the builtin-refusal and scope-match rules.
4511 func (c *Controller) DeleteSkill(name string, scope skill.Scope) error {
4512 w := c.skills.writer()
4513 if w == nil {
4514 return fmt.Errorf("no writable skill store in this session")
4515 }
4516 return w.Delete(name, scope)
4517 }
4518
4519 // HookRunner returns the session's hook runner (nil-safe; may hold zero hooks),
4520 // so a frontend can list the active hooks via `/hooks`.
4521 func (c *Controller) HookRunner() *hook.Runner { return c.hooks }
4522
4523 // AddMCPServer connects an MCP server live and persists it to the user-global
4524 // config. Its tools are registered immediately and become available on the next
4525 // turn (the agent reads the registry per turn). The raw entry — ${VARS} intact —
4526 // is what's written to disk; the live connection uses the expanded form. Returns
4527 // the number of tools the server exposed. Persistence is transactional: a config
4528 // or activation failure removes the just-connected client so the live registry
4529 // never claims an install that will disappear after restart.
4530 func (c *Controller) AddMCPServer(e config.PluginEntry) (int, error) {
4531 // AddMCPServer is an explicit user action. Mark the live entry with the same
4532 // provenance it will receive when the saved user config is loaded next time,
4533 // so /mcp add is add-and-use in the current session too.
4534 e.Source = config.MCPSourceUserConfig
4535 if effective, loadErr := config.LoadForRootReadOnly(c.workspaceRoot); loadErr != nil {
4536 return 0, loadErr
4537 } else {
4538 for _, configured := range effective.Plugins {
4539 if configured.Name != e.Name {
4540 continue
4541 }
4542 if configured.Source != config.MCPSourceUserConfig && configured.Source != config.MCPSourceLegacyUser {
4543 return 0, fmt.Errorf("MCP server %q is already configured by %s; edit or remove that declaration before installing a global server with the same name", e.Name, configured.Source)
4544 }
4545 break
4546 }
4547 }
4548 n, err := c.connectMCPServer(e)
4549 if err != nil {
4550 return 0, err
4551 }
4552 if _, err := config.InstallUserPluginForRoot(c.workspaceRoot, e, true); err != nil {
4553 c.DisconnectMCPServer(e.Name)
4554 return 0, fmt.Errorf("saving MCP server config: %w", err)
4555 }
4556 return n, nil
4557 }
4558
4559 // ConnectMCPServer connects an MCP server entry for this session without writing
4560 // it to config. Desktop owns config placement so it can keep user-level settings
4561 // out of project reasonix.toml while preserving the CLI AddMCPServer semantics.
4562 func (c *Controller) ConnectMCPServer(e config.PluginEntry) (int, error) {
4563 return c.connectMCPServer(e)
4564 }
4565
4566 // RegisterMCPServerOnDemand restores a configured server's cached provider
4567 // surface without forcing a handshake. It is the durable-enable counterpart to
4568 // ConnectMCPServer, which remains the explicit install/retry operation.
4569 func (c *Controller) RegisterMCPServerOnDemand(e config.PluginEntry) (int, error) {
4570 spec := c.mcpSpec(e)
4571 n, err := c.mcp.registerSpecOnDemand(spec)
4572 if err == nil && c.capabilityRuntime != nil {
4573 c.capabilityRuntime.UpsertServer(e, spec, true)
4574 }
4575 return n, err
4576 }
4577
4578 // connectMCPServer expands an entry's ${VARS}, applies the known-server
4579 // overrides scoped to the workspace, and connects it live via the mcp manager.
4580 func (c *Controller) connectMCPServer(e config.PluginEntry) (int, error) {
4581 spec := c.mcpSpec(e)
4582 n, err := c.mcp.connectSpec(spec)
4583 if err == nil && c.capabilityRuntime != nil {
4584 c.capabilityRuntime.UpsertServer(e, spec, true)
4585 }
4586 return n, err
4587 }
4588
4589 func (c *Controller) mcpSpec(e config.PluginEntry) plugin.Spec {
4590 exp := e.ExpandedPlugin()
4591 configSource := strings.TrimSpace(string(exp.Source))
4592 spec := plugin.ApplyKnownOverrides(plugin.Spec{
4593 Name: exp.Name,
4594 Type: exp.Type,
4595 Command: exp.Command,
4596 Args: exp.Args,
4597 Env: exp.Env,
4598 URL: exp.URL,
4599 Headers: exp.Headers,
4600 StartupTimeout: controllerMCPTimeout(exp.StartupTimeoutSeconds),
4601 DefaultCallTimeout: c.mcpDefaultCallTimeout,
4602 CallTimeout: controllerMCPTimeout(exp.CallTimeoutSeconds),
4603 ToolTimeouts: controllerMCPToolTimeouts(exp.ToolTimeoutSeconds),
4604 WorkspaceRoot: c.WorkspaceRoot(),
4605 ConfigSource: configSource,
4606 Authorized: exp.Source.UserAuthorized(),
4607 // Explicit user installs and reconnects run as trusted host processes.
4608 ProcessMode: plugin.MCPProcessHost,
4609 }, c.WorkspaceRoot())
4610 if exp.Source.ProjectScoped() && strings.TrimSpace(spec.Dir) == "" {
4611 spec.Dir = c.WorkspaceRoot()
4612 }
4613 if c.mcpConfigureSpec != nil {
4614 c.mcpConfigureSpec(&spec)
4615 if spec.ProcessMode == "" {
4616 spec.ProcessMode = plugin.MCPProcessHost
4617 }
4618 }
4619 return spec
4620 }
4621
4622 // syncCapabilityRuntimeFromConfig restores one server's authoritative runtime
4623 // entry after a transactional disconnect/rollback. enabledOverride is used for
4624 // a session-only disconnect; nil re-resolves the durable activation state.
4625 func (c *Controller) syncCapabilityRuntimeFromConfig(name string, enabledOverride *bool) {
4626 if c == nil || c.capabilityRuntime == nil {
4627 return
4628 }
4629 name = strings.TrimSpace(name)
4630 cfg, err := config.LoadForRoot(c.workspaceRoot)
4631 if err != nil {
4632 // The caller revokes first. A config read failure must not re-enable a
4633 // potentially stale spec or shared-Host client.
4634 return
4635 }
4636 for _, entry := range cfg.Plugins {
4637 if strings.TrimSpace(entry.Name) != name {
4638 continue
4639 }
4640 enabled := config.DeclaredDefaultOn(entry)
4641 if enabledOverride != nil {
4642 enabled = *enabledOverride
4643 } else if resolved, resolveErr := config.DefaultMCPActivationStore().IsEnabled(entry, c.workspaceRoot); resolveErr == nil {
4644 enabled = resolved
4645 }
4646 c.capabilityRuntime.UpsertServer(entry, c.mcpSpec(entry), enabled)
4647 return
4648 }
4649 c.capabilityRuntime.RemoveServer(name)
4650 }
4651
4652 func controllerMCPTimeout(seconds int) time.Duration {
4653 if seconds <= 0 {
4654 return 0
4655 }
4656 return time.Duration(seconds) * time.Second
4657 }
4658
4659 func controllerMCPToolTimeouts(values map[string]int) map[string]time.Duration {
4660 if len(values) == 0 {
4661 return nil
4662 }
4663 out := make(map[string]time.Duration, len(values))
4664 for name, seconds := range values {
4665 if name = strings.TrimSpace(name); name != "" && seconds > 0 {
4666 out[name] = time.Duration(seconds) * time.Second
4667 }
4668 }
4669 if len(out) == 0 {
4670 return nil
4671 }
4672 return out
4673 }
4674
4675 // ImportMCPEntries persists selected MCP entries and attempts to connect them
4676 // live. A connection failure does not roll back the config import: the user can
4677 // fix local dependencies and reconnect in a later session.
4678 func (c *Controller) ImportMCPEntries(entries []config.PluginEntry) (total, added, updated, connected, failed, skipped int, err error) {
4679 total, added, updated, err = config.ImportCCSwitchMCPEntries(entries)
4680 if err != nil {
4681 return 0, 0, 0, 0, 0, 0, err
4682 }
4683 effectiveCfg, loadErr := config.LoadForRoot(c.workspaceRoot)
4684 if loadErr != nil {
4685 return 0, 0, 0, 0, 0, 0, loadErr
4686 }
4687 effective := make(map[string]config.PluginEntry, len(effectiveCfg.Plugins))
4688 for _, entry := range effectiveCfg.Plugins {
4689 effective[entry.Name] = entry
4690 }
4691 for _, imported := range entries {
4692 e, ok := effective[imported.Name]
4693 if !ok || e.Source != config.MCPSourceUserConfig {
4694 // A project declaration with the same name remains effective. The
4695 // imported global entry is saved as its lower-priority fallback.
4696 skipped++
4697 continue
4698 }
4699 if c.mcp.hasServer(e.Name) {
4700 if c.capabilityRuntime != nil {
4701 // Import updates may intentionally keep an existing live client, but
4702 // future proxy reconnects must use the newly persisted spec.
4703 c.capabilityRuntime.UpsertServer(e, c.mcpSpec(e), true)
4704 }
4705 skipped++
4706 continue
4707 }
4708 if _, err := c.AddMCPServer(e); err != nil {
4709 failed++
4710 continue
4711 }
4712 connected++
4713 }
4714 return total, added, updated, connected, failed, skipped, nil
4715 }
4716
4717 func (c *Controller) ConfiguredMCPNames() []string {
4718 cfg, err := config.LoadForRootReadOnly(c.workspaceRoot)
4719 if err != nil {
4720 return nil
4721 }
4722 names := make([]string, 0, len(cfg.Plugins))
4723 for _, p := range cfg.Plugins {
4724 names = append(names, p.Name)
4725 }
4726 return names
4727 }
4728
4729 func (c *Controller) DisconnectedMCPNames() []string {
4730 cfg, err := config.LoadForRootReadOnly(c.workspaceRoot)
4731 if err != nil {
4732 return nil
4733 }
4734 connected := map[string]bool{}
4735 for _, name := range c.mcp.serverNames() {
4736 connected[name] = true
4737 }
4738 var names []string
4739 for _, p := range cfg.Plugins {
4740 if !connected[p.Name] {
4741 names = append(names, p.Name)
4742 }
4743 }
4744 return names
4745 }
4746
4747 // ConnectConfiguredMCPServer starts a configured server at the user's request;
4748 // for a project-declared one that request is the approval, and is recorded.
4749 func (c *Controller) ConnectConfiguredMCPServer(name string) (int, error) {
4750 p, err := c.configuredMCPServer(name)
4751 if err != nil {
4752 return 0, err
4753 }
4754 if err := config.RecordExplicitStart(p, c.workspaceRoot); err != nil {
4755 return 0, err
4756 }
4757 return c.connectMCPServer(p)
4758 }
4759
4760 func (c *Controller) configuredMCPServer(name string) (config.PluginEntry, error) {
4761 cfg, err := config.LoadForRoot(c.workspaceRoot)
4762 if err != nil {
4763 return config.PluginEntry{}, err
4764 }
4765 for _, p := range cfg.Plugins {
4766 if p.Name == name {
4767 return p, nil
4768 }
4769 }
4770 return config.PluginEntry{}, fmt.Errorf("no configured MCP server named %q", name)
4771 }
4772
4773 // RemoveMCPServer removes writable config before disconnecting the live server.
4774 // A persistence failure must not produce a false-successful session-only removal.
4775 // MCPs contributed by installed plugin packages cannot be removed independently.
4776 func (c *Controller) RemoveMCPServer(name string) (disconnected bool, err error) {
4777 cfg, lerr := config.LoadForRoot(c.workspaceRoot)
4778 if lerr != nil {
4779 return false, lerr
4780 }
4781 if owner, ok := cfg.PluginPackageOwner(name); ok {
4782 return false, fmt.Errorf("MCP server %q is managed by plugin %q; disable or remove the plugin instead", name, owner)
4783 }
4784 entry, removed, _, rerr := config.RemovePluginFromEffectiveSourceForRoot(c.workspaceRoot, name)
4785 if rerr != nil {
4786 return false, rerr
4787 }
4788 if !removed {
4789 return false, fmt.Errorf("no removable MCP server named %q", name)
4790 }
4791 _ = config.DefaultMCPActivationStore().ClearServer(entry, c.workspaceRoot)
4792 removedState := reconcileRemovedMCPState(c.workspaceRoot, name)
4793 if c.capabilityRuntime != nil {
4794 // Revoke before touching the shared Host so an overlapping resolver cannot
4795 // reuse a sibling tab's still-connected client.
4796 c.capabilityRuntime.RemoveServer(name)
4797 }
4798 disconnected = c.mcp.disconnect(name)
4799 if !disconnected {
4800 c.mcp.removeToolPrefix(name)
4801 }
4802 // A lower-priority same-name declaration may now be effective. Restore its
4803 // cached/on-demand surface without starting a process; otherwise ensure the
4804 // removed name stays absent.
4805 if removedState.fallbackFound {
4806 enabled := config.MCPServerEnabled(removedState.fallback, c.workspaceRoot)
4807 if enabled {
4808 _, _ = c.RegisterMCPServerOnDemand(removedState.fallback)
4809 } else {
4810 c.syncCapabilityRuntimeFromConfig(name, &enabled)
4811 }
4812 } else {
4813 c.syncCapabilityRuntimeFromConfig(name, nil)
4814 }
4815 return disconnected, removedState.cleanupErr
4816 }
4817
4818 // DisconnectMCPServer disconnects a live server for this session without touching
4819 // config — the connector toggle's "off". Its tools vanish next turn; it reconnects
4820 // on the next session start, or now via ConnectConfiguredMCPServer (the "on").
4821 // Reports whether a live server was actually disconnected.
4822 func (c *Controller) DisconnectMCPServer(name string) bool {
4823 if c.capabilityRuntime != nil {
4824 c.capabilityRuntime.SetServerEnabled(name, false)
4825 }
4826 disconnected := c.mcp.disconnect(name)
4827 removedPlaceholder := 0
4828 if !disconnected {
4829 removedPlaceholder = c.mcp.removeToolPrefix(name)
4830 }
4831 // Keep configured servers discoverable as disabled, but forget runtime-only
4832 // or rolled-back installs that no longer exist in configuration.
4833 disabled := false
4834 c.syncCapabilityRuntimeFromConfig(name, &disabled)
4835 return disconnected || removedPlaceholder > 0
4836 }
4837
4838 // UnregisterMCPServerTools hides a shared MCP server from this controller only.
4839 // The desktop shared-host path uses this for per-tab connector toggles: the
4840 // shared client stays alive for sibling tabs, while this session's registry drops
4841 // the server's provider-visible tools before the next turn.
4842 func (c *Controller) UnregisterMCPServerTools(name string) bool {
4843 if c.capabilityRuntime != nil {
4844 c.capabilityRuntime.SetServerEnabled(name, false)
4845 }
4846 return c.mcp.suspendToolPrefix(name)
4847 }
4848
4849 // Label returns the human-readable model label, e.g. "deepseek-flash".
4850 func (c *Controller) Label() string { return c.label }
4851
4852 // ModelRef returns the canonical provider/model reference for the session.
4853 func (c *Controller) ModelRef() string { return c.selection.ref }
4854
4855 // ModelSelectionIdentity is frozen with the provider assembled for this runtime.
4856 func (c *Controller) ModelSelectionIdentity() string { return c.selection.identity }
4857
4858 // WorkspaceRoot returns the workspace root for this controller's session
4859 // (the directory that file-writers and @-references are scoped to).
4860 // Empty means no scoping is in effect.
4861 func (c *Controller) WorkspaceRoot() string { return c.workspaceRoot }
4862
4863 // WorkspaceRepo is the workspace's git identity as the session resolved it when
4864 // it opened. Host git reads the workspace through it rather than rediscovering
4865 // the repository from files the session's own commands may have written.
4866 func (c *Controller) WorkspaceRepo() gitcmd.Repo { return c.workspaceRepo }
4867
4868 func (c *Controller) imageInputEnabled() bool {
4869 if c.frozenImageInput != nil {
4870 return *c.frozenImageInput
4871 }
4872 ref := c.selection.ref
4873 cfg, err := config.LoadForRoot(c.workspaceRoot)
4874 if err == nil && ref == "" {
4875 ref = cfg.DefaultModel
4876 }
4877 if err != nil || ref == "" {
4878 return false
4879 }
4880 entry, ok := cfg.ResolveModel(ref)
4881 if !ok {
4882 return false
4883 }
4884 if c.modelCapabilityResolver != nil {
4885 return c.modelCapabilityResolver(entry).AcceptsImages(c.visionModel != "")
4886 }
4887 return config.VisionCapabilityForModel(entry).AllowsImages(c.visionModel != "")
4888 }
4889
4890 // ImageInputEnabled reports whether the current model accepts direct image
4891 // inputs, so frontends can gate image-only UX before a turn starts.
4892 func (c *Controller) ImageInputEnabled() bool { return c.imageInputEnabled() }
4893
4894 // ImageInputSnapshot avoids configuration reads on the Desktop metadata path.
4895 // Legacy/custom controllers without a frozen boot snapshot use the existing
4896 // background metadata fallback instead.
4897 func (c *Controller) ImageInputSnapshot() (enabled, fallback, available bool) {
4898 if c == nil || c.frozenImageInput == nil {
4899 return false, false, false
4900 }
4901 return *c.frozenImageInput, c.visionModel != "", true
4902 }
4903
4904 // ImageCapabilityChanged lets desktop refresh an idle runtime before admission.
4905 func (c *Controller) ImageCapabilityChanged() bool {
4906 return c.imageCapabilityChanged != nil && c.imageCapabilityChanged()
4907 }
4908
4909 // SessionAuthorizations snapshots this controller's same-session tool
4910 // grants ("Allow for this session"), external-folder refs, and Plan-mode trust,
4911 // for carrying into a replacement controller across a rebuild — see
4912 // RestoreSessionAuthorizations.
4913 func (c *Controller) SessionAuthorizations() SessionAuthorizations {
4914 auth := c.approval.snapshotSessionAuthorizations()
4915 auth.externalFolderRefs = c.snapshotExternalFolderRefs()
4916 if c.writeAccess.roots != nil {
4917 auth.WriteRoots = c.writeAccess.roots.SessionRoots()
4918 if auth.WriteRoots == nil {
4919 auth.WriteRoots = []string{}
4920 }
4921 }
4922 return auth
4923 }
4924
4925 // ReleaseResources stops plugin subprocesses and releases resources without
4926 // firing SessionEnd. Use it only when replacing the controller for the same
4927 // logical session.
4928 func (c *Controller) ReleaseResources() {
4929 c.close(false, closeJobsWithGrace)
4930 }
4931
4932 // Close stops plugin subprocesses and releases resources. A session that ever
4933 // started fires SessionEnd so a teardown hook runs.
4934 func (c *Controller) Close() {
4935 c.recordLifecycle("close", "controller_close", "", 0, "")
4936 c.close(true, closeJobsWithGrace)
4937 }
4938
4939 // Closed is signalled after teardown has released all Controller-owned stores.
4940 // Close itself only requests teardown when a turn is still finalizing.
4941 func (c *Controller) Closed() <-chan struct{} { return c.closeFinalized }
4942
4943 // CloseAfterDestroy releases controller resources after the caller has already
4944 // begun session-specific job teardown. It avoids a second synchronous job grace
4945 // wait while still cancelling the manager root and reaping temporary artifacts
4946 // once every job goroutine finally exits.
4947 func (c *Controller) CloseAfterDestroy() {
4948 c.close(true, closeJobsAsync)
4949 }
4950
4951 type closeJobsMode int
4952
4953 const (
4954 closeJobsWithGrace closeJobsMode = iota
4955 closeJobsAsync
4956 )
4957
4958 func (c *Controller) close(fireSessionEnd bool, jobsMode closeJobsMode) {
4959 defer c.refreshRuntimeState(event.Event{})
4960 // Desktop tab lifecycles can race a rebind/model-switch/close on the same
4961 // controller; make teardown idempotent so a duplicate Close cannot re-fire
4962 // SessionEnd hooks or re-run cleanup. The first caller's jobsMode wins.
4963 c.closeOnce.Do(func() {
4964 c.mu.Lock()
4965 cancel := c.turns.cancel
4966 maintenance := c.maintenance
4967 done := c.turns.done
4968 // A phase marker alone is not a live turn: recovery may retain one after
4969 // cancel/done ownership has gone. Only a live body or terminal fanout
4970 // defers final resource release.
4971 maintenanceActive := maintenance != nil && !maintenance.safeToRelease
4972 maintenanceNeedsCancel := maintenanceActive && maintenance.activity != "finalizing"
4973 turnActive := done != nil || c.finalizingLocked() || c.turns.recoveryFanout || maintenanceActive
4974 // Seal turn admission and drop anything already parked: a parked turn
4975 // must not start against a controller that is being torn down, and
4976 // without the closed flag a submit landing after this critical
4977 // section (while a running turn's TurnDone delivery is still in
4978 // flight) would park again and start after teardown.
4979 c.closed = true
4980 c.closeFireSessionEnd = fireSessionEnd
4981 c.closeJobsMode = jobsMode
4982 c.turns.pending = nil
4983 c.turns.wake = false
4984 if cancel != nil {
4985 c.turns.cancelRequested = true
4986 if c.turns.phase == session.RuntimeRunning {
4987 c.turns.phase = session.RuntimeCancelling
4988 c.noteExecutionLocked(session.RuntimeCancelling, "cancelling")
4989 }
4990 } else {
4991 c.turns.cancelRequested = false
4992 }
4993 if !turnActive {
4994 if maintenance != nil {
4995 c.maintenance = nil
4996 close(maintenance.done)
4997 }
4998 c.turns.phase = session.RuntimeClosed
4999 c.turns.finishingBound.end()
5000 c.turns.finishingBound.endIdle()
5001 }
5002 c.mu.Unlock()
5003 if maintenanceNeedsCancel {
5004 maintenance.cancel()
5005 }
5006 if cancel != nil {
5007 // Signal the owned turn before prompt bookkeeping or callbacks. A
5008 // stalled registry/adapter must never delay Stop during shutdown.
5009 cancel()
5010 c.startCancellationWatchdog(done)
5011 c.promptOwner.CancelAll()
5012 c.approval.clearAll()
5013 } else {
5014 c.promptOwner.Clear()
5015 }
5016 if c.goalDriverControl.cancel != nil {
5017 c.goalDriverControl.cancel()
5018 }
5019 if !turnActive {
5020 c.finalizeControllerClose()
5021 }
5022 })
5023 }
5024
5025 // finalizeControllerClose releases stores and process resources only after an
5026 // active turn has published its terminal boundary. Closing the ledger or the
5027 // session binding earlier makes the final TurnDone impossible to accept.
5028 func (c *Controller) finalizeControllerClose() {
5029 c.closeFinalizeOnce.Do(func() {
5030 if c.closeFinalized != nil {
5031 defer close(c.closeFinalized)
5032 }
5033 c.mu.Lock()
5034 started := c.startedOnce
5035 fireSessionEnd := c.closeFireSessionEnd && !c.background.retired
5036 jobsMode := c.closeJobsMode
5037 c.mu.Unlock()
5038 // Goal-driver workers may be inside the pre-admission durability
5039 // checkpoint. Join them before closing the v3 writer so teardown cannot
5040 // race a late Flush or recreate files under a test/session directory.
5041 c.goalDriverWG.Wait()
5042 // Join sidecar creation and queue scans without waiting for the
5043 // dispatcher itself: host admission may retire its own controller.
5044 c.inbox.scanMu.Lock()
5045 c.inbox.mu.Lock()
5046 c.inbox.closed = true
5047 if c.inbox.store != nil {
5048 c.inbox.store.Close()
5049 c.inbox.store = nil
5050 }
5051 if c.inbox.tempLease != nil {
5052 c.inbox.tempLease.Release()
5053 c.inbox.tempLease = nil
5054 }
5055 c.inbox.mu.Unlock()
5056 c.inbox.scanMu.Unlock()
5057 if fireSessionEnd && started {
5058 c.hooks.SessionEnd(context.Background(), "other")
5059 c.extensionSessionEvent(extension.PointSessionEnd, dispatch.PhaseEnd, c.SessionPath())
5060 }
5061 if c.background.scope != nil {
5062 c.background.scope.Release(jobsMode == closeJobsAsync)
5063 } else if c.jobs != nil {
5064 switch jobsMode {
5065 case closeJobsAsync:
5066 c.jobs.CloseAsync()
5067 default:
5068 c.jobs.Close() // cancel any still-running background jobs
5069 }
5070 }
5071 c.turnEvents.mu.RLock()
5072 projection := c.turnEvents.projection
5073 c.turnEvents.mu.RUnlock()
5074 if projection != nil {
5075 projection.CloseFollowers()
5076 }
5077 if ledger := c.turnEventLedger(); ledger != nil {
5078 if err := ledger.Close(); err != nil {
5079 slog.Warn("controller: close turn event ledger", "err", err)
5080 }
5081 }
5082 c.turnEvents.commitMu.Lock()
5083 if pending := c.turnEvents.pendingExecutionCommit; pending != nil {
5084 pending.Release()
5085 c.turnEvents.pendingExecutionCommit = nil
5086 }
5087 c.turnEvents.commitMu.Unlock()
5088 service, runtime, exclusive := c.v3Binding()
5089 if exclusive && runtime != nil {
5090 c.releaseSessionRuntimeBinding(service)
5091 } else if v3 := c.sessionEventStore(); v3 != nil {
5092 c.turnEvents.mu.RLock()
5093 release := c.turnEvents.v3Release
5094 c.turnEvents.mu.RUnlock()
5095 var err error
5096 if release != nil {
5097 err = release(context.Background())
5098 } else {
5099 err = v3.Close(context.Background())
5100 }
5101 if err != nil {
5102 slog.Warn("controller: flush and close v3 session", "err", err)
5103 }
5104 }
5105 if c.cleanup != nil {
5106 c.cleanup()
5107 }
5108 // Drop the Controller owner reference last so background job leases
5109 // that outlive close still pin retired generations until they exit.
5110 if c.sessionTemp != nil {
5111 c.sessionTemp.Release()
5112 }
5113 if c.persistentShell != nil {
5114 c.persistentShell.Release()
5115 }
5116 c.finishBackgroundReplacement(false)
5117 })
5118 }
5119
5120 // SessionTemp returns the logical-session private temporary directory manager.
5121 // Hot rebuilds pass this to the replacement Controller so the directory survives
5122 // model/settings swaps. Nil only when the Controller was constructed without one
5123 // (should not happen after New).
5124 func (c *Controller) SessionTemp() *sessiontemp.Manager {
5125 if c == nil {
5126 return nil
5127 }
5128 return c.sessionTemp
5129 }
5130
5131 // rotateSessionTemp advances the private temporary generation so a new logical
5132 // session cannot see the previous session's temporary files. In-flight command
5133 // leases keep the old generation alive until they release.
5134 func (c *Controller) rotateSessionTemp() {
5135 if c == nil {
5136 return
5137 }
5138 if c.sessionTemp != nil {
5139 c.sessionTemp.Rotate()
5140 }
5141 if c.persistentShell != nil {
5142 c.persistentShell.Rotate()
5143 }
5144 }
5145
5146 // PersistentShell returns the session-scoped PTY manager. Hot rebuilds pass
5147 // this to the replacement Controller so shell state survives model/settings
5148 // swaps. Nil only when the Controller was constructed without one.
5149 func (c *Controller) PersistentShell() *persistentshell.Manager {
5150 if c == nil {
5151 return nil
5152 }
5153 return c.persistentShell
5154 }
5155
5156 // Jobs returns the still-running background jobs for the status bar (nil when
5157 // background jobs are disabled).
5158 func (c *Controller) Jobs() []jobs.View {
5159 if c.jobs == nil {
5160 return nil
5161 }
5162 return c.jobs.RunningForSession(c.parentSessionID())
5163 }
5164
5165 // KillJob cancels a running background job by ID.
5166 func (c *Controller) KillJob(id string) bool {
5167 if c.jobs == nil {
5168 return false
5169 }
5170 return c.jobs.Kill(id)
5171 }
5172
5173 // TaskRuntimeOwnerID identifies the recorder that admitted this runtime's jobs.
5174 func (c *Controller) TaskRuntimeOwnerID() string {
5175 if c.jobs == nil {
5176 return ""
5177 }
5178 return c.jobs.TaskRuntimeOwnerID()
5179 }
5180
5181 // CancelJob stops one background job owned by this controller's session.
5182 func (c *Controller) CancelJob(id string) bool {
5183 if c.jobs == nil {
5184 return false
5185 }
5186 return c.jobs.KillForSession(c.parentSessionID(), id)
5187 }
5188
5189 // WorkspaceLeaseState reports the process-local held and waiting lease scope.
5190 // Canonical keys are used only for matching another local controller and are
5191 // never copied into user-facing payloads.
5192 func (c *Controller) WorkspaceLeaseState() workspacelease.State {
5193 return c.workspaceLease.State()
5194 }
5195
5196 // WorkspaceLeaseHeldKeys is the lock-domain identity this controller currently
5197 // holds. Empty when no write lease is held.
5198 func (c *Controller) WorkspaceLeaseHeldKeys() []string {
5199 return c.workspaceLease.HeldKeys()
5200 }
5201
5202 // SetToolApprovalMode changes the runtime approval posture for permission-gated
5203 // tools. It does not answer business asks or plan approval. Sub-agents (task,
5204 // writer-capable skill sub-agents, the planner) have no UI to prompt through,
5205 // so this also pushes the mode to the shared headless gate they read from —
5206 // without it, a mode switch (Shift+Tab) would only rebuild the parent
5207 // executor's gate and leave sub-agents pinned to whatever mode was active
5208 // when the session booted.
5209 func (c *Controller) SetToolApprovalMode(mode string) {
5210 c.ApplyToolApprovalMode(mode)
5211 }
5212
5213 // ApplyToolApprovalMode updates the preset without answering an older prompt.
5214 // A real mode change invalidates the active turn and its request IDs, so an
5215 // approval created under an earlier permission revision can never authorize a
5216 // call under the new revision.
5217 func (c *Controller) ApplyToolApprovalMode(mode string) []string {
5218 c.permissionMu.Lock()
5219 defer c.permissionMu.Unlock()
5220 return c.applyToolApprovalModeLocked(mode)
5221 }
5222
5223 func (c *Controller) applyToolApprovalModeLocked(mode string) []string {
5224 mode = normalizeToolApprovalMode(mode)
5225 c.promptResolveMu.Lock()
5226 previousMode := c.approval.mode()
5227 if previousMode == mode {
5228 c.promptResolveMu.Unlock()
5229 return nil
5230 }
5231 c.permissionStateMu.Lock()
5232 pending := c.approval.setMode(mode)
5233 if c.subagentGate != nil {
5234 c.subagentGate.Update(mode)
5235 }
5236 c.refreshInteractiveGate()
5237 // Publish the revision only after every enforcement owner has adopted the
5238 // new mode. promptResolveMu makes this one transaction with approval commit.
5239 c.permissionRevision.Add(1)
5240 c.permissionStateMu.Unlock()
5241 drained := make([]string, 0, len(pending))
5242 for _, p := range pending {
5243 p.reply <- approvalReply{allow: true}
5244 drained = append(drained, p.id)
5245 }
5246 // A change that does not widen the preset invalidates the active turn so an
5247 // older approval never authorizes work the new snapshot forbids. A widening
5248 // revokes nothing the turn holds, so the turn keeps running. Avoid the idle
5249 // Cancel path: it stops an active Goal, and the preset is a separate axis.
5250 upgrade := permissionPresetRank(mode) > permissionPresetRank(previousMode)
5251 turnID, cancelled := "", false
5252 if !upgrade && c.Running() {
5253 turnID, cancelled = c.cancelTurnLocked()
5254 }
5255 c.promptResolveMu.Unlock()
5256 if cancelled {
5257 c.finishCancel(turnID, true)
5258 }
5259 // Processes admitted under a broader preset may outlive their spawning
5260 // turn. Only a downgrade must terminate them; an upgrade does not revoke
5261 // any capability they already held.
5262 if permissionPresetRank(mode) < permissionPresetRank(previousMode) && !c.isBackgroundCandidate() {
5263 for _, job := range c.Jobs() {
5264 c.CancelJob(job.ID)
5265 }
5266 }
5267 c.refreshRuntimeState(event.Event{})
5268 return drained
5269 }
5270
5271 func permissionPresetRank(mode string) int {
5272 switch normalizeToolApprovalMode(mode) {
5273 case ToolApprovalDangerFullAccess:
5274 return 2
5275 case ToolApprovalWorkspaceWrite:
5276 return 1
5277 default:
5278 return 0
5279 }
5280 }
5281
5282 func (c *Controller) ToolApprovalMode() string {
5283 return c.approval.mode()
5284 }
5285
5286 // SetAutoApproveTools is the legacy boolean compatibility binding. Both values
5287 // migrate to the safe workspace preset; full access requires an explicit preset.
5288 func (c *Controller) SetAutoApproveTools(on bool) {
5289 _ = on
5290 c.SetToolApprovalMode(ToolApprovalWorkspaceWrite)
5291 }
5292
5293 // SetBypass is the legacy name for SetAutoApproveTools. Keep it for existing
5294 // desktop/serve bindings and CLI code that still uses the bypass wording.
5295 func (c *Controller) SetBypass(on bool) {
5296 c.SetAutoApproveTools(on)
5297 }
5298
5299 // SetMode is the legacy combined Plan/permission binding. New callers use
5300 // ApplyComposerProfile with an explicit permission preset.
5301 func (c *Controller) SetMode(plan, autoApproveTools bool) {
5302 c.ApplyMode(plan, autoApproveTools)
5303 }
5304
5305 // ApplyMode is the legacy SetMode variant that reports invalidated prompt IDs.
5306 func (c *Controller) ApplyMode(plan, autoApproveTools bool) []string {
5307 c.applyPlanMode(plan)
5308 _ = autoApproveTools
5309 return c.ApplyToolApprovalMode(ToolApprovalWorkspaceWrite)
5310 }
5311
5312 // ApplyComposerProfile publishes the collaboration, approval, and Goal axes as
5313 // one controller operation. The only fallible mutation (durable Goal state)
5314 // commits first, so a persistence failure leaves Plan and approval unchanged.
5315 // Serve serializes this call with turn admission and controller replacement.
5316 func (c *Controller) ApplyComposerProfile(plan bool, toolApprovalMode, goal string) ([]string, error) {
5317 c.permissionMu.Lock()
5318 defer c.permissionMu.Unlock()
5319 return c.applyComposerProfileLocked(plan, toolApprovalMode, goal)
5320 }
5321
5322 // ApplyComposerProfileAt is the revision-checked protocol entry point used by
5323 // desktop and remote clients. It keeps Goal, Plan and permission changes under
5324 // one controller mutation boundary.
5325 func (c *Controller) ApplyComposerProfileAt(plan bool, toolApprovalMode, goal string, expectedPermissionRevision uint64) ([]string, error) {
5326 c.permissionMu.Lock()
5327 defer c.permissionMu.Unlock()
5328 if current := c.permissionRevision.Load(); current != expectedPermissionRevision {
5329 return nil, fmt.Errorf("permission revision changed: have %d, expected %d", current, expectedPermissionRevision)
5330 }
5331 return c.applyComposerProfileLocked(plan, toolApprovalMode, goal)
5332 }
5333
5334 // ApplyComposerProfileAtDurable is the canonical-session protocol entry point.
5335 // The explicit preset reaches durable storage before it changes enforcement.
5336 func (c *Controller) ApplyComposerProfileAtDurable(ctx context.Context, plan bool, toolApprovalMode, goal string, expectedPermissionRevision uint64) ([]string, error) {
5337 c.permissionMu.Lock()
5338 defer c.permissionMu.Unlock()
5339 if current := c.permissionRevision.Load(); current != expectedPermissionRevision {
5340 return nil, fmt.Errorf("permission revision changed: have %d, expected %d", current, expectedPermissionRevision)
5341 }
5342 raw := strings.ToLower(strings.TrimSpace(toolApprovalMode))
5343 if raw != "ask" && raw != "auto" && raw != "yolo" && !permissionpreset.Valid(raw) {
5344 return nil, fmt.Errorf("permission preset must be read-only, workspace-write, or danger-full-access")
5345 }
5346 raw = normalizeToolApprovalMode(raw)
5347 capabilities := platformPermissionCapabilities()
5348 if !slices.Contains(capabilities.SupportedPresets, raw) {
5349 return nil, fmt.Errorf("permission preset %q is unavailable: %s", raw, capabilities.UnavailableReason)
5350 }
5351 _, runtime, exclusive := c.v3Binding()
5352 if !exclusive || runtime == nil {
5353 return nil, session.ErrSessionNotRunning
5354 }
5355 goal = strings.TrimSpace(goal)
5356 if strings.TrimSpace(c.Goal()) != goal {
5357 if err := c.SetGoalDurable(goal); err != nil {
5358 return nil, fmt.Errorf("persist goal state: %w", err)
5359 }
5360 }
5361 if err := c.persistSessionPermissionPreset(ctx, runtime, raw); err != nil {
5362 return c.applyFailedPermissionDowngradeLocked(raw, err)
5363 }
5364 if goal != "" {
5365 plan = false
5366 }
5367 c.applyPlanMode(plan)
5368 return c.applyDurablePermissionPresetLocked(raw), nil
5369 }
5370
5371 func (c *Controller) applyComposerProfileLocked(plan bool, toolApprovalMode, goal string) ([]string, error) {
5372 if raw := strings.ToLower(strings.TrimSpace(toolApprovalMode)); raw != "ask" && raw != "auto" && raw != "yolo" &&
5373 raw != ToolApprovalReadOnly && raw != ToolApprovalWorkspaceWrite && raw != ToolApprovalDangerFullAccess {
5374 return nil, fmt.Errorf("permission preset must be read-only, workspace-write, or danger-full-access")
5375 }
5376 toolApprovalMode = normalizeToolApprovalMode(toolApprovalMode)
5377 goal = strings.TrimSpace(goal)
5378 if strings.TrimSpace(c.Goal()) != goal {
5379 if err := c.SetGoalDurable(goal); err != nil {
5380 return nil, fmt.Errorf("persist goal state: %w", err)
5381 }
5382 }
5383 if goal != "" {
5384 plan = false
5385 }
5386 c.applyPlanMode(plan)
5387 return c.applyToolApprovalModeLocked(toolApprovalMode), nil
5388 }
5389
5390 // AutoApproveTools is the legacy status query for explicit full access.
5391 func (c *Controller) AutoApproveTools() bool {
5392 return c.ToolApprovalMode() == ToolApprovalDangerFullAccess
5393 }
5394
5395 // Bypass is the legacy name for AutoApproveTools.
5396 func (c *Controller) Bypass() bool {
5397 return c.AutoApproveTools()
5398 }
5399
5400 // memory
5401 //
5402 // The memory snapshot, pending standing-doc notes, and write serialization
5403 // live in c.memory (a memoryManager) behind its own locks, off c.mu — so a
5404 // memory-panel save never stalls an approval or status poll. These methods are
5405 // the SessionAPI surface; each is a thin delegation. See memory.go.
5406
5407 // QuickAdd appends a one-line note to the doc-memory file for scope (project
5408 // REASONIX.md by default) — the write side of "#<note>". Returns the file written.
5409 func (c *Controller) QuickAdd(scope memory.Scope, note string) (string, error) {
5410 return c.memory.quickAdd(scope, note)
5411 }
5412
5413 // SaveDoc overwrites a recognized memory doc with body — the save side of the
5414 // desktop panel's in-place editor. Returns the file written.
5415 func (c *Controller) SaveDoc(path, body string) (string, error) {
5416 return c.memory.saveDoc(path, body)
5417 }
5418
5419 // SaveMemory writes an active auto-memory fact and refreshes the in-session
5420 // snapshot. It is the explicit user-confirmed counterpart to the model-owned
5421 // remember tool, used by management surfaces that preview a candidate first.
5422 func (c *Controller) SaveMemory(m memory.Memory) (string, error) {
5423 return c.memory.saveMemory(m)
5424 }
5425
5426 // ForgetMemory removes a saved auto-memory by name — the panel/TUI forget action,
5427 // the manual counterpart to the model's `forget` tool.
5428 func (c *Controller) ForgetMemory(name string) error {
5429 return c.memory.forget(name)
5430 }
5431
5432 // QueueMemory implements memory.Queue: model remember/forget tool results are
5433 // already visible in the current loop, so this refreshes the background snapshot
5434 // that will be published in session-context on the next real user turn.
5435 func (c *Controller) QueueMemory(note string) {
5436 c.memory.queue(note)
5437 }
5438
5439 // ClaimAutoMemoryWrite consumes the one-shot create-only authorization issued
5440 // by gateApprover for a low-risk project fact.
5441 func (c *Controller) ClaimAutoMemoryWrite(args json.RawMessage) bool {
5442 return c.memory.claimAutoRemember(args)
5443 }
5444
5445 func (c *Controller) MemoryRevisions(ref string) []memory.Memory {
5446 return c.memory.revisions(ref)
5447 }
5448
5449 // RestoreMemory restores an older active-memory revision as a new audited
5450 // revision and applies it to the next user turn.
5451 func (c *Controller) RestoreMemory(ref string, revision int) (memory.Memory, error) {
5452 return c.memory.restore(ref, revision)
5453 }
5454
5455 // RestoreArchivedMemory recovers an archived fact as a new audited revision and
5456 // applies it to the next user turn.
5457 func (c *Controller) RestoreArchivedMemory(archivePath string) (memory.Memory, error) {
5458 return c.memory.restoreArchived(archivePath)
5459 }
5460
5461 // Memory returns the loaded memory snapshot (nil when memory is disabled), for
5462 // frontends that surface a memory panel or the /memory command. The returned
5463 // *Set is immutable — mutations go through QuickAdd / SaveDoc.
5464 func (c *Controller) Memory() *memory.Set {
5465 return c.memory.current()
5466 }
5467
5468 // approval bridge (agent gate → events)
5469
5470 // gateApprover adapts the Controller to permission.Approver. It is distinct
5471 // from the public Approve command (different signature, different direction).
5472 type gateApprover struct{ c *Controller }
5473
5474 func (g gateApprover) Approve(ctx context.Context, tool, subject string, args json.RawMessage) (bool, bool, error) {
5475 allow, remember, _, err := g.ApproveWithReason(ctx, tool, subject, args)
5476 return allow, remember, err
5477 }
5478
5479 func (g gateApprover) ApproveWithReason(ctx context.Context, tool, subject string, args json.RawMessage) (bool, bool, string, error) {
5480 return g.approveWithPolicyReason(ctx, tool, subject, args, "")
5481 }
5482
5483 func (g gateApprover) ApproveWithPolicyReason(ctx context.Context, tool, subject string, args json.RawMessage, policyReason string) (bool, bool, string, error) {
5484 return g.approveWithPolicyReason(ctx, tool, subject, args, policyReason)
5485 }
5486
5487 func (g gateApprover) approveWithPolicyReason(ctx context.Context, tool, subject string, args json.RawMessage, policyReason string) (bool, bool, string, error) {
5488 if tool == memoryRememberTool && g.c.allowLowRiskRemember(args) {
5489 return true, false, "", nil
5490 }
5491 subject = approvalDisplaySubject(tool, subject, args)
5492 // Check pre-approval before any prompt or Guardian review. OS sandboxing is
5493 // the authority for nested shell syntax, so pipes, command substitutions and
5494 // inline interpreters follow the same permission decision as other commands.
5495 if g.c.approval.preApproved(tool, subject, args) {
5496 return true, false, "", nil
5497 }
5498 allow, remember, err := g.c.requestApprovalWithReason(ctx, tool, subject, args, policyReason)
5499 return allow, remember, "", err
5500 }
5501
5502 type planModeReadOnlyTrustApprover struct{ c *Controller }
5503
5504 type sandboxEscapeApprover struct{ c *Controller }
5505
5506 func (s sandboxEscapeApprover) ApproveSandboxEscape(ctx context.Context, req sandbox.EscapeRequest) (bool, string, error) {
5507 subject := sandboxEscapeApprovalSubject(req.Command)
5508 reason := sandboxEscapeApprovalReason(req.Reason)
5509 reply, err := s.c.requestFreshApprovalDecision(ctx, SandboxEscapeApprovalTool, subject, req.Args, reason)
5510 if err != nil {
5511 return false, "approval aborted", err
5512 }
5513 if !reply.allow {
5514 return false, i18n.M.SandboxEscapeDeclined, nil
5515 }
5516 if reply.session {
5517 s.c.permissionStateMu.Lock()
5518 s.c.approval.grantSession(SandboxEscapeApprovalTool, subject)
5519 s.c.permissionStateMu.Unlock()
5520 }
5521 return true, "", nil
5522 }
5523
5524 func (s sandboxEscapeApprover) SandboxEscapeSessionAllowed(_ context.Context, req sandbox.EscapeRequest) bool {
5525 return s.c.approval.preApprovedForDecision(SandboxEscapeApprovalTool, sandboxEscapeApprovalSubject(req.Command), nil, true)
5526 }
5527
5528 func sandboxEscapeApprovalSubject(command string) string {
5529 subject := strings.TrimSpace(command)
5530 if subject == "" {
5531 return i18n.M.SandboxEscapeSubjectFallback
5532 }
5533 return i18n.M.SandboxEscapeSubjectPrefix + subject
5534 }
5535
5536 func sandboxEscapeApprovalReason(reason string) string {
5537 reason = strings.TrimSpace(reason)
5538 if reason == "" {
5539 return i18n.M.SandboxEscapeRuntimeReason
5540 }
5541 return reason
5542 }
5543
5544 // managedConfigWriteApprover routes a file tool's Reasonix-managed config write
5545 // through the fresh-human approval prompt (see ManagedConfigWriteApprovalTool).
5546 // A session grant is tool-wide (mirroring sandbox_escape): one "allow for this
5547 // session" covers the rest of the repair flow across the handful of managed
5548 // config files without re-prompting on every incremental edit.
5549 type managedConfigWriteApprover struct{ c *Controller }
5550
5551 func (m managedConfigWriteApprover) ApproveManagedConfigWrite(ctx context.Context, req tool.ConfigWriteRequest) (bool, string, error) {
5552 subject := managedConfigWriteApprovalSubject(req.Path)
5553 args, _ := json.Marshal(map[string]string{"path": req.Path})
5554 reply, err := m.c.requestFreshApprovalDecision(ctx, ManagedConfigWriteApprovalTool, subject, args, i18n.M.ConfigWriteReason)
5555 if err != nil {
5556 return false, "approval aborted", err
5557 }
5558 if !reply.allow {
5559 return false, i18n.M.ConfigWriteDeclined, nil
5560 }
5561 if reply.session {
5562 m.c.permissionStateMu.Lock()
5563 m.c.approval.grantSession(ManagedConfigWriteApprovalTool, subject)
5564 m.c.permissionStateMu.Unlock()
5565 }
5566 return true, "", nil
5567 }
5568
5569 func (m managedConfigWriteApprover) ManagedConfigWriteSessionAllowed(_ context.Context, req tool.ConfigWriteRequest) bool {
5570 return m.c.approval.preApprovedForDecision(ManagedConfigWriteApprovalTool, managedConfigWriteApprovalSubject(req.Path), nil, true)
5571 }
5572
5573 func managedConfigWriteApprovalSubject(path string) string {
5574 return i18n.M.ConfigWriteSubjectPrefix + strings.TrimSpace(path)
5575 }
5576
5577 func (p planModeReadOnlyTrustApprover) CheckPlanModeReadOnlyTrust(ctx context.Context, req agent.PlanModeReadOnlyTrustRequest) (bool, string, error) {
5578 prefix := normalizePlanModeReadOnlyCommandPrefix(req.Prefix)
5579 if prefix == "" {
5580 return false, "missing plan-mode read-only command prefix", nil
5581 }
5582 return p.checkBashReadOnlyCommandTrust(ctx, req, prefix)
5583 }
5584
5585 func (p planModeReadOnlyTrustApprover) checkBashReadOnlyCommandTrust(ctx context.Context, req agent.PlanModeReadOnlyTrustRequest, prefix string) (bool, string, error) {
5586 if p.c.approval.planModeReadOnlyCommandTrusted(prefix) {
5587 return true, "", nil
5588 }
5589 command := strings.TrimSpace(req.Command)
5590 if command == "" {
5591 command = strings.TrimSpace(string(req.Args))
5592 }
5593 subject := fmt.Sprintf(i18n.M.PlanModeBashTrustSubjectFmt, prefix, command)
5594 reason := i18n.M.PlanModeBashTrustReason
5595 reply, err := p.c.requestFreshApprovalDecision(ctx, agent.PlanModeReadOnlyCommandApprovalTool, subject, req.Args, reason)
5596 if err != nil {
5597 return false, "approval aborted", err
5598 }
5599 if !reply.allow {
5600 return false, i18n.M.PlanModeBashTrustDeclined, nil
5601 }
5602 if reply.session {
5603 p.c.permissionStateMu.Lock()
5604 p.c.approval.grantPlanModeReadOnlyCommand(prefix)
5605 p.c.permissionStateMu.Unlock()
5606 }
5607 if reply.persist && p.c.onRememberPlanModeReadOnlyCommand != nil {
5608 p.c.emitPlanModeReadOnlyCommandTrustResult(p.c.onRememberPlanModeReadOnlyCommand(prefix))
5609 p.c.permissionStateMu.Lock()
5610 p.c.approval.grantPlanModeReadOnlyCommand(prefix)
5611 p.c.permissionStateMu.Unlock()
5612 }
5613 return true, "", nil
5614 }
5615
5616 func approvalDisplaySubject(tool, subject string, args json.RawMessage) string {
5617 switch tool {
5618 case memoryRememberTool:
5619 return rememberApprovalSubject(subject, args)
5620 case memoryForgetTool:
5621 return forgetApprovalSubject(subject, args)
5622 case "move_file":
5623 return moveApprovalSubject(subject, args)
5624 default:
5625 return subject
5626 }
5627 }
5628
5629 func moveApprovalSubject(fallback string, args json.RawMessage) string {
5630 if len(args) == 0 {
5631 return fallback
5632 }
5633 var in struct {
5634 SourcePath string `json:"source_path"`
5635 DestinationPath string `json:"destination_path"`
5636 }
5637 if err := json.Unmarshal(args, &in); err != nil {
5638 return fallback
5639 }
5640 if in.SourcePath == "" || in.DestinationPath == "" {
5641 return fallback
5642 }
5643 return in.SourcePath + " -> " + in.DestinationPath
5644 }
5645
5646 func rememberApprovalSubject(fallback string, args json.RawMessage) string {
5647 if len(args) == 0 {
5648 return fallback
5649 }
5650 var in struct {
5651 Name string `json:"name"`
5652 Title string `json:"title"`
5653 Description string `json:"description"`
5654 Type string `json:"type"`
5655 Body string `json:"body"`
5656 }
5657 if err := json.Unmarshal(args, &in); err != nil {
5658 return fallback
5659 }
5660 name := approvalCompactText(firstNonEmpty(in.Name, in.Title))
5661 desc := approvalTruncate(approvalCompactText(in.Description), 180)
5662 body := approvalTruncate(approvalCompactText(in.Body), 240)
5663 typ := string(memory.NormalizeType(in.Type))
5664
5665 var b strings.Builder
5666 b.WriteString(i18n.M.MemoryApprovalSaveUpdate)
5667 baseLen := b.Len()
5668 if name != "" {
5669 fmt.Fprintf(&b, " %q", name)
5670 }
5671 if typ != "" {
5672 fmt.Fprintf(&b, " [%s]", typ)
5673 }
5674 if desc != "" {
5675 b.WriteString(": ")
5676 b.WriteString(desc)
5677 }
5678 if body != "" {
5679 if desc == "" {
5680 b.WriteString(": ")
5681 } else {
5682 b.WriteString(" | ")
5683 }
5684 b.WriteString(i18n.M.MemoryApprovalBodyLabel)
5685 b.WriteString(": ")
5686 b.WriteString(body)
5687 }
5688 if b.Len() == baseLen && fallback != "" {
5689 return fallback
5690 }
5691 return b.String()
5692 }
5693
5694 func forgetApprovalSubject(fallback string, args json.RawMessage) string {
5695 if len(args) == 0 {
5696 return fallback
5697 }
5698 var in struct {
5699 Name string `json:"name"`
5700 }
5701 if err := json.Unmarshal(args, &in); err != nil {
5702 return fallback
5703 }
5704 name := approvalCompactText(in.Name)
5705 if name == "" {
5706 return fallback
5707 }
5708 return fmt.Sprintf(i18n.M.MemoryApprovalArchiveFmt, name)
5709 }
5710
5711 func firstNonEmpty(values ...string) string {
5712 for _, value := range values {
5713 if strings.TrimSpace(value) != "" {
5714 return value
5715 }
5716 }
5717 return ""
5718 }
5719
5720 func approvalCompactText(s string) string {
5721 return strings.Join(strings.Fields(s), " ")
5722 }
5723
5724 func approvalTruncate(s string, maxRunes int) string {
5725 if maxRunes <= 0 {
5726 return ""
5727 }
5728 runes := []rune(s)
5729 if len(runes) <= maxRunes {
5730 return s
5731 }
5732 return string(runes[:maxRunes]) + "..."
5733 }
5734
5735 func (c *Controller) sessionMessageCount() int {
5736 if c.executor == nil {
5737 return 0
5738 }
5739 return c.executor.Session().Len()
5740 }
5741
5742 // parseRewind parses the arguments after "/rewind". The user may provide:
5743 //
5744 // /rewind → latest checkpoint, both
5745 // /rewind <turn> → that turn, both
5746 // /rewind <turn> <scope> → that turn, code|conversation|both
5747 //
5748 // If no turn is given, the latest checkpoint is used. If no scope is given, Both is assumed.
5749 func parseRewind(args string, cps []checkpoint.Meta) (int, RewindScope, error) {
5750 fields := strings.Fields(args)
5751 if len(fields) == 0 {
5752 if len(cps) == 0 {
5753 return 0, RewindBoth, fmt.Errorf("no checkpoints available")
5754 }
5755 return cps[len(cps)-1].Turn, RewindBoth, nil
5756 }
5757 turn, err := strconv.Atoi(fields[0])
5758 if err != nil {
5759 return 0, RewindBoth, fmt.Errorf("invalid turn: %w", err)
5760 }
5761 scope := RewindBoth
5762 if len(fields) >= 2 {
5763 switch strings.ToLower(fields[1]) {
5764 case "code":
5765 scope = RewindCode
5766 case "conversation":
5767 scope = RewindConversation
5768 case "both":
5769 scope = RewindBoth
5770 default:
5771 return 0, RewindBoth, fmt.Errorf("unknown scope %q", fields[1])
5772 }
5773 }
5774 return turn, scope, nil
5775 }
5776
5777 // requestApproval emits an ApprovalRequest and blocks until Approve(ID, …)
5778 // answers or ctx is cancelled. A prior session grant (or a bypass posture) for
5779 // the same approval scope short-circuits. Each prompt waits independently;
5780 // this method keeps the I/O (events, hooks, remember) out of the registry.
5781 func (c *Controller) requestApproval(ctx context.Context, tool, subject string, args json.RawMessage) (bool, bool, error) {
5782 return c.requestApprovalWithReason(ctx, tool, subject, args, "")
5783 }
5784
5785 func (c *Controller) requestApprovalWithReason(ctx context.Context, tool, subject string, args json.RawMessage, reason string) (bool, bool, error) {
5786 return c.requestApprovalWithReasonOptions(ctx, tool, subject, args, reason, approvalDecisionOptions{})
5787 }
5788
5789 func (c *Controller) requestApprovalWithReasonOptions(ctx context.Context, tool, subject string, args json.RawMessage, reason string, opts approvalDecisionOptions) (bool, bool, error) {
5790 r, err := c.requestApprovalDecisionWithOptions(ctx, tool, subject, args, reason, opts)
5791 if err != nil {
5792 return false, false, err
5793 }
5794 // Plan approvals are one-shot — never persist a session grant for them, or
5795 // every future plan would auto-approve.
5796 if r.allow && r.session && !requiresFreshApprovalTool(tool) {
5797 c.permissionStateMu.Lock()
5798 c.approval.grantSession(tool, subject)
5799 c.permissionStateMu.Unlock()
5800 }
5801 if r.allow && r.persist && !requiresFreshApprovalTool(tool) && c.onRemember != nil {
5802 c.emitRememberResult(c.onRemember(permission.RememberRuleForScope(tool, subject)))
5803 }
5804 return r.allow, false, nil
5805 }
5806
5807 func (c *Controller) requestFreshApprovalDecision(ctx context.Context, tool, subject string, args json.RawMessage, reason string) (approvalReply, error) {
5808 return c.requestApprovalDecisionWithOptions(ctx, tool, subject, args, reason, approvalDecisionOptions{fresh: true})
5809 }
5810
5811 type approvalDecisionOptions struct {
5812 // fresh marks a user trust/business decision rather than an ordinary tool
5813 // permission. It may reuse an explicit session grant, but YOLO/auto approval
5814 // must not answer or drain the prompt.
5815 fresh bool
5816 // requireHuman marks an ordinary tool approval that Auto, an approved-plan
5817 // window, Guardian, or an allowing hook must not answer. Unlike fresh it
5818 // retains the ordinary four-choice UI and YOLO remains an explicit bypass.
5819 requireHuman bool
5820 }
5821
5822 func (c *Controller) requestApprovalDecisionWithOptions(ctx context.Context, tool, subject string, args json.RawMessage, reason string, opts approvalDecisionOptions) (approvalReply, error) {
5823 // YOLO/full access and the just-approved-plan execution window auto-allow
5824 // approval-gated tools without prompting. Plan approval is a user decision,
5825 // not a tool permission, so it deliberately stays interactive.
5826 if c.approval.preApprovedForDecisionOptions(tool, subject, args, opts.fresh, opts.requireHuman) {
5827 return approvalReply{allow: true}, nil
5828 }
5829
5830 // Claude's PermissionRequest contract answers the dialog on the plugin's
5831 // behalf (auto-allow/auto-deny) instead of merely observing it, so a
5832 // decision here must preempt the prompt rather than just notify — this
5833 // runs synchronously and before the dialog is shown. Native Reasonix
5834 // PermissionRequest hooks stay advisory-only (see claudePermissionBlocking).
5835 //
5836 // Hook auto-allow cannot replace a fresh-human decision. Interactive
5837 // YOLO may already have skipped remember/forget via preApproved. Deny
5838 // still applies universally — refusing is always safe to honor.
5839 if hookSubject, hookArgs, ok := permissionRequestHookPayload(tool, subject, args); ok {
5840 if decision, _ := c.hooks.PermissionRequest(ctx, tool, hookSubject, hookArgs); decision != nil {
5841 switch {
5842 case !*decision:
5843 return approvalReply{}, nil
5844 case !opts.fresh && !opts.requireHuman && !requiresFreshApprovalTool(tool):
5845 return approvalReply{allow: true}, nil
5846 }
5847 // An "allow" opinion on a fresh-human-required decision is
5848 // ignored; fall through to the normal interactive prompt.
5849 }
5850 }
5851
5852 c.approval.promptEmitMu.Lock()
5853 // Re-check at the publication boundary: a session grant may have landed
5854 // after the initial policy check.
5855 if c.approval.preApprovedForDecisionOptions(tool, subject, args, opts.fresh, opts.requireHuman) {
5856 c.approval.promptEmitMu.Unlock()
5857 return approvalReply{allow: true}, nil
5858 }
5859 var id string
5860 var reply chan approvalReply
5861 kind := ""
5862 if opts.fresh || opts.requireHuman || tool == planApprovalTool {
5863 if tool == planApprovalTool {
5864 kind = "plan"
5865 }
5866 id, reply = c.approval.registerDecisionKindWithInput(tool, subject, reason, args, opts.fresh, opts.requireHuman, kind, nil)
5867 ownerKind := PromptApproval
5868 if kind == "plan" {
5869 ownerKind = PromptPlan
5870 }
5871 c.registerOwnedPrompt(id, ownerKind)
5872 } else {
5873 id, reply = c.approval.registerWithInput(tool, subject, reason, args)
5874 c.registerOwnedPrompt(id, PromptApproval)
5875 }
5876
5877 if err := event.EmitChecked(c.sink, c.approvalRequestEvent(event.Approval{ID: id, Tool: tool, Subject: subject, Reason: reason, RawInput: append(json.RawMessage(nil), args...), Fresh: opts.fresh, Kind: kind})); err != nil {
5878 c.approval.promptEmitMu.Unlock()
5879 c.cancelOwnedPrompt(id)
5880 return approvalReply{}, fmt.Errorf("persist approval request: %w", err)
5881 }
5882 c.approval.promptEmitMu.Unlock()
5883 // The agent now needs the user's attention; a Notification hook can ping an
5884 // external channel (desktop notice, phone) while the run blocks on the reply.
5885 go c.hooks.Notification(ctx, approvalNotificationText(tool, subject), "permission_prompt")
5886
5887 waitCtx, cancelWait := c.approval.waitContext(ctx)
5888 defer cancelWait()
5889
5890 select {
5891 case r := <-reply:
5892 return r, nil
5893 case <-waitCtx.Done():
5894 c.cancelOwnedPrompt(id)
5895 return approvalReply{}, waitCtx.Err()
5896 }
5897 }
5898
5899 func (c *Controller) approvalRequestEvent(approval event.Approval) event.Event {
5900 approval.Generation = c.runtimeGeneration
5901 approval.PermissionRevision = c.permissionRevision.Load()
5902 if approval.TurnID == "" {
5903 approval.TurnID, _, _, _ = c.turnEventRuntimeStatus()
5904 }
5905 _, runtimeEpoch := c.promptIdentitySnapshot()
5906 if identity := c.bindOwnedPromptRouting(approval.ID, approval.TurnID, runtimeEpoch); identity.TurnID != "" {
5907 approval.TurnID = identity.TurnID
5908 }
5909 return event.Event{Kind: event.ApprovalRequest, TurnID: approval.TurnID, ItemID: approval.ID, Approval: approval}
5910 }
5911
5912 func (c *Controller) emitRememberResult(r RememberResult) {
5913 if r.Err != nil {
5914 c.sink.Emit(event.Event{
5915 Kind: event.Notice,
5916 Level: event.LevelWarn,
5917 Text: fmt.Sprintf(i18n.M.PermissionSaveFailedFmt, r.Rule, r.Err),
5918 })
5919 return
5920 }
5921 switch {
5922 case r.Saved:
5923 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: fmt.Sprintf(i18n.M.PermissionSavedFmt, r.Path, r.Rule)})
5924 case strings.TrimSpace(r.CoveredBy) != "":
5925 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: fmt.Sprintf(i18n.M.PermissionAlreadyAllowedFmt, r.Path, r.CoveredBy)})
5926 }
5927 }
5928
5929 func (c *Controller) emitPlanModeReadOnlyCommandTrustResult(r PlanModeReadOnlyCommandTrustResult) {
5930 prefix := strings.TrimSpace(r.Prefix)
5931 if r.Err != nil {
5932 c.sink.Emit(event.Event{
5933 Kind: event.Notice,
5934 Level: event.LevelWarn,
5935 Text: fmt.Sprintf(i18n.M.PlanModeReadOnlyCommandTrustFailedFmt, prefix, r.Err),
5936 })
5937 return
5938 }
5939 switch {
5940 case r.Saved:
5941 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: fmt.Sprintf(i18n.M.PlanModeReadOnlyCommandTrustSavedFmt, r.Path, prefix)})
5942 case strings.TrimSpace(r.CoveredBy) != "":
5943 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: fmt.Sprintf(i18n.M.PlanModeReadOnlyCommandTrustAlreadyFmt, r.Path, r.CoveredBy)})
5944 }
5945 }
5946
5946 lines GO