返回 DeepSeek-Reasonix
agent.go
根目录 / internal / agent / agent.go
1 package agent
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "strings"
9 "sync"
10 "sync/atomic"
11 "time"
12
13 "reasonix/internal/ablation"
14 "reasonix/internal/capability"
15 "reasonix/internal/checkpoint"
16 "reasonix/internal/diff"
17 "reasonix/internal/event"
18 "reasonix/internal/evidence"
19 "reasonix/internal/extension/dispatch"
20 "reasonix/internal/fileops"
21 "reasonix/internal/i18n"
22 "reasonix/internal/imageinput"
23 "reasonix/internal/instruction"
24 "reasonix/internal/jobs"
25 "reasonix/internal/mcpinteraction"
26 "reasonix/internal/memory"
27 "reasonix/internal/nilutil"
28 "reasonix/internal/plancontract"
29 "reasonix/internal/planmode"
30 "reasonix/internal/provider"
31 "reasonix/internal/runtimepolicy"
32 "reasonix/internal/sandbox"
33 "reasonix/internal/sessiontemp"
34 "reasonix/internal/tool"
35 "reasonix/internal/workspacelease"
36 )
37
38 // maxToolOutputBytes bounds the stable provider-visible Content. RawContent
39 // retains the complete local result for explicit session-scoped paging.
40 const maxToolOutputBytes = 32 * 1024
41
42 var deprecatedContextRetentionWarning sync.Once
43
44 const maxEmptyFinalBlocks = 2
45
46 // These bounds cover corrected tool arguments and protocol/context repairs.
47 // Transport failures never replay the failed request automatically.
48 const maxToolArgumentRepairs = 3
49 const maxSamplingAttempts = 4
50
51 // defaultReasoningByteLimit caps stored hidden reasoning for one stream.
52 // It does not cancel generation; official DeepSeek may emit up to 384K tokens.
53 const defaultReasoningByteLimit = 8 << 20
54
55 // DeliveryRuntimeMarker is the delivery-mode contract block appended to user
56 // turns (withTurnPreferences). Exported as the single source of truth for the
57 // byte-exact suffix strip in preview derivation and for cross-package tests;
58 // its text is cache-frozen — changing it breaks steer replay matching and the
59 // prefix stability of every live delivery session.
60 const DeliveryRuntimeMarker = `<delivery-runtime>
61 This session is in delivery-first mode. Use todo_write when a task benefits from
62 an explicit task list, update it from your own assessment, and finish when the
63 user's request is handled. Structured file tools require a current host-observed
64 file version; reading any useful window establishes that observation.
65 </delivery-runtime>`
66
67 // Renderer redraws the assistant's final-answer text as styled output. It is
68 // applied only after a turn's text stream completes, so the user sees raw
69 // markdown stream live, then a single redraw replaces it with formatted
70 // output. The renderer is intentionally interface-shaped so the agent stays
71 // independent of the cli's markdown library choice. Consumed by TextSink.
72 type Renderer interface {
73 Render(text string) string
74 }
75
76 // Asker puts structured multiple-choice questions to the user and blocks for the
77 // answers. The agent consults it for the `ask` tool. It is interface-shaped so
78 // the agent stays independent of the frontend; a nil asker means no interactive
79 // user (headless runs), where `ask` returns a "decide for yourself" result. The
80 // interactive frontends wire the controller in as the Asker.
81 type Asker interface {
82 Ask(ctx context.Context, questions []event.AskQuestion) ([]event.AskAnswer, error)
83 }
84
85 // callContextKey carries the executing tool call's identity into Execute.
86 type callContextKey struct{}
87 type parentSessionContextKey struct{}
88 type subagentDepthContextKey struct{}
89 type userImagesContextKey struct{}
90
91 // callContext is the per-call context a tool can read. parentID is the call being
92 // executed and sink is the agent's event sink (the `task` tool uses both to nest
93 // a sub-agent's events under this call); asker lets the `ask` tool reach the user.
94 type callContext struct {
95 parentID string
96 sink event.Sink
97 asker Asker
98 planMode bool
99 }
100
101 // withCallContext stamps ctx with the executing call's ID, the agent's sink, and
102 // the asker. executeOne sets this before every Execute; `task` reads it (via
103 // CallContext) to nest sub-agent events, and `ask` reads the asker to prompt.
104 // The plan-mode flag is mirrored onto the leaf planmode key so tools that must
105 // not import this package (for example internal/tool/builtin) can still read it.
106 func withCallContext(ctx context.Context, parentID string, sink event.Sink, asker Asker, planMode bool) context.Context {
107 ctx = planmode.WithActive(ctx, planMode)
108 return context.WithValue(ctx, callContextKey{}, callContext{parentID: parentID, sink: sink, asker: asker, planMode: planMode})
109 }
110
111 // WithToolCallContext stamps ctx as a host-initiated top-level tool call.
112 // Normal model-selected tools receive this context from executeOne; controller
113 // entry points that deliberately invoke the same tool machinery (for example a
114 // user typing /<subagent-skill>) use this exported wrapper so nested sub-agent
115 // activity still reaches the parent event stream and plan-mode policy remains
116 // visible to the invoked runner.
117 func WithToolCallContext(ctx context.Context, parentID string, sink event.Sink, asker Asker, planMode bool) context.Context {
118 return withCallContext(ctx, parentID, sink, asker, planMode)
119 }
120
121 // CallContext returns the executing call's ID, the agent's sink, and the asker,
122 // if the context was set by an agent's executeOne. ok is false for a plain
123 // context (headless tool tests, calls made outside the run loop).
124 func CallContext(ctx context.Context) (parentID string, sink event.Sink, asker Asker, ok bool) {
125 cc, ok := ctx.Value(callContextKey{}).(callContext)
126 if !ok {
127 return "", nil, nil, false
128 }
129 return cc.parentID, cc.sink, cc.asker, true
130 }
131
132 // PlanModeFromContext reports whether the tool call is executing during the
133 // plan-first workflow. Tools may use it for phase-specific behavior, but it is
134 // not a permission or read-only boundary.
135 func PlanModeFromContext(ctx context.Context) bool {
136 cc, ok := ctx.Value(callContextKey{}).(callContext)
137 return ok && cc.planMode
138 }
139
140 // withAgentContext establishes the agent-owned workflow capabilities for a
141 // model round and for tool availability checks. Missing capabilities shadow
142 // inherited values so child agents cannot reach parent Goal, Jobs, or memory
143 // state accidentally.
144 func (a *Agent) withAgentContext(ctx context.Context) context.Context {
145 if a == nil {
146 return ctx
147 }
148 if a.svc.jobs != nil {
149 ctx = jobs.WithManager(ctx, a.svc.jobs)
150 } else {
151 ctx = jobs.WithoutManager(ctx)
152 }
153 if a.svc.memQueue != nil {
154 ctx = memory.WithQueue(ctx, a.svc.memQueue)
155 } else {
156 ctx = memory.WithoutQueue(ctx)
157 }
158 return planmode.WithActive(ctx, a.planMode.Load())
159 }
160
161 // WithParentSession stamps the active parent session ID onto a turn context so
162 // persisted sub-agents can record and enforce their owning conversation.
163 func WithParentSession(ctx context.Context, parentSession string) context.Context {
164 return context.WithValue(ctx, parentSessionContextKey{}, strings.TrimSpace(parentSession))
165 }
166
167 // ParentSession returns the active parent session ID carried by a turn context.
168 func ParentSession(ctx context.Context) string {
169 parentSession, _ := ctx.Value(parentSessionContextKey{}).(string)
170 return strings.TrimSpace(parentSession)
171 }
172
173 // WithSubagentDepth carries the current subagent depth through nested tool calls.
174 // The root agent runs at depth 0; each spawned subagent increments by one.
175 func WithSubagentDepth(ctx context.Context, depth int) context.Context {
176 if depth < 0 {
177 depth = 0
178 }
179 return context.WithValue(ctx, subagentDepthContextKey{}, depth)
180 }
181
182 // SubagentDepth returns the current subagent depth carried by a turn context.
183 func SubagentDepth(ctx context.Context) int {
184 depth, _ := ctx.Value(subagentDepthContextKey{}).(int)
185 if depth < 0 {
186 return 0
187 }
188 return depth
189 }
190
191 // WithUserImages carries the data URLs of images the user attached to this turn,
192 // resolved by the controller (which owns attachments) since the agent must not
193 // depend on it. Run embeds them on the user message; the provider sends them only
194 // when the model is vision-capable.
195 func WithUserImages(ctx context.Context, images []string) context.Context {
196 return context.WithValue(ctx, userImagesContextKey{}, images)
197 }
198
199 func userImages(ctx context.Context) []string {
200 images, _ := ctx.Value(userImagesContextKey{}).([]string)
201 return images
202 }
203
204 // Gate decides, per tool call, whether it may run. The agent consults it at
205 // execute time after any explicit planning-phase opt-out. It is interface-shaped so the agent
206 // stays independent of the permission package and of how "ask" is resolved
207 // (silently in headless runs, interactively in the chat TUI). A nil gate means
208 // no gating — every call runs, preserving behaviour for callers that don't wire
209 // one in. reason is fed back to the model when allow is false; a non-nil err
210 // (e.g. ctx cancelled awaiting approval) is treated as a block for that call.
211 type Gate interface {
212 Check(ctx context.Context, toolName string, args json.RawMessage, readOnly bool) (allow bool, reason string, err error)
213 }
214
215 // ExplicitDenyGate exposes the only global permission decision that applies to
216 // an already-authorized MCP server. Installing or approving a server is the
217 // user's authorization boundary; ordinary ask/fallback posture must not add a
218 // second per-call prompt, while explicit deny rules remain authoritative.
219 type ExplicitDenyGate interface {
220 ExplicitlyDenies(toolName string, args json.RawMessage) bool
221 }
222
223 const PlanModeReadOnlyCommandApprovalTool = "plan_mode_read_only_command"
224
225 // PlanModeReadOnlyTrustRequest describes a bash command that is safe enough to
226 // ask the user to accept as read-only during planning. Command is the concrete
227 // attempted command and Prefix is the reusable prefix to trust.
228 type PlanModeReadOnlyTrustRequest struct {
229 ToolName string
230 Command string
231 Prefix string
232 Args json.RawMessage
233 }
234
235 // PlanModeReadOnlyTrustGate is the legacy Plan bash trust bridge. It remains in
236 // the internal API for controller compatibility, but ordinary Plan execution no
237 // longer invokes it; bash calls use the normal permission gate.
238 type PlanModeReadOnlyTrustGate interface {
239 CheckPlanModeReadOnlyTrust(ctx context.Context, req PlanModeReadOnlyTrustRequest) (allow bool, reason string, err error)
240 }
241
242 const DefaultMaxSubagentDepth = 2
243
244 // NormalizeMaxSubagentDepth applies the public config contract: values below 1
245 // preserve the old single-delegation boundary.
246 func NormalizeMaxSubagentDepth(depth int) int {
247 if depth < 1 {
248 return 1
249 }
250 return depth
251 }
252
253 // ToolHooks fires user-configured shell hooks around each tool call. PreToolUse
254 // runs before the call and may block it (block=true; message is the reason fed
255 // back to the model); PostToolUse runs after and only surfaces output to the
256 // user (it can't block). It is interface-shaped so the agent stays independent
257 // of the hook package — a nil hooks field disables hook firing entirely.
258 type ToolHooks interface {
259 PreToolUse(ctx context.Context, name string, args json.RawMessage) (block bool, message string)
260 PostToolUse(ctx context.Context, name string, args json.RawMessage, result string)
261 PostToolUseFailure(ctx context.Context, name string, args json.RawMessage, result string, err error)
262 // PostLLMCall fires after each model turn completes (streaming finishes)
263 // but before reasoning_content is stored. It returns the (possibly
264 // translated) reasoning string — the original when no hook is configured.
265 // HasPostLLMCall reports whether such a hook exists, so the agent keeps
266 // streaming reasoning live when none is wired up.
267 PostLLMCall(ctx context.Context, reasoning string, turn int) string
268 HasPostLLMCall() bool
269 // SubagentStop fires when a `task` sub-agent finishes (foreground). PreCompact
270 // fires just before a compaction pass and returns extra summary guidance (its
271 // hooks' stdout) to fold into the summary prompt; "" when no hook contributes.
272 SubagentStop(ctx context.Context, last string)
273 PreCompact(ctx context.Context, trigger string) string
274 }
275
276 // Agent drives a single task: a Provider, a tool Registry, and a Session wired
277 // into the main loop.
278 type Agent struct {
279 // protocolRunSeq scopes provider-protocol recovery records across runs. It
280 // is unrelated to the retired Auto Guard execution gate.
281 protocolRunSeq atomic.Uint64
282
283 imageInput agentImageInput
284 imageResolver ImageRequestResolver
285 agentConfig
286 // reads groups the run-scoped read registry and its generation: both are
287 // replaced at each run start so cursors from an earlier run never continue.
288 reads readState
289 // fileObservations is the non-persisted, per-agent observation table used by
290 // structured file tools. A new Agent (resume, fork, rollback, or sub-agent)
291 // always starts with an empty table.
292 fileObservations *fileops.Store
293 stragglers runStragglers
294 // svc are the collaborators this agent talks to; see services.go.
295 svc agentServices
296 // sess is the state one conversation owns; SetSession restarts it. See
297 // sessionstate.go.
298 sess sessionRuntime
299 responseLanguage atomic.Value // string: auto|zh|en
300 reasoningLanguage atomic.Value // string: auto|zh|en
301
302 continuationPolicy ContinuationPolicy
303
304 // unwrittenResolve is the resolve watermark a failed state write still owes.
305 // It outlives the conversation, which is why it is not in sessionRuntime.
306 unwrittenResolve unwrittenResolve
307
308 // planMode enables planning workflow instructions and explicit phase opt-outs.
309 // It does not replace the permission or sandbox boundary. The system prompt and
310 // tool list never change with the toggle, preserving the provider-cache prefix.
311 planMode atomic.Bool
312
313 // readOnlyExecution is a construction-time defense for planner/research
314 // agents. Unlike planMode it is not a collaboration toggle: it remains on
315 // for the agent's lifetime and validates proxy calls after resolution.
316 readOnlyExecution bool
317
318 // plannerMCPExecution relaxes the strict read-only MCP boundary for the
319 // two-model Planner only: authorized, non-destructive MCP targets may run
320 // through use_capability even without readOnlyHint. Ordinary writers, bash,
321 // and destructive MCP stay blocked. Strict read-only sub-agents leave this
322 // false and still require readOnlyHint.
323 plannerMCPExecution bool
324
325 // writeWorkspaceRoot is the workspace used to normalize parent write
326 // reservations when writeScheduler is set.
327
328 // steerQueue holds mid-turn guidance admitted while the agent is running.
329 // Entries keep a durable inbox item ID plus a loader so full bodies are not
330 // retained in the agent heap beyond need. Cache miss for the next API call
331 // is unavoidable but limited to one call — the prefix stays stable otherwise.
332 steerMu sync.Mutex
333 steerQueue []steerEntry
334 steerConsumed bool
335 steerUnapplied bool
336 // steerRunActive is true while Run is executing. Steer only queues while
337 // it is set; once the turn's exit flush has drained the queue, later
338 // steers are rejected so the caller can deliver them as a regular turn
339 // instead of leaving them in a queue no loop will ever consume.
340 steerRunActive bool
341
342 // task is the state shared by every Run continuing one delivery scope: the
343 // spend that outlives a single Run and resource limits keyed to the task
344 // rather than the turn. See taskstate.go.
345 task taskRuntime
346
347 planContract *plancontract.Plan // approved plan this turn executes, if any
348
349 // inheritedExec is the writer parent's host execution context.
350 inheritedExec *runtimepolicy.InheritedExecutionContext
351
352 // turn is the state of the Run currently executing; beginRunTurn replaces
353 // it wholesale. See turnruntime.go.
354 turn turnRuntime
355
356 // ablation names the subsystems a benchmark arm switched off. The zero value
357 // is the control arm.
358 ablation ablation.Set
359
360 // pending is what an external caller arms before the next Run; see
361 // turnruntime.go.
362 pending pendingTurn
363
364 // capabilityLedger tracks require/prefer outcomes for this user turn only.
365 // Never serialized into prompts or session state.
366 capabilityLedger *capability.Ledger
367 // capabilityAudit accumulates non-persisted routing/proxy counters.
368 capabilityAudit *capability.Audit
369 // capabilityGate is the turn's gate memory across final-answer retries.
370 capabilityGate capabilityGateState
371
372 // subagentDepth tracks the current agent's nesting depth. maxSubagentDepth
373 // caps delegation; when reached, recursive agent/skill tools are excluded.
374
375 // Context management keeps the canonical transcript immutable and installs
376 // at most one provider-visible checkpoint each time compactRatio is crossed.
377 keepPolicy KeepPolicy
378 strictAlternatingRoles bool // coalesce adjacent user turns on provider request copies
379 // activeTurnCreatedAt identifies the real/synthetic user message that began
380 // the currently running turn. Compaction may rewrite older history while a
381 // tool loop is active, but it must keep this message and everything after it
382 // verbatim so cancellation/crash recovery can retain completed tool pairs.
383 activeTurnCreatedAt atomic.Int64
384 // Pinned revisions are staged after admission and appended with the user turn.
385 pinned pinnedContextRuntime
386 }
387
388 // KeepPolicy is a bitmask controlling which messages are preserved beyond the
389 // recent tail during compaction.
390 type KeepPolicy int
391
392 const (
393 KeepErrors KeepPolicy = 1 << iota
394 KeepUserMarked
395 )
396
397 // SetPlanMode toggles the plan-first workflow flag. Ordinary calls still use
398 // Permissions/Sandbox; only explicit phase opt-outs are refused. The system
399 // prompt and tool schemas stay untouched, while the caller supplies the
400 // model-facing Marker in a user turn.
401 func (a *Agent) SetPlanMode(v bool) { a.planMode.Store(v) }
402
403 // SetTools replaces the agent's tool registry. The next API call picks up the
404 // new tool schema; tools already cached in the provider prefix are unaffected
405 // until the prefix is invalidated. Safe to call between turns.
406 func (a *Agent) SetTools(tools *tool.Registry) {
407 if a == nil {
408 return
409 }
410 a.svc.tools = tools
411 }
412
413 // SetReasoningLanguage updates the visible reasoning language preference for
414 // subsequent user-role messages emitted by this agent.
415 func (a *Agent) SetReasoningLanguage(lang string) {
416 if a == nil {
417 return
418 }
419 a.reasoningLanguage.Store(NormalizeReasoningLanguage(lang))
420 }
421
422 // SetResponseLanguage updates the final-answer language preference for
423 // subsequent user-role messages emitted by this agent.
424 func (a *Agent) SetResponseLanguage(lang string) {
425 if a == nil {
426 return
427 }
428 a.responseLanguage.Store(NormalizeResponseLanguage(lang))
429 }
430
431 // SetGate installs the per-call permission gate. Interactive frontends also use
432 // it to switch approval modes while a turn is running, so readers take an
433 // atomic snapshot through agentServices. nil disables gating.
434 func (a *Agent) SetGate(g Gate) {
435 if nilutil.IsNil(g) {
436 g = nil
437 }
438 a.svc.setGate(g)
439 }
440
441 // SetExtensions installs the extension dispatcher after construction. Boot
442 // uses it because sidecars — and therefore the dispatcher — only exist after
443 // snapshot assembly, which runs after the agent is built. Safe to call before
444 // the run loop starts; nil disables interception.
445 func (a *Agent) SetExtensions(d *dispatch.Dispatcher) {
446 if a == nil {
447 return
448 }
449 a.svc.extensions = d
450 }
451
452 // SetRecoveryGate is retained for source compatibility. Auto Guard is retired,
453 // so no caller can reinstall its execution gates.
454 func (a *Agent) SetRecoveryGate(g RecoveryGate) {
455 }
456
457 // SetRecoveryIdentity sets the agent/task labels used on recovery cards.
458 func (a *Agent) SetRecoveryIdentity(agentID, taskID string) {
459 }
460
461 // RecoveryGate is retained for source compatibility and always returns nil.
462 func (a *Agent) RecoveryGate() RecoveryGate {
463 return nil
464 }
465
466 // SetPlanModeReadOnlyTrustGate retains the legacy confirmation bridge for old
467 // controller/session data. Main Plan execution no longer calls it.
468 func (a *Agent) SetPlanModeReadOnlyTrustGate(g PlanModeReadOnlyTrustGate) {
469 if nilutil.IsNil(g) {
470 g = nil
471 }
472 a.svc.planTrust = g
473 }
474
475 // SetSandboxEscapeApprover installs the optional one-shot approval path used by
476 // the bash tool when an enforced OS sandbox fails to start.
477 func (a *Agent) SetSandboxEscapeApprover(g sandbox.EscapeApprover) {
478 if nilutil.IsNil(g) {
479 g = nil
480 }
481 a.svc.sandboxEscape = g
482 }
483
484 func (a *Agent) withTurnPreferences(input string) string {
485 if a == nil {
486 return input
487 }
488 responseLang := "auto"
489 if v := a.responseLanguage.Load(); v != nil {
490 if s, ok := v.(string); ok {
491 responseLang = s
492 }
493 }
494 input = WithResponseLanguage(input, responseLang)
495
496 lang := "auto"
497 if v := a.reasoningLanguage.Load(); v != nil {
498 if s, ok := v.(string); ok {
499 lang = s
500 }
501 }
502 input = WithReasoningLanguage(input, lang)
503 return input
504 }
505
506 // SetAsker installs the asker the `ask` tool uses to question the user.
507 // Interactive frontends wire one in; headless runs leave it nil.
508 func (a *Agent) SetAsker(as Asker) { a.svc.asker = as }
509
510 // SetInteractionBroker installs the broker that carries MCP server-initiated
511 // elicitations to the user. Headless runs leave it nil so requests cancel.
512 func (a *Agent) SetInteractionBroker(b mcpinteraction.Broker) { a.svc.interactionBroker = b }
513
514 // SetMemoryQueue installs the sink the remember/forget tools use to apply a
515 // memory change in the current session. The controller wires itself in.
516 func (a *Agent) SetMemoryQueue(q memory.Queue) { a.svc.memQueue = q }
517
518 // SetPreEditHook installs the pre-edit snapshot hook (see onPreEdit). The
519 // controller wires it to its per-session checkpoint store; nil disables capture.
520 // Prefer SetMutationObserver for v2 capture (before+after fingerprints).
521 func (a *Agent) SetPreEditHook(fn func(diff.Change)) { a.svc.preEdit = fn }
522
523 // SetMutationObserver installs the unified mutation observer. When set, it
524 // supersedes onPreEdit for capture and also records after-mutation fingerprints.
525 // When a task tool is already registered it inherits the observer for sub-agents.
526 func (a *Agent) SetMutationObserver(obs *checkpoint.MutationObserver) {
527 a.svc.mutationObserver = obs
528 if a.svc.tools == nil || obs == nil {
529 return
530 }
531 if t, ok := a.svc.tools.Get("task"); ok {
532 if task, ok := t.(*TaskTool); ok {
533 task.WithMutationObserver(obs)
534 }
535 }
536 }
537
538 // MutationObserver returns the installed observer (may be nil).
539 func (a *Agent) MutationObserver() *checkpoint.MutationObserver {
540 if a == nil {
541 return nil
542 }
543 return a.svc.mutationObserver
544 }
545
546 // LastUsage returns the most recent per-turn token telemetry the provider
547 // reported (nil if no turn has run yet). The TUI uses it to show a context
548 // gauge alongside the prompt; ContextManager.Prepare owns cache-breaking
549 // maintenance decisions.
550 func (a *Agent) LastUsage() *provider.Usage { return a.sess.output.lastUsage.Load() }
551
552 // SessionCache returns the cumulative cache hit/miss prompt tokens across every
553 // API call this session — the basis for the status line's aggregate hit-rate.
554 func (a *Agent) SessionCache() (hit, miss int) {
555 return int(a.sess.cacheHit.Load()), int(a.sess.cacheMiss.Load())
556 }
557
558 // ContextWindow returns the configured context-window size in tokens. 0
559 // means automatic compaction is disabled for this agent.
560 func (a *Agent) ContextWindow() int { return a.contextWindow }
561
562 // mid-turn steer marker.
563 // MidTurnSteerPrefix marks user messages that were injected mid-turn as
564 // guidance (via Steer). The model sees them as instructions; frontends
565 // display them as a notice, not a regular user bubble.
566 const MidTurnSteerPrefix = "[Mid-turn steer queued by the user. Do not treat this as a new task; use it only as additional guidance for the current task after completing the current step.]"
567
568 func midTurnSteerMessage(text string) string {
569 return MidTurnSteerPrefix + "\n" + text
570 }
571
572 // SteerText checks whether content is a mid-turn steer message and, if so,
573 // returns the original user text without the wrapper prefix. The returned
574 // text preserves the user's exact input — it only strips the prefix and the
575 // "\n" separator that midTurnSteerMessage inserts between the prefix and the
576 // user text; it does not trim spaces so the history replay matches the live
577 // Steer event rendering character-for-character.
578 //
579 // Steers are persisted through withTurnPreferences, which can prepend
580 // transient language blocks (for Chinese text even in auto mode) and append
581 // the delivery-runtime marker. Both are transport framing, not steer text:
582 // leading blocks are skipped before matching the prefix and a trailing
583 // marker is cut from the returned text, so replay recognizes steers
584 // regardless of the session's language and profile settings.
585 func SteerText(content string) (string, bool) {
586 s := content
587 for {
588 if after, found := strings.CutPrefix(s, MidTurnSteerPrefix); found {
589 // Strip only the "\n" separator, preserving the user's original text.
590 after = strings.TrimPrefix(after, "\n")
591 if trimmed, cut := strings.CutSuffix(after, "\n\n"+DeliveryRuntimeMarker); cut {
592 after = trimmed
593 }
594 return after, true
595 }
596 next, ok := trimLeadingSteerWrapper(s)
597 if !ok {
598 return "", false
599 }
600 s = next
601 }
602 }
603
604 // trimLeadingSteerWrapper removes one leading transient preference block that
605 // withTurnPreferences may have placed ahead of the steer prefix. It reports
606 // false when content does not start with such a block.
607 func trimLeadingSteerWrapper(content string) (string, bool) {
608 s := strings.TrimLeft(content, " \t\r\n")
609 for _, tag := range []string{"response-language", "reasoning-language"} {
610 if !strings.HasPrefix(s, "<"+tag+">") {
611 continue
612 }
613 if rest, ok := trimLeadingTransientBlock(s, tag); ok {
614 return rest, true
615 }
616 }
617 return content, false
618 }
619
620 // steerEntry is one mid-turn guidance admission.
621 type steerEntry struct {
622 itemID string
623 load func() (string, error)
624 // text is a fallback when load is nil (legacy Steer(string) path).
625 text string
626 }
627
628 // ErrSteerWithdrawn tells the agent that a durable steer was intentionally
629 // removed by a concurrent user cancellation. It must not be recorded as an
630 // unapplied failure in the transcript.
631 var ErrSteerWithdrawn = errors.New("steer withdrawn")
632
633 // Steer queues a message for mid-turn injection. It reports whether an active
634 // turn accepted the text; on false nothing was queued and the caller must
635 // deliver it another way (typically as a new turn). Without the active check,
636 // a steer landing in the window between the turn's exit flush and the
637 // controller observing running=false would sit in the queue unconsumed and
638 // unpersisted — invisible to both the model and history.
639 func (a *Agent) Steer(text string) bool {
640 return a.SteerItem("", func() (string, error) { return text, nil })
641 }
642
643 // SteerItem queues durable-inbox guidance identified by itemID. load is called
644 // only when the entry is consumed so the agent does not retain every body.
645 func (a *Agent) SteerItem(itemID string, load func() (string, error)) bool {
646 a.steerMu.Lock()
647 defer a.steerMu.Unlock()
648 if !a.steerRunActive {
649 return false
650 }
651 a.steerQueue = append(a.steerQueue, steerEntry{itemID: itemID, load: load})
652 a.steerConsumed = false
653 return true
654 }
655
656 // SteerConsumed returns true when the steer queue became empty after the last consume.
657 func (a *Agent) SteerConsumed() bool {
658 a.steerMu.Lock()
659 defer a.steerMu.Unlock()
660 return a.steerConsumed
661 }
662
663 // HasUnappliedSteer reports whether the last Run ended with user guidance that
664 // arrived too late to be consumed. Hosts use it to yield before starting an
665 // automatic synthetic continuation.
666 func (a *Agent) HasUnappliedSteer() bool {
667 a.steerMu.Lock()
668 defer a.steerMu.Unlock()
669 return a.steerUnapplied
670 }
671
672 // SetSink replaces the agent's event sink. Controllers use this to wrap the
673 // sink after construction (e.g. durable inbox observation) without rebuilding
674 // the agent.
675 func (a *Agent) SetSink(sink event.Sink) {
676 if a == nil {
677 return
678 }
679 if nilutil.IsNil(sink) {
680 sink = event.Discard
681 }
682 a.svc.sink = sink
683 }
684
685 func (a *Agent) consumeSteer() (text, itemID string, ok bool) {
686 a.steerMu.Lock()
687 defer a.steerMu.Unlock()
688 if len(a.steerQueue) == 0 {
689 return "", "", false
690 }
691 e := a.steerQueue[0]
692 a.steerQueue = a.steerQueue[1:]
693 a.steerConsumed = len(a.steerQueue) == 0
694 if e.load != nil {
695 t, err := e.load()
696 if err != nil {
697 if errors.Is(err, ErrSteerWithdrawn) {
698 return "", "", false
699 }
700 return "", e.itemID, false
701 }
702 return t, e.itemID, true
703 }
704 return e.text, e.itemID, true
705 }
706
707 // closeSteerIntakeIfIdle atomically closes the normal-completion race between
708 // the final queue check and Run returning. A steer accepted before this check
709 // keeps the loop alive; one arriving after it is rejected so the host can keep
710 // the user's draft and retry it as a regular follow-up.
711 func (a *Agent) closeSteerIntakeIfIdle() bool {
712 a.steerMu.Lock()
713 defer a.steerMu.Unlock()
714 if len(a.steerQueue) > 0 {
715 return false
716 }
717 a.steerRunActive = false
718 return true
719 }
720
721 // flushSteerQueue ends the turn's steer intake. Guidance that arrived too late
722 // to be consumed is persisted for transcript visibility but marked local-only:
723 // replaying it to the model on the next unrelated user turn can execute a stale
724 // historical task (#7045). An explicit warning keeps the transcript honest
725 // without presenting the text as successfully applied guidance (#6238).
726 func (a *Agent) flushSteerQueue() {
727 a.steerMu.Lock()
728 pending := a.steerQueue
729 a.steerQueue = nil
730 a.steerUnapplied = false
731 if len(pending) > 0 {
732 a.steerConsumed = true
733 }
734 a.steerRunActive = false
735 a.steerMu.Unlock()
736 unapplied := false
737 for _, e := range pending {
738 text := e.text
739 if e.load != nil {
740 if t, err := e.load(); errors.Is(err, ErrSteerWithdrawn) {
741 continue
742 } else if err == nil {
743 text = t
744 }
745 }
746 a.RecordUnappliedSteer(text, e.itemID)
747 unapplied = true
748 }
749 a.steerMu.Lock()
750 a.steerUnapplied = unapplied
751 a.steerMu.Unlock()
752 }
753
754 func (a *Agent) steerQueueLen() int {
755 a.steerMu.Lock()
756 defer a.steerMu.Unlock()
757 return len(a.steerQueue)
758 }
759
760 // CompactNow forces one projection compaction (canonical transcript untouched).
761 func (a *Agent) CompactNow(ctx context.Context, instructions string) error {
762 _, err := a.contextManager().Prepare(ctx, ContextPreparePolicy{
763 Trigger: CompactionTriggerManual,
764 Instructions: instructions,
765 Force: true,
766 AllowChunkedFallback: true,
767 })
768 return err
769 }
770
771 // Options configures an Agent.
772 type Options struct {
773 ImageInput *imageinput.Config
774 ImageRequestResolver ImageRequestResolver
775 MaxSteps int
776 // MaxStepsKey names the explicit runtime control shown when the MaxSteps guard
777 // is hit. Empty defaults to the generic max_steps tool/runtime parameter.
778 MaxStepsKey string
779 // ReasoningByteLimit bounds a single stream's hidden reasoning bytes. Zero
780 // uses the default guard; a negative value disables only this client guard.
781 // Provider output budgets are a separate protocol/model capability.
782 ReasoningByteLimit int
783 // MaxOutputTokens overrides the provider's configured/default total output
784 // budget. Zero delegates to the provider; a negative value asks optional
785 // protocols to omit the budget (Anthropic still requires max_tokens).
786 MaxOutputTokens int
787 Temperature float64
788 // TaskBudget bounds a task's spend; zero uses DefaultTaskBudget.
789 TaskBudget TaskBudget
790 Pricing *provider.Pricing // optional, for per-turn cost display
791 // QuoteContext is shared with the host CostQuote sink so budget accounting
792 // and emitted usage consume the exact same occurrence-time quote.
793 QuoteContext *event.QuoteContext
794 UsageSource string // optional billable usage source; default executor
795 // ModelRef names the canonical "provider/model" ref backing this agent's
796 // provider instance. It is attached to emitted Usage events so downstream
797 // usage accounting can attribute tokens to the exact model.
798 ModelRef string
799 // RequireVisibleFinal is retained for source compatibility. All callers now
800 // reject terminal responses without an answer or a structured finalizer.
801 RequireVisibleFinal bool
802 // ContinuationPolicy is the internal host policy for synthetic same-Run
803 // continuation. The zero value (ContinuationDisabled) is the product default.
804 ContinuationPolicy ContinuationPolicy
805 // Gate is the per-call permission gate. nil disables gating.
806 Gate Gate
807 // ReadOnlyExecution enables a permanent host-side read-only boundary for
808 // planner and research agents. It is intentionally independent of Plan mode
809 // so a stale collaboration flag cannot authorize a dynamic writer target.
810 ReadOnlyExecution bool
811 // PlannerMCPExecution enables Planner-trusted MCP through use_capability:
812 // authorized, non-destructive tools may run without readOnlyHint. Only
813 // NewPlannerAgent sets this; strict read-only sub-agents must not.
814 PlannerMCPExecution bool
815
816 // PlanModeReadOnlyTrustGate is retained for legacy controller compatibility.
817 // The main Plan execution path no longer invokes it.
818 PlanModeReadOnlyTrustGate PlanModeReadOnlyTrustGate
819
820 // SandboxEscapeApprover confirms a one-shot unconfined shell rerun after an
821 // enforced OS sandbox fails. nil keeps fail-closed behavior.
822 SandboxEscapeApprover sandbox.EscapeApprover
823
824 // ConfigWriteApprover confirms file-tool writes to Reasonix-managed config
825 // files outside the workspace roots. nil keeps fail-closed behavior.
826 ConfigWriteApprover tool.ConfigWriteApprover
827
828 // Context management. ContextWindow <= 0 disables automatic compaction. Ratios and
829 // RecentKeep fall back to defaults when unset.
830 ContextWindow int
831 CompactRatio float64
832 // CompactRatioSource must be concurrency-safe; root/planner decisions stay live.
833 CompactRatioSource func() float64
834 // Deprecated compatibility inputs. New agents ignore these fields; automatic
835 // maintenance is controlled only by CompactRatio.
836 SoftCompactRatio float64
837 ToolResultSnipRatio float64
838 CompactForceRatio float64
839 RecentKeep int
840 ArchiveDir string
841 KeepPolicy KeepPolicy
842 SessionPath string // projection sidecar path; empty = memory only
843 WorkspaceID string // prompt-cache lineage component
844 StrictAlternatingRoles bool // merge adjacent user turns for strict providers at request time
845 ContextEditing string // deprecated; native provider editing was removed
846
847 // Hooks fires PreToolUse / PostToolUse shell hooks around tool calls. nil
848 // disables hook firing.
849 Hooks ToolHooks
850
851 // MissingReasoningWarnStateDir, when non-empty, points at the shared
852 // directory where missing tool-call thinking recovery retries are gated by
853 // opaque provider-configuration fingerprint (#7059). The field name is kept
854 // for source compatibility. Boot always supplies it; direct construction
855 // with an empty value keeps in-memory gating.
856 MissingReasoningWarnStateDir string
857
858 // Jobs is the session's background-job manager (nil disables background tools).
859 Jobs *jobs.Manager
860 // MemoryQueue optionally gives a child agent an explicitly owned live-memory
861 // queue. When nil, child construction shadows inherited queues.
862 MemoryQueue memory.Queue
863
864 // WriteScheduler is the session-scoped subagent concurrency/write-claim
865 // controller. When set on the parent executor, write-capable tools reserve
866 // paths for the duration of Execute so background writers cannot TOCTOU
867 // race parent writes. Subagents leave this nil (or depth > 0 skips it).
868 WriteScheduler *SubagentScheduler
869 // WriteWorkspaceRoot normalizes parent write reservations.
870 WriteWorkspaceRoot string
871 // SessionTemp owns the exact private scratch root for delivery accounting.
872 SessionTemp *sessiontemp.Manager
873 // WriteRoots is the session-scoped writable directory manager.
874 WriteRoots *sandbox.WritableRootSet
875 // WriteAccessGate authorizes extra writable directories. nil is fail-closed
876 // for missing dirs when WriteRoots is set.
877 WriteAccessGate WriteAccessGate
878 // DisableWriteAccessExpand prevents this agent from requesting new write
879 // directories. Sub-agents set this.
880 DisableWriteAccessExpand bool
881 // HomeDir and StateRoot are used to normalize and reject write directories.
882 HomeDir string
883 StateRoot string
884
885 // WorkspaceLease serializes writer mutations across sessions that target
886 // the same workspace. nil preserves source compatibility for direct Agent
887 // construction; boot always supplies it for writer-capable sessions.
888 WorkspaceLease *workspacelease.Owner
889
890 // ProjectChecks is a retired compatibility option. Project instructions
891 // remain in normal model context and are not compiled into host obligations.
892 ProjectChecks []instruction.VerifyCheck
893
894 // InheritedExecution is the writer parent's host execution context.
895 InheritedExecution *runtimepolicy.InheritedExecutionContext
896
897 // Ablation switches subsystems off for a benchmark arm. The zero value runs
898 // everything, so ordinary callers leave it unset.
899 Ablation ablation.Set
900
901 // ClassifierTaskText, when non-empty, is the pristine task text, set by
902 // sub-agent spawners before host framing is prepended. Delivery intent
903 // classification judges it instead of the raw Run input, so framing verbs
904 // cannot arm expectations; the delegation audit scores evidence origin
905 // against it, so only locations the parent wrote itself count as hints.
906 ClassifierTaskText string
907
908 // CapabilityLedger is the optional turn-scoped capability route ledger for
909 // Delivery require/prefer gates. Nil disables capability gates.
910 CapabilityLedger *capability.Ledger
911 // CapabilityAudit is the optional non-persisted metrics sink for routing.
912 CapabilityAudit *capability.Audit
913
914 // RequireReviewReportKind is a retired compatibility field. Subagents return
915 // their ordinary final answer without a proof tool.
916 RequireReviewReportKind evidence.ReviewKind
917
918 // ReasoningLanguage controls visible reasoning language preference as transient
919 // user-turn context. Empty/auto injects nothing.
920 ReasoningLanguage string
921
922 // ResponseLanguage controls final-answer language preference as transient
923 // user-turn context. Empty/auto keeps the stable same-as-user policy.
924 ResponseLanguage string
925
926 // PlanModeReadOnlyCommands is retained for old config/controller data. Main
927 // Plan execution classifies bash through Permissions instead.
928 PlanModeReadOnlyCommands []string
929
930 // RecoveryGate and the identity fields are retired compatibility inputs.
931 // Agent construction ignores them.
932 RecoveryGate RecoveryGate
933 // RecoveryAgentID labels this agent on recovery cards (empty = root).
934 RecoveryAgentID string
935 // RecoveryTaskID isolates recovery state for this agent (empty = root task).
936 RecoveryTaskID string
937
938 // SubagentDepth is the current nesting depth for this agent. Root sessions are
939 // depth 0; child subagents are depth 1. MaxSubagentDepth caps delegation.
940 SubagentDepth int
941 MaxSubagentDepth int
942
943 // Extensions is the frozen extension dispatcher for this agent's controller
944 // generation (Extension Protocol v2). Nil means no runtime packages are
945 // installed; the run loop then passes every intercept point through
946 // byte-identically. Boot installs it with SetExtensions once sidecars are
947 // live (they start after the agent is constructed).
948 Extensions *dispatch.Dispatcher
949
950 // MutationObserver is the host-side file mutation observer shared with
951 // (or cloned for) sub-agents. nil disables v2 capture. Does not affect
952 // provider-visible tool schemas or prompts.
953 MutationObserver *checkpoint.MutationObserver
954
955 // SessionCheckpointer flushes the accepted session event prefix at semantic
956 // boundaries before model and top-level tool side effects.
957 SessionCheckpointer SessionCheckpointer
958 }
959
960 // New constructs an Agent. MaxSteps <= 0 means no cap — the run loop continues
961 // until the model gives a final answer, the context is cancelled, or the
962 // provider errors (compaction keeps the context bounded). A nil sink is replaced
963 // with event.Discard so the agent can always emit unconditionally.
964 func New(prov provider.Provider, tools *tool.Registry, session *Session, opts Options, sink event.Sink) *Agent {
965 warnDeprecatedRetention := deprecatedContextRetentionConfigured(opts)
966 if opts.CompactRatio <= 0 {
967 opts.CompactRatio = defaultCompactRatio
968 }
969 if opts.RecentKeep <= 0 {
970 opts.RecentKeep = minRecentKeep
971 }
972 if nilutil.IsNil(sink) {
973 sink = event.Discard
974 }
975 gate := opts.Gate
976 if nilutil.IsNil(gate) {
977 gate = nil
978 }
979 planModeReadOnlyTrust := opts.PlanModeReadOnlyTrustGate
980 if nilutil.IsNil(planModeReadOnlyTrust) {
981 planModeReadOnlyTrust = nil
982 }
983 sandboxEscapeApprover := opts.SandboxEscapeApprover
984 if nilutil.IsNil(sandboxEscapeApprover) {
985 sandboxEscapeApprover = nil
986 }
987 configWriteApprover := opts.ConfigWriteApprover
988 if nilutil.IsNil(configWriteApprover) {
989 configWriteApprover = nil
990 }
991 hooks := opts.Hooks
992 if nilutil.IsNil(hooks) {
993 hooks = nil
994 }
995 maxStepsKey := opts.MaxStepsKey
996 if strings.TrimSpace(maxStepsKey) == "" {
997 maxStepsKey = "max_steps"
998 }
999 maxSubagentDepth := opts.MaxSubagentDepth
1000 if maxSubagentDepth == 0 {
1001 maxSubagentDepth = DefaultMaxSubagentDepth
1002 } else {
1003 maxSubagentDepth = NormalizeMaxSubagentDepth(maxSubagentDepth)
1004 }
1005 subagentDepth := max(opts.SubagentDepth, 0)
1006 reasoningByteLimit := opts.ReasoningByteLimit
1007 if reasoningByteLimit == 0 {
1008 reasoningByteLimit = defaultReasoningByteLimit
1009 }
1010 a := &Agent{
1011 imageInput: newImageInput(opts.ImageInput, prov),
1012 imageResolver: opts.ImageRequestResolver,
1013 svc: newAgentServices(prov, tools, sink, gate, planModeReadOnlyTrust,
1014 sandboxEscapeApprover, configWriteApprover, hooks, opts),
1015 reads: readState{},
1016 fileObservations: fileops.NewStore(),
1017 agentConfig: agentConfig{
1018 maxSteps: opts.MaxSteps,
1019 maxStepsKey: maxStepsKey,
1020 reasoningByteLimit: reasoningByteLimit,
1021 maxOutputTokens: opts.MaxOutputTokens,
1022 temperature: opts.Temperature,
1023 usageSource: usageSourceOrDefault(opts.UsageSource, event.UsageSourceExecutor),
1024 modelRef: strings.TrimSpace(opts.ModelRef),
1025 workspaceID: strings.TrimSpace(opts.WorkspaceID),
1026 classifierTaskText: opts.ClassifierTaskText,
1027 writeWorkspaceRoot: strings.TrimSpace(opts.WriteWorkspaceRoot),
1028 subagentDepth: subagentDepth,
1029 maxSubagentDepth: maxSubagentDepth,
1030 contextWindow: opts.ContextWindow,
1031 compactRatio: opts.CompactRatio,
1032 compactRatioSource: opts.CompactRatioSource,
1033 recentKeep: opts.RecentKeep,
1034 archiveDir: opts.ArchiveDir,
1035 },
1036 sess: sessionRuntime{
1037 conversation: session,
1038 path: strings.TrimSpace(opts.SessionPath),
1039 cacheState: CacheStateUnknown,
1040 },
1041 task: taskRuntime{
1042 ledger: evidence.NewLedger(),
1043 budget: runBudget{limit: normalizeTaskBudget(opts.TaskBudget)},
1044 },
1045 continuationPolicy: opts.ContinuationPolicy,
1046 readOnlyExecution: opts.ReadOnlyExecution,
1047 plannerMCPExecution: opts.PlannerMCPExecution,
1048 inheritedExec: opts.InheritedExecution,
1049 ablation: opts.Ablation,
1050 capabilityLedger: opts.CapabilityLedger,
1051 capabilityAudit: opts.CapabilityAudit,
1052 keepPolicy: opts.KeepPolicy,
1053 strictAlternatingRoles: opts.StrictAlternatingRoles,
1054 }
1055 a.sess.output.outputBudget = outputBudgetOf(prov)
1056 if a.sess.path != "" {
1057 a.LoadProjectionSidecar(a.sess.path)
1058 }
1059 a.SetResponseLanguage(opts.ResponseLanguage)
1060 a.SetReasoningLanguage(opts.ReasoningLanguage)
1061 a.bindCapabilityObservers()
1062 a.maybeArmForkFromEnv()
1063 a.maybeWrapForkCaptureProvider()
1064 if warnDeprecatedRetention {
1065 deprecatedContextRetentionWarning.Do(func() {
1066 a.svc.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn,
1067 Text: i18n.M.DeprecatedContextRetention,
1068 Detail: "Harness-style compaction now retains only the newest 16% of the context window; legacy retention fields are preserved in configuration but ignored at runtime."})
1069 })
1070 }
1071 return a
1072 }
1073
1074 func deprecatedContextRetentionConfigured(opts Options) bool {
1075 recentNonDefault := opts.RecentKeep > 0 && opts.RecentKeep != minRecentKeep
1076 defaultKeepPolicy := KeepErrors | KeepUserMarked
1077 keepNonDefault := opts.KeepPolicy != 0 && opts.KeepPolicy != KeepErrors && opts.KeepPolicy != defaultKeepPolicy
1078 return recentNonDefault || keepNonDefault
1079 }
1080
1081 // closedLoopActive reports whether the current (or most recent) turn must
1082 // close the evidence loop. It replaces every historical deliveryProfile gate:
1083 // acceptance criteria before mutations, todo ownership, opaque-bash limits,
1084 // capability call preference, post-write verification, review, and sign-off.
1085 // It is authoritative only for host control flow, never for tool schemas.
1086 func (a *Agent) closedLoopActive() bool {
1087 return a != nil && a.turn.deliveryScopeActive
1088 }
1089
1090 func usageSourceOrDefault(source, fallback string) string {
1091 source = strings.TrimSpace(source)
1092 if source != "" {
1093 return source
1094 }
1095 return fallback
1096 }
1097
1098 // missingReasoningWarnStateFor returns nil when no state dir is configured, so
1099 // direct Agent construction keeps the historical once-per-session notice scope.
1100 func missingReasoningWarnStateFor(dir string) *missingReasoningWarnState {
1101 if strings.TrimSpace(dir) == "" {
1102 return nil
1103 }
1104 return newMissingReasoningWarnState(dir)
1105 }
1106
1107 // reserveParentWrite holds write claims for the duration of a parent-agent
1108 // write tool call. Returns a no-op release when reservation is not needed
1109 // (subagent, read-only, no scheduler, or non-write tool).
1110 func (a *Agent) reserveParentWrite(runTool tool.Tool, args json.RawMessage, readOnly bool) (release func(), err error) {
1111 noop := func() {}
1112 if a == nil || a.svc.writeScheduler == nil || a.subagentDepth > 0 || readOnly || runTool == nil {
1113 return noop, nil
1114 }
1115 name := runTool.Name()
1116 if !parentWriteGuardTarget(name) {
1117 return noop, nil
1118 }
1119 claim, err := parentWriteReservation(a.writeWorkspaceRoot, name, args)
1120 if err != nil {
1121 return noop, err
1122 }
1123 return a.svc.writeScheduler.ReserveParentWrite(claim)
1124 }
1125
1126 // Run appends the user input and drives the tool loop until the model returns a
1127 // final answer, the context is cancelled, or the provider errors. maxSteps <= 0
1128 // leaves the loop unbounded here: bounding it is the host's call, and the
1129 // adaptive stop is the no-progress ladder rather than a round count. Turn policy
1130 // lives in beginRunTurn / runToolLoop / handleFinalResponse / handleToolRound.
1131 func (a *Agent) Run(ctx context.Context, input string) (runErr error) {
1132 defer a.finishRunRecovery(&runErr)
1133 if err := a.prepareProtocolRecovery(ctx); err != nil {
1134 return err
1135 }
1136 a.restoreProtocolProjection()
1137 ctx = a.withProviderCacheSession(ctx)
1138 runMaxSteps := a.maxSteps
1139 runMaxStepsKey := a.maxStepsKey
1140 a.protocolRunSeq.Add(1)
1141 // Participate in the run lease; per-tool write leases end with execution.
1142 if a.svc.workspaceLease != nil {
1143 a.svc.workspaceLease.BeginRun()
1144 defer a.svc.workspaceLease.EndRun()
1145 }
1146 turnStartedAt := time.Now()
1147 workDurationMs := func() int64 {
1148 if elapsed := time.Since(turnStartedAt).Milliseconds(); elapsed > 0 {
1149 return elapsed
1150 }
1151 return 1
1152 }
1153 defer a.flushSteerQueue()
1154 a.steerMu.Lock()
1155 a.steerConsumed = false
1156 a.steerUnapplied = false
1157 a.steerRunActive = true
1158 a.steerMu.Unlock()
1159
1160 // Commit background-job evidence leases only after this turn delivers.
1161 // job_output (and replay-only wait/bash_output aliases) merges a finished background writer's receipts into the
1162 // ledger provisionally; if the turn reaches a final answer (runErr == nil)
1163 // the delivery gates have verified and reviewed those mutations, so the
1164 // job's evidence can be permanently drained. A failed or cancelled turn
1165 // leaves the lease uncommitted so the next turn re-collects it.
1166 defer func() {
1167 if runErr != nil || a.task.ledger == nil || a.svc.jobs == nil {
1168 return
1169 }
1170 for _, lease := range a.task.ledger.BackgroundLeases() {
1171 a.svc.jobs.CommitEvidenceForSession(lease.Session, lease.JobID)
1172 }
1173 }()
1174 if _, scoped := DeliveryExecutionScopeFromContext(ctx); scoped {
1175 defer func() { a.updateDeliveryCheckpoint(runErr) }()
1176 }
1177 defer a.activeTurnCreatedAt.Store(0)
1178
1179 // agent.before_start: an extension may abort the run before the user turn
1180 // is appended. The redacted reason surfaces like a normal run error.
1181 if err := a.interceptAgentStart(ctx); err != nil {
1182 a.discardStagedPinnedContext()
1183 return err
1184 }
1185
1186 pinned, err := a.preparePinnedRevision()
1187 if err != nil {
1188 return err
1189 }
1190 _, state, err := a.beginRunTurn(ctx, input, pinned)
1191 if err != nil {
1192 return err
1193 }
1194 if a.pending.forkRestore != nil {
1195 a.pending.forkRestore(state)
1196 }
1197 state.runMaxSteps = runMaxSteps
1198 state.runMaxStepsKey = runMaxStepsKey
1199 state.workDurationMs = workDurationMs
1200 ctx = runtimepolicy.WithContext(ctx, a.turn.constraints)
1201 ctx = runtimepolicy.WithInherited(ctx, runtimepolicy.InheritedExecutionContext{
1202 Constraints: a.turn.constraints,
1203 PlanReadOnly: a.planMode.Load() || a.readOnlyExecution,
1204 GoalScopeID: a.task.scopeID,
1205 })
1206 return a.runToolLoop(ctx, state)
1207 }
1208
1209 // ReadinessResult is the host-consumable outcome of the Delivery final-answer
1210 // readiness check. The Controller reads it after each Goal/approved-Plan turn;
1211 // plain Standard turns end after the visible answer and do not enter the Goal
1212 // continuation path.
1213 type ReadinessResult struct {
1214 // Ready is true when no missing requirement remains.
1215 Ready bool
1216 // Missing lists stable category ids of the missing requirements
1217 // (project_check, todo, criteria, verification, review, signoff, action,
1218 // mutation, capability). Empty when Ready.
1219 Missing []string
1220 // Reason is the user-facing summary of what is still missing.
1221 Reason string
1222 // ProgressKey is the host-verifiable progress signature of the current
1223 // evidence state. Identical ProgressKey across consecutive goal turns
1224 // means no host-observable progress was made.
1225 ProgressKey string
1226 }
1227
1228 // ReadinessResult returns the current final-readiness outcome for the host.
1229 func (a *Agent) ReadinessResult() ReadinessResult {
1230 // Compatibility query only: quality assessments are no longer execution
1231 // conditions. Historical missing checks remain in their original records.
1232 return ReadinessResult{Ready: true}
1233 }
1234
1235 // DeliveryCheckpoint returns the compact Goal-scoped delivery state. It is safe
1236 // to persist next to the Goal sidecar because it contains no raw arguments.
1237 func (a *Agent) DeliveryCheckpoint() evidence.DeliveryCheckpoint {
1238 return a.task.checkpoint
1239 }
1240
1241 // RestoreDeliveryCheckpoint seeds a rebuilt controller before its next Goal
1242 // run. A mismatched/empty scope is ignored conservatively.
1243 func (a *Agent) RestoreDeliveryCheckpoint(checkpoint evidence.DeliveryCheckpoint) {
1244 checkpoint.ScopeID = strings.TrimSpace(checkpoint.ScopeID)
1245 if checkpoint.ScopeID == "" {
1246 return
1247 }
1248 a.task.checkpoint = checkpoint
1249 a.task.scopeID = checkpoint.ScopeID
1250 }
1251
1252 func (a *Agent) updateDeliveryCheckpoint(runErr error) {
1253 if !a.turn.deliveryScopeActive || a.task.scopeID == "" || a.task.ledger == nil {
1254 return
1255 }
1256 cp := a.task.checkpoint
1257 if cp.ScopeID != a.task.scopeID {
1258 cp = evidence.DeliveryCheckpoint{ScopeID: a.task.scopeID}
1259 }
1260 cp.WorkObserved = cp.WorkObserved || a.task.ledger.HasSuccessfulWorkReceipt()
1261 if _, ok := a.task.ledger.LatestSuccessfulMutationIndex(); ok {
1262 cp.MutationObserved = true
1263 }
1264 if a.task.ledger.HasSuccessfulToolReceipt("remember") && !a.task.ledger.HasSuccessfulMutationOtherThan("remember") {
1265 cp.MutationObserved = true
1266 }
1267 a.task.checkpoint = cp
1268 }
1269
1270 func (a *Agent) setTodoState(todos []evidence.TodoItem) {
1271 a.sess.todoMu.Lock()
1272 a.sess.todoState = append([]evidence.TodoItem(nil), todos...)
1273 a.sess.todoWritten = true
1274 a.sess.todoMu.Unlock()
1275 }
1276
1277 func executorHandoffRetryMessage() string {
1278 return `You are already in the executor phase. The planner's read-only limitations do not apply to you.
1279
1280 The tool schema is still attached to this executor request. Do not invent that MCP servers or tools are unavailable; only report an unavailable tool after a real tool call or host error proves it.
1281
1282 Do not answer as the planner and do not ask how to trigger the executor.
1283 Use your available tools now to carry out the task. If carrying out the planner's instructions requires a user-owned choice or review, call the ask tool with concrete options and wait for its tool result; do not ask in prose, and do not claim the user answered unless an actual ask tool result or a new user message says so. If a write or command is blocked by permissions or workspace boundaries, state that specific blocker and ask for the needed approval/path.`
1284 }
1285
1286 func hasVisibleFinalAnswer(text string) bool {
1287 return strings.TrimSpace(text) != ""
1288 }
1289
1290 func emptyFinalRetryMessage() string {
1291 return "The previous assistant response finished without any visible answer text. Continue the same task from the recorded results: call the available tools if work remains, or provide a concise visible answer. Do not repeat completed actions or send reasoning only."
1292 }
1293
1294 func emptyFinalNotice() string {
1295 return i18n.M.EmptyFinal
1296 }
1297
1298 func emptyFinalNoticeDetail(prov string, u *provider.Usage, reasoningLen int) string {
1299 finish := "unknown"
1300 if u != nil && u.FinishReason != "" {
1301 finish = u.FinishReason
1302 }
1303 return fmt.Sprintf("empty final answer blocked: %s returned no visible answer text (finish=%s, reasoning=%d chars); retrying", prov, finish, reasoningLen)
1304 }
1305
1306 func toolBudgetNoticeText() string {
1307 return i18n.M.ToolBudget
1308 }
1309
1310 // stream runs one completion, emitting reasoning and text deltas as typed
1311 // events and collecting complete tool calls. A Message event closes the text
1312 // stream so a sink can re-render the streamed raw text as styled markdown. The
1313 // accumulated text and reasoning are also returned so the caller can round-trip
1314 // reasoning on the next turn.
1315 //
1316 // When frozen is non-nil, the request is not rebuilt from session — retries
1317 // must replay the same provider-visible body.
1318 func (a *Agent) stream(ctx context.Context, turn int, sink event.Sink) streamedTurn {
1319 return a.streamWithFrozen(ctx, turn, sink, nil, "")
1320 }
1321
1322 func (a *Agent) streamWithFrozen(ctx context.Context, turn int, sink event.Sink, frozen *samplingRequest, attemptID string) streamedTurn {
1323 // Reuse a parent counter so protocol/context repair requests accumulate into
1324 // one RequestCount; otherwise install a fresh counter for this call.
1325 ctx = provider.WithRequestAttemptCounter(ctx)
1326 // A stream can terminate locally before the provider channel closes (for
1327 // example when the client-side reasoning guard fires). Own a child context
1328 // here so every return path aborts the HTTP request and releases the provider
1329 // reader instead of leaving generation and billing running in the background.
1330 ctx, cancel := context.WithCancel(ctx)
1331 defer cancel()
1332
1333 var req provider.Request
1334 var err error
1335 if frozen != nil {
1336 req = freezeProviderRequest(frozen.req)
1337 } else {
1338 prepared, perr := a.prepareSamplingRequest(ctx)
1339 if perr != nil {
1340 return streamedTurn{err: perr}
1341 }
1342 req = prepared.req
1343 }
1344 // Host stream cancels on generation drain (OpenAI/Anthropic HTTP reads).
1345 defer trackPublishedHostStream(ctx, cancel)()
1346 ch, err := a.streamProviderRequest(ctx, req)
1347 if err != nil {
1348 return streamedTurn{usage: provider.UsageWithRequestAttemptCount(ctx, nil), err: err}
1349 }
1350
1351 // A PostLLMCall hook rewrites the whole reasoning block, so when one is wired
1352 // up we buffer reasoning silently and emit the transformed text once after the
1353 // stream. With no such hook the reasoning streams live, chunk by chunk, as
1354 // before — the common case must not lose its live "thinking…" display.
1355 transformReasoning := a.svc.hooks != nil && a.svc.hooks.HasPostLLMCall()
1356
1357 var text, reasoning strings.Builder
1358 meta := reasoningStreamMeta{complete: true}
1359 var calls []provider.ToolCall
1360 var responsesItems []json.RawMessage
1361 search := newSearchTurn()
1362 var partialCalls []provider.ToolCall
1363 var usage *provider.Usage
1364 var partialToolStarted bool
1365 var maxArgChars int
1366 var lastArgProgress time.Time
1367 // collect packages the stream state accumulated so far; stored is the
1368 // finishReasoning output that becomes the round-tripped reasoning.
1369 collect := func(stored string, err error) streamedTurn {
1370 return streamedTurn{
1371 text: text.String(), reasoning: stored, signature: meta.signature,
1372 reasoningID: meta.id, reasoningStatus: meta.status, reasoningComplete: meta.complete,
1373 reasoningState: meta.state, thinkingBlocks: meta.blocks,
1374 calls: calls, responsesItems: responsesItems, serverSearch: search.calls, usage: usage,
1375 partialToolStarted: partialToolStarted, partialCalls: partialCalls,
1376 maxArgChars: maxArgChars, err: err,
1377 }
1378 }
1379 finishReasoning := func() (stored, display string) {
1380 original := reasoning.String()
1381 display = original
1382 if transformReasoning && original != "" {
1383 display = a.svc.hooks.PostLLMCall(ctx, original, turn)
1384 if display != "" {
1385 sink.Emit(event.Event{Kind: event.Reasoning, Text: display})
1386 }
1387 }
1388 stored = display
1389 if a.preserveRawReasoning(original, meta.signature, meta.id, meta.status, calls, search.calls) {
1390 stored = original
1391 }
1392 return stored, display
1393 }
1394 for {
1395 var chunk provider.Chunk
1396 // Cancellation wins over already buffered provider tokens.
1397 if ctx.Err() != nil {
1398 stored, _ := finishReasoning()
1399 usage = provider.UsageWithRequestAttemptCount(ctx, bestEffortStreamUsage(usage, text.Len(), reasoning.Len(), "interrupted"))
1400 return collect(stored, ctx.Err())
1401 }
1402 select {
1403 case <-ctx.Done():
1404 stored, _ := finishReasoning()
1405 usage = bestEffortStreamUsage(usage, text.Len(), reasoning.Len(), "interrupted")
1406 usage = provider.UsageWithRequestAttemptCount(ctx, usage)
1407 return collect(stored, ctx.Err())
1408 case c, ok := <-ch:
1409 if !ok {
1410 if err := ctx.Err(); err != nil {
1411 stored, _ := finishReasoning()
1412 usage = bestEffortStreamUsage(usage, text.Len(), reasoning.Len(), "interrupted")
1413 usage = provider.UsageWithRequestAttemptCount(ctx, usage)
1414 return collect(stored, err)
1415 }
1416 stored, display := finishReasoning()
1417 // provider.response: extensions rule on the assembled terminal
1418 // response before it is persisted. A replacement becomes the
1419 // visible assistant turn (the user's transcript); a block fails
1420 // the turn.
1421 providerSignature := meta.signature
1422 finalText, finalReasoning, finalSignature, calls, usage, err := a.interceptProviderResponse(
1423 ctx, text.String(), stored, meta.signature, calls, usage)
1424 if err != nil {
1425 return streamedTurn{partialToolStarted: partialToolStarted, partialCalls: partialCalls, maxArgChars: maxArgChars, err: err}
1426 }
1427 // Responses reasoning IDs/status and Anthropic signatures are
1428 // provider-bound metadata. Never attach the provider's metadata
1429 // to reasoning that an extension replaced.
1430 if finalReasoning != stored || finalSignature != providerSignature {
1431 meta.id, meta.status = "", ""
1432 meta.blocks = nil
1433 responsesItems = provider.WithoutResponsesReasoning(responsesItems)
1434 }
1435 if finalReasoning != stored {
1436 // The extension replaced the reasoning: what is persisted
1437 // and what the closing Message event re-renders must agree.
1438 display = finalReasoning
1439 }
1440 usage = provider.UsageWithRequestAttemptCount(ctx, usage)
1441 // A clean terminal never reports partialToolStarted: the calls
1442 // slice is now authoritative and the partial cards were merged.
1443 return streamedTurn{
1444 displayReasoning: display,
1445 text: finalText, reasoning: finalReasoning, signature: finalSignature,
1446 reasoningID: meta.id, reasoningStatus: meta.status,
1447 reasoningComplete: meta.complete,
1448 reasoningState: meta.state, thinkingBlocks: meta.blocks,
1449 calls: calls, responsesItems: responsesItems, serverSearch: search.calls, usage: usage,
1450 partialCalls: partialCalls, maxArgChars: maxArgChars,
1451 }
1452 }
1453 chunk = c
1454 }
1455 switch chunk.Type {
1456 case provider.ChunkReasoning:
1457 meta.ingest(chunk, &reasoning, a.reasoningByteLimit)
1458 if chunk.Text != "" && !transformReasoning {
1459 sink.Emit(event.Event{Kind: event.Reasoning, Text: chunk.Text})
1460 }
1461 case provider.ChunkText:
1462 text.WriteString(chunk.Text)
1463 sink.Emit(event.Event{Kind: event.Text, Text: chunk.Text})
1464 case provider.ChunkToolCallStart:
1465 partialToolStarted = true
1466 // Surface the tool card as soon as the call begins — before its
1467 // (possibly large) arguments finish streaming — so the user sees it
1468 // working instead of a stall. executeBatch emits the full dispatch
1469 // (with args) once the call completes; the frontend merges by ID.
1470 if tc := chunk.ToolCall; tc != nil {
1471 partialCalls = upsertPartialToolCall(partialCalls, *tc)
1472 sink.Emit(event.Event{Kind: event.ToolDispatch, Tool: event.Tool{
1473 ID: tc.ID, Name: tc.Name, ReadOnly: a.toolReadOnly(tc.Name), Partial: true, AttemptID: attemptID,
1474 }})
1475 }
1476 case provider.ChunkToolCallArgsDelta:
1477 partialToolStarted = true
1478 // Liveness ticks while a large argument payload streams: re-emit the
1479 // partial dispatch with the cumulative size (time-throttled) so the
1480 // UI can show progress instead of a dead counter for the duration of
1481 // a 30KB write_file body.
1482 if chunk.ArgChars > maxArgChars {
1483 maxArgChars = chunk.ArgChars
1484 }
1485 if tc := chunk.ToolCall; tc != nil && time.Since(lastArgProgress) >= 250*time.Millisecond {
1486 partialCalls = upsertPartialToolCall(partialCalls, *tc)
1487 lastArgProgress = time.Now()
1488 sink.Emit(event.Event{Kind: event.ToolDispatch, Tool: event.Tool{
1489 ID: tc.ID, Name: tc.Name, ReadOnly: a.toolReadOnly(tc.Name), Partial: true, ArgChars: chunk.ArgChars, AttemptID: attemptID,
1490 }})
1491 }
1492 case provider.ChunkToolCall:
1493 partialToolStarted = true
1494 if chunk.ToolCall != nil {
1495 calls = append(calls, *chunk.ToolCall)
1496 partialCalls = upsertPartialToolCall(partialCalls, *chunk.ToolCall)
1497 if n := len(chunk.ToolCall.Arguments); n > maxArgChars {
1498 maxArgChars = n
1499 }
1500 }
1501 case provider.ChunkResponsesItem:
1502 responsesItems = meta.ingestResponsesItem(responsesItems, chunk.ResponsesItem, a.reasoningByteLimit)
1503 case provider.ChunkServerSearch:
1504 search.onChunk(sink, chunk, attemptID)
1505 case provider.ChunkUsage:
1506 usage, a.turn.lastReasoning = chunk.Usage, chunk.Usage.ReasoningTokens
1507 a.storeLatestRequestUsage(chunk.Usage)
1508 a.sess.cacheHit.Add(int64(chunk.Usage.CacheHitTokens))
1509 a.sess.cacheMiss.Add(int64(chunk.Usage.CacheMissTokens))
1510 case provider.ChunkError:
1511 if provider.IsStreamInterrupted(chunk.Err) {
1512 stored, _ := finishReasoning()
1513 usage = bestEffortStreamUsage(usage, text.Len(), reasoning.Len(), "interrupted")
1514 usage = provider.UsageWithRequestAttemptCount(ctx, usage)
1515 st := collect(stored, chunk.Err)
1516 st.interrupted = true
1517 return st
1518 }
1519 stored, _ := finishReasoning()
1520 if errors.Is(chunk.Err, context.Canceled) || errors.Is(chunk.Err, context.DeadlineExceeded) {
1521 usage = bestEffortStreamUsage(usage, text.Len(), reasoning.Len(), "interrupted")
1522 }
1523 usage = provider.UsageWithRequestAttemptCount(ctx, usage)
1524 return collect(stored, chunk.Err)
1525 }
1526 }
1527 }
1528
1529 func boundReasoningReplay(reasoning *strings.Builder, latest string, byteLimit int, complete bool) bool {
1530 if byteLimit <= 0 || reasoning.Len() <= byteLimit {
1531 return complete
1532 }
1533 reasoning.Reset()
1534 reasoning.WriteString(snapToRuneBoundary(latest, 0, min(len(latest), byteLimit)))
1535 return false
1536 }
1537
1538 func bestEffortStreamUsage(current *provider.Usage, textBytes, reasoningBytes int, finishReason string) *provider.Usage {
1539 if current == nil && textBytes == 0 && reasoningBytes == 0 {
1540 return nil
1541 }
1542 var usage provider.Usage
1543 usage.Unknown = current == nil
1544 if current != nil {
1545 usage = *current
1546 }
1547 if finishReason != "" {
1548 usage.FinishReason = finishReason
1549 }
1550 reasoningTokens := estimateTokensFromBytes(reasoningBytes)
1551 textTokens := estimateTokensFromBytes(textBytes)
1552 completionTokens := reasoningTokens + textTokens
1553 if usage.ReasoningTokens < reasoningTokens {
1554 usage.ReasoningTokens = reasoningTokens
1555 usage.Estimated = true
1556 }
1557 if usage.CompletionTokens < completionTokens {
1558 usage.CompletionTokens = completionTokens
1559 usage.Estimated = true
1560 }
1561 if minTotal := usage.PromptTokens + usage.CompletionTokens; usage.TotalTokens < minTotal {
1562 usage.TotalTokens = minTotal
1563 usage.Estimated = true
1564 }
1565 return &usage
1566 }
1567
1568 func estimateTokensFromBytes(n int) int {
1569 if n <= 0 {
1570 return 0
1571 }
1572 tokens := n / 4
1573 if n%4 != 0 {
1574 tokens++
1575 }
1576 if tokens <= 0 {
1577 return 1
1578 }
1579 return tokens
1580 }
1581
1582 func upsertPartialToolCall(calls []provider.ToolCall, call provider.ToolCall) []provider.ToolCall {
1583 for i := range calls {
1584 if call.ID != "" && calls[i].ID == call.ID {
1585 calls[i] = call
1586 return calls
1587 }
1588 }
1589 return append(calls, call)
1590 }
1591
1592 func (a *Agent) capturePrefixShape(schemas []provider.ToolSchema) PrefixShape {
1593 return captureTurnContextShape(a.systemPrompt(), schemas, a.sess.conversation.RewriteVersion(), a.modelVisibleMessages())
1594 }
1595
1596 func (a *Agent) systemPrompt() string {
1597 var b strings.Builder
1598 for _, m := range a.sess.conversation.Messages {
1599 if m.Role != provider.RoleSystem {
1600 continue
1601 }
1602 if b.Len() > 0 {
1603 b.WriteByte('\n')
1604 }
1605 b.WriteString(m.Content)
1606 }
1607 return b.String()
1608 }
1609
1610 func toEventShellExecution(in *tool.ShellExecution, durationMs int64) *event.ShellExecution {
1611 if in == nil {
1612 return nil
1613 }
1614 out := &event.ShellExecution{
1615 Kind: in.Kind,
1616 Shell: in.Shell,
1617 ShellVersion: in.ShellVersion,
1618 Platform: in.Platform,
1619 SupportsAndAnd: in.SupportsAndAnd,
1620 State: in.State,
1621 FailurePhase: in.FailurePhase,
1622 OutputTail: in.OutputTail,
1623 MutationRisk: in.MutationRisk,
1624 Verification: in.Verification,
1625 DurationMs: in.DurationMs,
1626 }
1627 if out.DurationMs == 0 && durationMs > 0 {
1628 out.DurationMs = durationMs
1629 }
1630 if in.ExitCode != nil {
1631 code := *in.ExitCode
1632 out.ExitCode = &code
1633 }
1634 return out
1635 }
1636
1637 func toProviderToolExecution(in *tool.ShellExecution) *provider.ToolExecution {
1638 if in == nil {
1639 return nil
1640 }
1641 out := &provider.ToolExecution{
1642 Kind: in.Kind,
1643 Shell: in.Shell,
1644 ShellVersion: in.ShellVersion,
1645 Platform: in.Platform,
1646 SupportsAndAnd: in.SupportsAndAnd,
1647 State: in.State,
1648 FailurePhase: in.FailurePhase,
1649 OutputTail: in.OutputTail,
1650 MutationRisk: in.MutationRisk,
1651 Verification: in.Verification,
1652 DurationMs: in.DurationMs,
1653 }
1654 if in.ExitCode != nil {
1655 code := *in.ExitCode
1656 out.ExitCode = &code
1657 }
1658 return out
1659 }
1660
1661 func (a *Agent) emitFullToolDispatch(ctx context.Context, c provider.ToolCall, refreshed bool) error {
1662 t, _, ambiguous := a.svc.tools.ResolveCall(c.Name)
1663 ok := t != nil && len(ambiguous) == 0
1664 ev := event.Tool{ID: c.ID, Name: c.Name, Args: c.Arguments, ReadOnly: ok && t.ReadOnly(), Refreshed: refreshed, RunState: provider.ToolRunPending}
1665 ev.FileDiff = event.FileDiff{Diff: c.Diff, Added: c.Added, Removed: c.Removed}
1666 if ok && ev.Diff == "" && ev.Added == 0 && ev.Removed == 0 {
1667 if ch, ok := tool.PreviewChange(ctx, t, json.RawMessage(c.Arguments)); ok {
1668 ev.FileDiff = event.FileDiff{Diff: ch.Diff, Added: ch.Added, Removed: ch.Removed}
1669 }
1670 }
1671 if ok {
1672 if pr, ok := t.(interface {
1673 ResolveProfile(json.RawMessage) *event.Profile
1674 }); ok {
1675 ev.Profile = pr.ResolveProfile(json.RawMessage(c.Arguments))
1676 }
1677 }
1678 return event.EmitChecked(a.svc.sink, event.Event{Kind: event.ToolDispatch, MessageID: messageIdentity(ctx), Tool: ev})
1679 }
1680
1681 // emitResolvedToolDispatch upserts the real target classification of a stable
1682 // proxy call without changing the provider-visible Name/Args. Append-only sinks
1683 // ignore Refreshed events; stateful frontends replace the existing card by ID.
1684 func (a *Agent) emitResolvedToolDispatch(ctx context.Context, c provider.ToolCall) {
1685 if c.ResolvedReadOnly == nil {
1686 return
1687 }
1688 if c.ResolvedName != "" && c.ResolvedName != c.Name {
1689 EmitProxyAudit(a.svc.sink, tool.ResolvedCall{
1690 DisplayName: c.Name,
1691 TargetName: c.ResolvedName,
1692 CapabilityID: c.CapabilityID,
1693 }, c.ID)
1694 }
1695 a.svc.sink.Emit(event.Event{Kind: event.ToolDispatch, MessageID: messageIdentity(ctx), Tool: event.Tool{
1696 ID: c.ID,
1697 Name: c.Name,
1698 Args: c.Arguments,
1699 ResolvedName: c.ResolvedName,
1700 CapabilityID: c.CapabilityID,
1701 ReadOnly: *c.ResolvedReadOnly,
1702 Refreshed: true,
1703 FileDiff: event.FileDiff{
1704 Diff: c.Diff, Added: c.Added, Removed: c.Removed,
1705 },
1706 }})
1707 }
1708
1709 // refreshCurrentFileDiff recomputes a writer preview against the state left by
1710 // earlier successful writers in the same provider batch. Preview failures clear
1711 // any stale initial diff; a later Execute will then fail or ask for recovery
1712 // without presenting the user with a preview that no longer describes disk.
1713 func refreshCurrentFileDiff(ctx context.Context, t tool.Tool, call provider.ToolCall) (provider.ToolCall, bool) {
1714 pv, ok := t.(tool.Previewer)
1715 if !ok {
1716 return call, false
1717 }
1718 refreshed := call
1719 refreshed.Diff = ""
1720 refreshed.Added = 0
1721 refreshed.Removed = 0
1722 if change, err := pv.Preview(ctx, json.RawMessage(call.Arguments)); err == nil {
1723 refreshed.Diff = change.Diff
1724 refreshed.Added = change.Added
1725 refreshed.Removed = change.Removed
1726 }
1727 changed := refreshed.Diff != call.Diff || refreshed.Added != call.Added || refreshed.Removed != call.Removed
1728 return refreshed, changed
1729 }
1730
1731 func (a *Agent) withPreviewFileDiffs(ctx context.Context, calls []provider.ToolCall) []provider.ToolCall {
1732 if len(calls) == 0 {
1733 return calls
1734 }
1735 out := make([]provider.ToolCall, len(calls))
1736 copy(out, calls)
1737 for i := range out {
1738 if out[i].Diff != "" || out[i].Added != 0 || out[i].Removed != 0 {
1739 continue
1740 }
1741 t, _, ambiguous := a.svc.tools.ResolveCall(out[i].Name)
1742 ok := t != nil && len(ambiguous) == 0
1743 if !ok {
1744 continue
1745 }
1746 if ch, ok := tool.PreviewChange(ctx, t, json.RawMessage(out[i].Arguments)); ok {
1747 out[i].Diff = ch.Diff
1748 out[i].Added = ch.Added
1749 out[i].Removed = ch.Removed
1750 }
1751 }
1752 return out
1753 }
1754
1755 // completedMCPConnect recognizes a synthetic cache-miss connect call whose
1756 // background discovery finished after the provider request was serialized. The
1757 // connect placeholder is intentionally absent once real tools replace it, but
1758 // the already-advertised call still completed its only job and must not surface
1759 // as an unknown tool.
1760 func completedMCPConnect(reg *tool.Registry, name string) (string, bool) {
1761 server, rawName, ok := tool.SplitMCPName(name)
1762 if !ok || rawName != "connect" {
1763 return "", false
1764 }
1765 prefix := tool.MCPNamePrefix + server + "__"
1766 for _, current := range reg.Names() {
1767 if current != name && strings.HasPrefix(current, prefix) {
1768 return server, true
1769 }
1770 }
1771 return "", false
1772 }
1773
1774 func (a *Agent) readOnlyExecutionBlock(visible tool.Tool, resolved *tool.ResolvedCall) (toolOutcome, bool) {
1775 if a == nil || !a.readOnlyExecution {
1776 return toolOutcome{}, false
1777 }
1778 block := func(reason string) (toolOutcome, bool) {
1779 return toolOutcome{
1780 output: "blocked: read-only agent cannot " + reason,
1781 blocked: true,
1782 errMsg: "blocked by read-only execution boundary",
1783 }, true
1784 }
1785 // Destructive MCP is left for the Executor; Planner must not misread this
1786 // as missing configuration or an unavailable MCP server.
1787 blockDestructiveForExecutor := func(name string) (toolOutcome, bool) {
1788 msg := "blocked: MCP capability " + name + " is destructive and is reserved for the Executor. Write the required operation into the plan/handoff so the Coordinator can hand it to the Executor; do not treat this as missing MCP configuration or an unavailable capability."
1789 return toolOutcome{
1790 output: msg,
1791 blocked: true,
1792 errMsg: "blocked: destructive MCP reserved for executor",
1793 }, true
1794 }
1795 if resolved == nil {
1796 if a.plannerMCPExecution && isMCPExecutionTarget(visible, "") {
1797 if !mcpServerAuthorized(visible) {
1798 return block("execute an MCP capability from an unauthorized server")
1799 }
1800 if readOnlyExecutionMCPDestructive(visible) {
1801 return blockDestructiveForExecutor(visible.Name())
1802 }
1803 return toolOutcome{}, false
1804 }
1805 if visible == nil || !visible.ReadOnly() {
1806 if reasoner, ok := visible.(tool.ReadOnlyExecutionBlockReason); ok && strings.TrimSpace(reasoner.ReadOnlyExecutionBlockReason()) != "" {
1807 return block(reasoner.ReadOnlyExecutionBlockReason())
1808 }
1809 return block("execute a state-changing tool")
1810 }
1811 if isInstalledMCPTool(visible) && !mcpServerAuthorized(visible) {
1812 return block("execute a reader from an unauthorized MCP server")
1813 }
1814 if readOnlyExecutionMCPDestructive(visible) {
1815 return block("execute a destructive MCP capability")
1816 }
1817 if h, ok := visible.(tool.ReadOnlyExecutionHostMutation); ok && h.ReadOnlyExecutionHostMutation() && !readOnlyExecutionAllowsMCPStartup(visible) {
1818 return block("start or mutate a host capability")
1819 }
1820 return toolOutcome{}, false
1821 }
1822
1823 switch resolved.ProxyAction {
1824 case "list", "inspect":
1825 if !resolved.SkipExecute || resolved.Target != nil || !resolved.ReadOnly {
1826 return block("execute a malformed dynamic inspection")
1827 }
1828 return toolOutcome{}, false
1829 case "decline":
1830 return block("decline a capability decision")
1831 case "call":
1832 if resolved.Target == nil {
1833 if a.plannerMCPExecution && resolved.HostCompleted && resolved.SkipExecute && resolved.ReadOnly && !resolved.Unavailable {
1834 if _, ok := parseMCPServerCapabilityID(resolved.CapabilityID); ok {
1835 return toolOutcome{}, false
1836 }
1837 }
1838 return block("execute an unresolved dynamic capability")
1839 }
1840 if a.plannerMCPExecution && plannerAllowsMCPTarget(resolved.Target, resolved.TargetName) {
1841 if isMCPLifecycleConnectTarget(resolved.Target) {
1842 if !plannerMCPConnectAllowed(resolved.Target) {
1843 return block("start an unauthorized MCP server")
1844 }
1845 } else if !mcpServerAuthorized(resolved.Target) {
1846 return block("execute an MCP capability from an unauthorized server")
1847 }
1848 if readOnlyExecutionMCPDestructive(resolved.Target) {
1849 name := resolved.TargetName
1850 if name == "" {
1851 name = resolved.CapabilityID
1852 }
1853 return blockDestructiveForExecutor(name)
1854 }
1855 return toolOutcome{}, false
1856 }
1857 if !resolved.ReadOnly {
1858 if reasoner, ok := resolved.Target.(tool.ReadOnlyExecutionBlockReason); ok && strings.TrimSpace(reasoner.ReadOnlyExecutionBlockReason()) != "" {
1859 return block(reasoner.ReadOnlyExecutionBlockReason())
1860 }
1861 return block("execute a state-changing dynamic capability")
1862 }
1863 if isInstalledMCPTool(resolved.Target) && !mcpServerAuthorized(resolved.Target) {
1864 return block("execute a dynamic reader from an unauthorized MCP server")
1865 }
1866 if readOnlyExecutionMCPDestructive(resolved.Target) {
1867 return block("execute a destructive MCP capability")
1868 }
1869 if h, ok := resolved.Target.(tool.ReadOnlyExecutionHostMutation); ok && h.ReadOnlyExecutionHostMutation() && !readOnlyExecutionAllowsMCPStartup(resolved.Target) {
1870 return block("start or mutate a host capability")
1871 }
1872 return toolOutcome{}, false
1873 default:
1874 return block("execute an unknown dynamic capability action")
1875 }
1876 }
1877
1878 func readOnlyExecutionMCPDestructive(t tool.Tool) bool {
1879 return mcpDestructiveHint(t)
1880 }
1881
1882 func readOnlyExecutionAllowsMCPStartup(t tool.Tool) bool {
1883 if t == nil || !t.ReadOnly() || readOnlyExecutionMCPDestructive(t) {
1884 return false
1885 }
1886 if !mcpServerAuthorized(t) {
1887 return false
1888 }
1889 meta, ok := t.(tool.MCPMetadata)
1890 if !ok || strings.TrimSpace(meta.MCPServerName()) == "" || strings.TrimSpace(meta.MCPRawToolName()) == "" {
1891 return false
1892 }
1893 return true
1894 }
1895
1896 // plannerAllowsMCPTarget reports whether a resolved use_capability target is an
1897 // MCP tool or lifecycle connect that Planner may consider under
1898 // PlannerMCPExecution (authorization and destructive checks run separately).
1899 func plannerAllowsMCPTarget(t tool.Tool, targetName string) bool {
1900 if t == nil {
1901 return false
1902 }
1903 if isInstalledMCPTool(t) || isMCPLifecycleConnectTarget(t) {
1904 return true
1905 }
1906 return isMCPExecutionTarget(t, targetName)
1907 }
1908
1909 // isMCPLifecycleConnectTarget identifies on-demand MCP connect-and-list targets
1910 // (mcp_connect__<server>) used by use_capability action=call on mcp-server ids.
1911 func isMCPLifecycleConnectTarget(t tool.Tool) bool {
1912 if t == nil {
1913 return false
1914 }
1915 if _, ok := t.(mcpLifecycleConnect); ok {
1916 return true
1917 }
1918 name := strings.TrimSpace(t.Name())
1919 return strings.HasPrefix(name, "mcp_connect__")
1920 }
1921
1922 // mcpLifecycleConnect is implemented by deferred connect targets so Planner
1923 // can authorize lifecycle actions without relying on name prefixes alone.
1924 type mcpLifecycleConnect interface {
1925 MCPLifecycleConnect() bool
1926 MCPServerAuthorized() bool
1927 }
1928
1929 func plannerMCPConnectAllowed(t tool.Tool) bool {
1930 if life, ok := t.(mcpLifecycleConnect); ok {
1931 return life.MCPServerAuthorized()
1932 }
1933 return mcpServerAuthorized(t)
1934 }
1935
1936 func isInstalledMCPTool(t tool.Tool) bool {
1937 meta, ok := t.(tool.MCPMetadata)
1938 return ok && strings.TrimSpace(meta.MCPServerName()) != "" && strings.TrimSpace(meta.MCPRawToolName()) != ""
1939 }
1940
1941 func isMCPExecutionTarget(t tool.Tool, name string) bool {
1942 return isInstalledMCPTool(t) || strings.HasPrefix(strings.TrimSpace(name), "mcp__")
1943 }
1944
1945 func mcpServerAuthorized(t tool.Tool) bool {
1946 authority, ok := t.(tool.MCPServerAuthorization)
1947 return ok && authority.MCPServerAuthorized()
1948 }
1949
1950 func mcpDestructiveHint(t tool.Tool) bool {
1951 annotations, ok := t.(tool.MCPAnnotations)
1952 return ok && annotations.MCPDestructiveHint()
1953 }
1954
1955 func (a *Agent) planModeDecision(toolName string, readOnly bool, safety planmode.PlanSafety, args json.RawMessage) planmode.Decision {
1956 return (planmode.Policy{}).Decide(planmode.Call{
1957 Name: toolName,
1958 ReadOnly: readOnly,
1959 Safety: safety,
1960 Args: args,
1961 })
1962 }
1963
1964 // isBackgroundTaskCall reports whether a `task` call set run_in_background, so a
1965 // fire-and-return dispatch isn't mistaken for a sub-agent that has stopped.
1966 func isBackgroundTaskCall(args string) bool {
1967 var p struct {
1968 RunInBackground bool `json:"run_in_background"`
1969 }
1970 _ = json.Unmarshal([]byte(args), &p)
1971 return p.RunInBackground
1972 }
1973
1974 // toolReadOnly reports a tool's ReadOnly classification by name (false for an
1975 // unknown tool), for stamping early ToolDispatch events.
1976 func (a *Agent) toolReadOnly(name string) bool {
1977 t, _, ambiguous := a.svc.tools.ResolveCall(name)
1978 return t != nil && len(ambiguous) == 0 && t.ReadOnly()
1979 }
1980
1981 // firstLine returns s up to its first newline — a one-line failure summary for
1982 // the display Err, while the full error stays in the model-facing output.
1983 func firstLine(s string) string {
1984 if before, _, ok := strings.Cut(s, "\n"); ok {
1985 return before
1986 }
1987 return s
1988 }
1989
1990 // truncateToolOutput builds the stable provider-visible Content form for a tool
1991 // result. Under-cap bodies are byte-identical; over-cap bodies keep a tool-aware
1992 // preview while RawContent stores the full local original. read_file is special:
1993 // its preview is a contiguous prefix so an exact recovery cursor can never skip
1994 // source text that the model did not actually see.
1995 func truncateToolOutput(s string) (string, string) {
1996 return truncateToolOutputFor(s, "", "")
1997 }
1998
1999 // truncateToolOutputFor is the tool-aware provider-input limiter. toolName and
2000 // toolCallID populate the recovery marker.
2001 func truncateToolOutputFor(s, toolName, toolCallID string) (string, string) {
2002 if len(s) <= maxToolOutputBytes {
2003 return s, ""
2004 }
2005 if toolName == "read_file" {
2006 return truncateReadFileOutput(s, toolName, toolCallID)
2007 }
2008 strategy := snipStrategy{head: 40, tail: 40, headChars: 8000, tailChars: 8000}
2009 switch {
2010 case tool.IsShellToolName(toolName) || strings.Contains(toolName, "bash"):
2011 strategy = snipStrategy{head: 40, tail: 40, headChars: 8000, tailChars: 8000}
2012 case toolName == "read_file" || toolName == "web_fetch" || strings.Contains(toolName, "read"):
2013 strategy = snipStrategy{head: 120, tail: 12, headChars: 12000, tailChars: 2000}
2014 case toolName == "grep" || toolName == "glob" || toolName == "ls" || toolName == "list_dir":
2015 strategy = snipStrategy{head: 80, tail: 8, headChars: 10000, tailChars: 1000}
2016 }
2017 headKeep := strategy.headChars
2018 tailKeep := strategy.tailChars
2019 if headKeep+tailKeep > maxToolOutputBytes-512 {
2020 headKeep = maxToolOutputBytes * 2 / 3
2021 tailKeep = maxToolOutputBytes - headKeep - 512
2022 }
2023 if headKeep < 1024 {
2024 headKeep = maxToolOutputBytes / 2
2025 tailKeep = maxToolOutputBytes / 2
2026 }
2027 // Prefer more tail when the body looks like a failure.
2028 lower := strings.ToLower(s)
2029 if strings.Contains(lower, "error:") || strings.Contains(lower, "panic:") || strings.Contains(lower, "fatal:") {
2030 tailKeep = max(tailKeep, maxToolOutputBytes/3)
2031 if headKeep+tailKeep > maxToolOutputBytes-512 {
2032 headKeep = maxToolOutputBytes - 512 - tailKeep
2033 }
2034 }
2035 head := snapToRuneBoundary(s, 0, headKeep)
2036 tail := snapToRuneBoundary(s, len(s)-tailKeep, len(s))
2037 resultRef := toolResultRef(toolCallID, s)
2038 marker := toolOutputRecoveryMarker(toolName, toolCallID, resultRef, len(s), len(head)+len(tail))
2039 for range 3 {
2040 bodyLen := len(head) + len(marker) + len(tail)
2041 if bodyLen <= maxToolOutputBytes {
2042 break
2043 }
2044 overflow := bodyLen - maxToolOutputBytes
2045 trimHead := overflow / 2
2046 trimTail := overflow - trimHead
2047 if trimHead < len(head) {
2048 head = snapToRuneBoundary(head, 0, len(head)-trimHead)
2049 }
2050 if trimTail < len(tail) {
2051 tail = snapToRuneBoundary(tail, trimTail, len(tail))
2052 }
2053 marker = toolOutputRecoveryMarker(toolName, toolCallID, resultRef, len(s), len(head)+len(tail))
2054 }
2055 notice := fmt.Sprintf(i18n.M.ToolOutputTruncatedFmt, len(s)-len(head)-len(tail), len(s))
2056 return head + marker + tail, notice
2057 }
2058
2059 // finishReasonMessage maps an abnormal finish_reason to a one-line warning,
2060 // returning ok=false for the normal terminations ("stop", "tool_calls") and a
2061 // nil usage. The sink renders the message; the "! " prefix is presentation.
2062 func finishReasonMessage(u *provider.Usage) (string, bool) {
2063 if u == nil {
2064 return "", false
2065 }
2066 switch u.FinishReason {
2067 case "length":
2068 return i18n.M.FinishReasonLength, true
2069 case "content_filter":
2070 return i18n.M.FinishReasonContentFilter, true
2071 case "repetition_truncation":
2072 return i18n.M.FinishReasonRepetition, true
2073 default:
2074 return "", false
2075 }
2076 }
2077
2078 // streamInterruptNotice explains why a provider stream never reached a clean
2079 // terminal, in words a user can act on. Only the closed StreamInterrupt* enum
2080 // is rendered — the wrapped transport error can carry URLs or gateway bodies
2081 // and must not reach the transcript (#9560).
2082 func streamInterruptNotice(err error) (code, text string) {
2083 switch provider.StreamInterruptReason(err) {
2084 case provider.StreamInterruptIdleTimeout:
2085 return event.NoticeCodeStreamInterruptedIdleTimeout, i18n.M.StreamInterruptedIdleTimeout
2086 case provider.StreamInterruptPrematureEOF:
2087 return event.NoticeCodeStreamInterruptedPrematureEOF, i18n.M.StreamInterruptedPrematureEOF
2088 case provider.StreamInterruptConnectionReset:
2089 return event.NoticeCodeStreamInterruptedConnectionReset, i18n.M.StreamInterruptedConnectionReset
2090 default:
2091 return "", ""
2092 }
2093 }
2094
2094 lines GO