返回 DeepSeek-Reasonix
run_loop.go
根目录 / internal / agent / run_loop.go
1 package agent
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "strings"
9 "time"
10
11 "reasonix/internal/event"
12 "reasonix/internal/evidence"
13 "reasonix/internal/provider"
14 "reasonix/internal/runtimepolicy"
15 )
16
17 // streamedTurn is one provider completion collected by stream. Keeping the
18 // result together makes the missing-reasoning recovery path explicit: the
19 // first, malformed completion is never committed before a safe replacement is
20 // available, and a failed recovery can still fall back to the complete first
21 // response without re-running any tool.
22 type streamedTurn struct {
23 messageID string
24 displayReasoning string
25 settledAttemptID string
26 settledAttempt int
27 text string
28 reasoning string
29 signature string
30 reasoningID string
31 reasoningStatus string
32 reasoningComplete bool
33 reasoningState provider.ReasoningState
34 thinkingBlocks []provider.ThinkingBlock
35 calls []provider.ToolCall
36 responsesItems []json.RawMessage
37 serverSearch []provider.ServerSearchCall
38 usage *provider.Usage
39 interrupted bool
40 partialToolStarted bool
41 partialCalls []provider.ToolCall
42 maxArgChars int // peak streaming tool-arg size for failed-attempt estimates
43 err error
44 }
45
46 func (s streamedTurn) assistantMessage() provider.Message {
47 return provider.Message{
48 ID: s.messageID,
49 Role: provider.RoleAssistant, Content: s.text, ReasoningContent: s.reasoning,
50 ReasoningState: s.reasoningState, ThinkingBlocks: s.thinkingBlocks,
51 ReasoningSignature: s.signature, ReasoningID: s.reasoningID, ReasoningStatus: s.reasoningStatus,
52 ToolCalls: s.calls, ResponsesItems: s.responsesItems, ServerSearch: s.serverSearch,
53 }
54 }
55
56 // beginRunTurn handles evidence scope, delivery classification, background-job
57 // evidence re-lease, and the initial user-turn persistence. Callers still own
58 // all Run-level defers (workspace lease, evidence commit, delivery checkpoint,
59 // steer queue, active-turn timestamp).
60 func (a *Agent) beginRunTurn(ctx context.Context, input string, pinned pinnedRevisionPlan) (rawInput string, state *turnRuntime, err error) {
61 rawInput = RawUserInput(ctx, input)
62 providerInput := input
63 // A fresh user turn starts from zeroed per-turn host state; the new turn's
64 // values are computed below. Cross-turn state (checkpoint, scope, failure
65 // budgets) lives in taskRuntime and is reconciled there.
66 a.stragglers.drain(ctx, parallelStragglerGrace)
67 a.turn = turnRuntime{}
68 a.reads.runGen++
69 a.reads.tasks = newReadTasks(a.sess.path, a.reads.runGen)
70 a.reads.deliveries = make(map[string]readDelivery)
71 a.reads.visible = nil
72 scope, scoped := DeliveryExecutionScopeFromContext(ctx)
73 if a.task.ledger != nil {
74 switch {
75 case scoped && a.task.scopeID == scope.ID:
76 a.task.ledger.ResetBackgroundLeases()
77 default:
78 a.resetTurnEvidence()
79 }
80 }
81 if scoped {
82 a.task.scopeID = scope.ID
83 } else {
84 a.task.scopeID = ""
85 }
86 a.turn.deliveryScopeActive = scoped
87 if scoped && a.task.checkpoint.ScopeID != scope.ID {
88 a.task.checkpoint = evidence.DeliveryCheckpoint{ScopeID: scope.ID}
89 }
90 a.leasePendingBackgroundEvidence(ctx)
91 // Use the owning task text for explicit action constraints and recovery.
92 // Child framing must not be interpreted as an instruction from the user.
93 a.turn.turnInput = a.classifierTaskText
94 if scoped && strings.TrimSpace(scope.TaskText) != "" {
95 a.turn.turnInput = scope.TaskText
96 } else if strings.TrimSpace(a.turn.turnInput) == "" {
97 a.turn.turnInput = rawInput
98 }
99 a.turn.recoveryTaskSummary = boundedRecoveryTaskSummary(a.turn.turnInput)
100 if constraints, ok := runtimepolicy.FromContext(ctx); ok {
101 a.turn.constraints = constraints
102 } else {
103 a.turn.constraints = runtimepolicy.ParseConstraints(runtimepolicy.StripQuotedConstraints(a.turn.turnInput))
104 if a.planMode.Load() {
105 a.turn.constraints.PlanModeReadOnly = true
106 a.turn.constraints.ForbidMutation = true
107 }
108 }
109 if inherited, ok := runtimepolicy.InheritedFromContext(ctx); ok && !a.readOnlyExecution {
110 a.turn.constraints = mergeInheritedConstraints(a.turn.constraints, inherited.Constraints)
111 if inherited.PlanReadOnly {
112 a.turn.constraints.PlanModeReadOnly = true
113 a.turn.constraints.ForbidMutation = true
114 }
115 } else if a.inheritedExec != nil && !a.readOnlyExecution {
116 a.turn.constraints = mergeInheritedConstraints(a.turn.constraints, a.inheritedExec.Constraints)
117 if a.inheritedExec.PlanReadOnly {
118 a.turn.constraints.PlanModeReadOnly = true
119 a.turn.constraints.ForbidMutation = true
120 }
121 }
122 a.turn.engine = runtimepolicy.NewEngine(a.turn.constraints)
123 // A cancelled/error turn leaves a provider-excluded recovery record at the
124 // transcript tail. Fold its bounded facts into this new user turn exactly
125 // once; the user's raw text remains the source above.
126 a.ensureUnreplayableHistoryRecovery()
127 providerInput = withInterruptedRecovery(providerInput, a.verifyInterruptedWrites(ctx, a.pendingInterruptedRecovery()))
128 a.task.prepareScope(scoped, scope.ID)
129 a.svc.sink.Emit(event.Event{Kind: event.TurnStarted})
130 a.emitTurnPhase(event.TurnPhaseWorking)
131 input = a.prepareProviderTurn(ctx, providerInput)
132 userCreatedAt := time.Now().UnixMilli()
133 a.activeTurnCreatedAt.Store(userCreatedAt)
134 rawContent := rawInput
135 if rawContent == "" {
136 rawContent = a.turn.turnInput
137 }
138 userMessage := provider.Message{
139 ID: turnUserMessageID(ctx, a.sess.conversation),
140 Role: provider.RoleUser, Origin: inputMessageOrigin(ctx), Content: input, RawContent: rawContent,
141 Images: userImages(ctx), ImageInputs: userImageInputs(ctx), VisionSummary: VisionSummaryFromContext(ctx), CreatedAt: userCreatedAt,
142 }
143 if err := userMessage.ValidateImageFields(); err != nil {
144 return rawInput, nil, err
145 }
146 if err := a.appendPinnedRevisionAndUser(ctx, pinned, userMessage); err != nil {
147 return rawInput, nil, err
148 }
149 a.admitUserMessage(ctx, userMessage)
150
151 // The loop fields join the classification computed above rather than
152 // opening a second object: one turn, one turnRuntime. The zero values the
153 // old literal spelled out are already there from the reset at the top.
154 state = &a.turn
155 state.input = input
156 state.budget = runBudget{started: time.Now()}
157 return rawInput, state, nil
158 }
159
160 // runToolLoop owns the main tool-round budget and dispatches each streamed
161 // assistant turn into final-response or tool-round handling.
162 func (a *Agent) runToolLoop(ctx context.Context, state *turnRuntime) (runErr error) {
163 releaseMCPListObserver := a.activateMCPListObserver()
164 defer releaseMCPListObserver()
165 ctx = a.withAgentContext(ctx)
166 truncatedRounds := 0
167 for step := 0; state.runMaxSteps <= 0 || step < state.runMaxSteps || state.graceRound; step++ {
168 // Consume a queued steer and persist it to the session so it
169 // survives tab switches and history replay. The model sees it as
170 // guidance (with a prefix), not a new task. One cache miss per
171 // steer is unavoidable — the model must see the new instruction.
172 if text, itemID, ok := a.consumeSteer(); ok {
173 steerMessage := provider.Message{
174 ID: NewMessageID(),
175 Role: provider.RoleUser, Origin: provider.MessageOriginUser,
176 Content: a.withTurnPreferences(midTurnSteerMessage(text)), RawContent: text,
177 }
178 if err := a.appendCommittedMessages(ctx, "mid-turn-steer", steerMessage); err != nil {
179 return err
180 }
181 a.svc.sink.Emit(event.Event{Kind: event.Steer, MessageID: steerMessage.ID, Text: text, ItemID: itemID})
182 } else if itemID != "" {
183 // Loader failed after dequeue: durable entry stays for inspection
184 // (unapplied path marks uncertain + pause via the notice sink).
185 a.RecordUnappliedSteer("(body load failed)", itemID)
186 }
187 schemas := a.providerToolSchemas()
188 prefixShape := a.capturePrefixShape(schemas)
189 prevPrefixShape := a.sess.lastPrefixShape
190 if !a.sess.haveLastPrefixShape {
191 prevPrefixShape = prefixShape
192 }
193 // Drain reasons queued since the previous capture (compaction,
194 // snip/prune, rewind, guardian merge) so CompareShape can attribute
195 // any prefix change to the operation that actually caused it, instead
196 // of a generic rewrite signal that also fires on local-only metadata
197 // edits.
198 contentReasons := a.sess.conversation.DrainContentRewriteReasons()
199
200 // Prefix shape is captured once before sampling and frozen for the
201 // whole attempt lifecycle — stream retries must not rewrite session
202 // history mid-round, so the shape stays stable across body replays.
203 streamed := a.streamWithSamplingRecovery(ctx, step+1)
204 text, reasoning, calls, usage := streamed.text, streamed.reasoning, streamed.calls, streamed.usage
205 partialCalls, err := streamed.partialCalls, streamed.err
206 cacheDiagnostics := CompareShape(prevPrefixShape, prefixShape, usage, contentReasons)
207 a.attachSessionContextDiagnostics(&cacheDiagnostics)
208 if err != nil {
209 quote := a.emitTurnUsage(usage, &cacheDiagnostics)
210 a.observeRunBudget(state, usage, quote)
211 if msg, ok := finishReasonMessage(usage); ok {
212 a.svc.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: msg})
213 }
214 // Exhausted stream retries (or a non-retryable error): persist one
215 // bounded LocalOnly recovery record for the next real user message.
216 // Intermediate failed attempts never wrote session state.
217 a.recordInterruptedDisplay(text, reasoning, partialCalls, true, err, state.workDurationMs(), streamed.messageID)
218 // A broken provider stream can otherwise look like a silent hang
219 // followed only by the generic interrupted-turn notice (#9560).
220 if code, msg := streamInterruptNotice(err); msg != "" {
221 a.svc.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Code: code, Text: msg})
222 }
223 return err
224 }
225 a.sess.lastPrefixShape = prefixShape
226 a.sess.haveLastPrefixShape = true
227 quote := a.emitTurnUsage(usage, &cacheDiagnostics)
228 a.observeRunBudget(state, usage, quote)
229 if msg, ok := finishReasonMessage(usage); ok {
230 a.svc.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: msg})
231 }
232
233 // Commit clean terminal attempts, preserving provider reasoning contracts.
234 calls = a.withPreviewFileDiffs(ctx, calls)
235 if err := assignRecoveryCallIDs(calls); err != nil {
236 return err
237 }
238 assistant := streamed.assistantMessage()
239 assistant.ToolCalls = calls
240 assistant.WorkDurationMs = state.workDurationMs()
241 if err := a.appendCommittedMessages(ctx, "assistant-attempt", assistant); err != nil {
242 if errors.Is(err, context.Canceled) {
243 a.recordInterruptedDisplay(text, reasoning, partialCalls, true, err, state.workDurationMs(), streamed.messageID)
244 }
245 return err
246 }
247 a.publishCommittedSample(streamed)
248
249 if len(calls) == 0 {
250 cont, ferr := a.handleFinalResponse(ctx, state, text, reasoning, usage)
251 if !cont {
252 return ferr
253 }
254 continue
255 }
256
257 if usage != nil && usage.FinishReason == "length" {
258 truncatedRounds++
259 if err := a.recordTruncatedToolResults(withMessageIdentity(ctx, streamed.messageID), calls); err != nil {
260 return err
261 }
262 if truncatedRounds > maxToolArgumentRepairs {
263 return fmt.Errorf("tool arguments remained truncated after three recovery rounds")
264 }
265 continue
266 }
267 truncatedRounds = 0
268
269 // Invariant: executeBatch only ever receives tool calls from a
270 // committed sampling attempt (clean terminal + response intercept).
271 cont, terr := a.handleToolRound(withMessageIdentity(ctx, streamed.messageID), state, step, text, reasoning, calls, usage)
272 if !cont {
273 return terr
274 }
275 }
276 // Only reached when a positive maxSteps guard is configured. The work so far
277 // is already in the session, so the user can just send another message to pick
278 // up where it left off.
279 return a.gracePause(state)
280 }
281
282 func (a *Agent) emitProtocolRetry(attempt int, hasFallback bool) {
283 maxAttempts := 1
284 if hasFallback {
285 maxAttempts = 2
286 }
287 a.svc.sink.Emit(event.Event{
288 Kind: event.Retrying, RetryAttempt: attempt, RetryMax: maxAttempts,
289 RetryScope: event.RetryScopeProtocol,
290 })
291 }
292
293 func (a *Agent) emitStreamAttempt(id string, action event.StreamAttemptAction, attempt int, reason string, err error, summary ...*event.ResponseSummary) {
294 if reason == "" && err != nil {
295 reason = provider.StreamInterruptReason(err)
296 }
297 info := event.StreamAttemptInfo{ID: id, Action: action, Attempt: attempt, Max: maxSamplingAttempts, Reason: reason}
298 if len(summary) > 0 {
299 info.Response = summary[0]
300 }
301 a.svc.sink.Emit(event.Event{
302 Kind: event.StreamAttempt,
303 MessageID: id,
304 AttemptID: id,
305 StreamAttempt: info,
306 })
307 }
308
309 func newStreamAttemptID(_ int) string {
310 // A successful attempt retains this local identity when its message is
311 // committed. Failed attempts have distinct identities and cannot alias it.
312 return NewMessageID()
313 }
314
315 // handleFinalResponse processes a no-tool assistant turn: recovery pause,
316 // readiness boundary, empty-final retry, executor handoff nudge, steer drain,
317 // and final compaction. cont=true continues the tool loop; cont=false returns
318 // err from Run (err may be nil for a clean final answer).
319 func (a *Agent) handleFinalResponse(ctx context.Context, state *turnRuntime, text, reasoning string, usage *provider.Usage) (cont bool, err error) {
320 // Cancellation wins until Run returns, even after a committed answer; the
321 // answer stays in history for display (DeepSeek Harness turn semantics).
322 if err := ctx.Err(); err != nil {
323 return false, err
324 }
325 if state.graceRound {
326 // Explicit max_steps and spend budgets are user-selected boundaries.
327 // Preserve the summary, then return a resumable pause so Goal does not
328 // immediately open another Run and silently bypass the chosen limit.
329 a.contextManager().ObserveUsage(usage)
330 return false, a.gracePause(state)
331 }
332 if !hasVisibleFinalAnswer(text) {
333 // Transport completion is not delivery; structured finalizers end in
334 // handleToolRound. A spent budget is a resumable boundary, so it wins
335 // over both another recovery round and the exhaustion failure.
336 if axis, detail := a.task.budget.exceeded(a.taskBudgetLimit(ctx)); axis != "" {
337 return false, &taskBudgetPause{axis: axis, detail: detail}
338 }
339 state.terminal.emptyFinalBlocks++
340 if state.terminal.emptyFinalBlocks >= maxEmptyFinalBlocks {
341 // Clean streams skip the interrupted-stream recorder. This local-only
342 // marker drives reopened history and the controller's failed-turn
343 // cleanup, which owns any recovery facts replayed to the model.
344 failure := provider.ErrNoDeliverableOutput
345 record := interruptedDisplayRecord("", "", "", nil, true, failure)
346 if err := a.appendCommittedMessages(ctx, "no-deliverable-output", record); err != nil {
347 return false, err
348 }
349 return false, failure
350 }
351 state.terminal.answeringRecovery = true
352 return a.retryEmptyFinal(ctx, reasoning, usage)
353 }
354 a.emitTurnShadows(a.turn.turnInput)
355 if !a.closeSteerIntakeIfIdle() {
356 return true, nil
357 }
358 // A final-answer turn skips compaction, so a large context
359 // carries into the next turn un-folded and can overflow the model window.
360 // No-op below the trigger, so normal turns keep their warm cache.
361 a.contextManager().ObserveUsage(usage)
362 a.closeTurnPhase()
363 return false, nil // model gave a final answer
364 }
365
366 func (a *Agent) retryEmptyFinal(ctx context.Context, reasoning string, usage *provider.Usage) (cont bool, err error) {
367 a.svc.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Code: event.NoticeCodeEmptyFinal, Text: emptyFinalNotice(), Detail: emptyFinalNoticeDetail(a.svc.prov.Name(), usage, len(reasoning))})
368 if err := a.appendCommittedMessages(ctx, "empty-final-retry", HostGeneratedUserMessage(a.withTurnPreferences(emptyFinalRetryMessage()))); err != nil {
369 return false, err
370 }
371 a.contextManager().ObserveUsage(usage)
372 return true, nil
373 }
374
375 // handleToolRound executes a tool batch, persists tool messages, handles
376 // cancellation, todo stall tracking, recovery finalization pause, and the
377 // max-steps grace round. cont=true continues the tool loop; cont=false returns
378 // err from Run.
379 func (a *Agent) handleToolRound(ctx context.Context, state *turnRuntime, step int, text, reasoning string, calls []provider.ToolCall, usage *provider.Usage) (cont bool, err error) {
380 boundaryFinalizer := a.allowsBoundaryTurnFinalizer(ctx, state, calls)
381 if boundaryErr, stop := a.stopUnexecutedBoundaryCalls(ctx, state, calls, usage); stop {
382 return false, boundaryErr
383 }
384
385 // The phase pair around the batch is what makes the accounting mean its
386 // names: it bills this round's wait to the provider and the batch to tools.
387 a.emitTurnPhase(event.TurnPhaseChecking)
388 batch := a.executeBatch(ctx, state, calls)
389 a.emitTurnPhase(event.TurnPhaseWorking)
390 if batch.err != nil {
391 // Any completed results are already stored; a failed durability barrier
392 // prevents starting the next tool.
393 return false, batch.err
394 }
395 if a.successfulTurnFinalizer(ctx, calls, batch) {
396 // submit_plan is the planner's data-bearing final answer. Its paired tool
397 // result is stored, so another acknowledgement adds no host value and can
398 // turn a valid bounded plan into a max-steps pause.
399 a.contextManager().ObserveUsage(usage)
400 a.closeTurnPhase()
401 return false, nil
402 }
403 if boundaryFinalizer {
404 // The one allowed boundary finalizer ran but was rejected or blocked.
405 // Preserve the one-grace-round contract instead of opening an unbounded
406 // loop of malformed terminal submissions.
407 a.contextManager().ObserveUsage(usage)
408 return false, a.gracePause(state)
409 }
410 // The prompt only grows from here; compact before the next turn so it
411 // stays within the model's window.
412 a.contextManager().ObserveUsage(usage)
413
414 // Spend is checked before rounds: it is the axis a runaway is actually
415 // reported in, so on the turns both would catch it should be the one named.
416 if axis, detail := a.task.budget.exceeded(a.taskBudgetLimit(ctx)); axis != "" {
417 if err := a.armFinalizationRound(ctx, state, landCause{kind: "task_budget", axis: axis, detail: detail}); err != nil {
418 return false, err
419 }
420 return true, nil
421 }
422 if state.runMaxSteps > 0 && step+1 >= state.runMaxSteps {
423 if err := a.armFinalizationRound(ctx, state, landCause{kind: "max_steps", detail: fmt.Sprintf(
424 "budget (%s=%d) exhausted: one grace round to finalize", state.runMaxStepsKey, state.runMaxSteps)}); err != nil {
425 return false, err
426 }
427 }
428 return true, nil
429 }
430
431 func (a *Agent) pairUnexecutedGraceCalls(ctx context.Context, calls []provider.ToolCall, msg string) error {
432 messages := make([]provider.Message, 0, len(calls))
433 for _, call := range calls {
434 messages = append(messages, provider.Message{Role: provider.RoleTool, Content: msg, ToolCallID: call.ID, Name: call.Name})
435 }
436 return a.appendCommittedMessages(ctx, "unexecuted-grace-tools", messages...)
437 }
438
439 func (a *Agent) publishCommittedSample(streamed streamedTurn) {
440 // Publish settlement only after the complete message is accepted by
441 // the business log. Recovery must never observe an end without a result.
442 if streamed.text != "" || streamed.displayReasoning != "" {
443 a.svc.sink.Emit(event.Event{Kind: event.Message, MessageID: streamed.messageID, AttemptID: streamed.messageID,
444 Text: DisplayAssistantText(streamed.text), Reasoning: streamed.displayReasoning})
445 }
446 if streamed.settledAttemptID != "" {
447 a.emitStreamAttempt(streamed.settledAttemptID, event.StreamAttemptCommit, streamed.settledAttempt, "", nil, a.responseSummary(streamed))
448 }
449 a.turn.terminal.answeringRecovery = false
450 }
451
451 lines GO