返回 DeepSeek-Reasonix
turn_orchestrator.go
根目录 / internal / control / turn_orchestrator.go
1 package control
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "time"
9
10 "reasonix/internal/agent"
11 "reasonix/internal/event"
12 "reasonix/internal/jobs"
13 "reasonix/internal/provider"
14 "reasonix/internal/skill"
15 "reasonix/internal/tool"
16 )
17
18 // turnOrchestrator owns foreground turn execution while Controller keeps the
19 // public ports, run-state guard, and session-scoped dependencies.
20 type turnOrchestrator struct {
21 c *Controller
22 }
23
24 type orchestratedTurn struct {
25 input string
26 raw string
27 imageRefs string
28 userImages []string
29 imageCandidates []string
30 imagesResolved bool
31 display string
32 editedOriginal string
33 synthetic bool
34 goalRound *goalRoundReservation
35 }
36
37 func newTurnOrchestrator(c *Controller) *turnOrchestrator {
38 return &turnOrchestrator{c: c}
39 }
40
41 func (o *turnOrchestrator) runTurnWithRawDisplay(ctx context.Context, input, raw, display string) error {
42 return o.runOrchestratedTurn(ctx, orchestratedTurn{input: input, raw: raw, display: display})
43 }
44
45 func (o *turnOrchestrator) runTurnWithImageRefsRawDisplay(ctx context.Context, input, raw, imageRefs, display string) error {
46 return o.runOrchestratedTurn(ctx, orchestratedTurn{input: input, raw: raw, imageRefs: imageRefs, display: display})
47 }
48
49 func (o *turnOrchestrator) runSyntheticTurnWithRawDisplay(ctx context.Context, input, raw, display string) error {
50 return o.runOrchestratedTurn(ctx, orchestratedTurn{input: input, raw: raw, display: display, synthetic: true})
51 }
52
53 func (o *turnOrchestrator) runComposedSyntheticTurn(ctx context.Context, text string) error {
54 c := o.c
55 ctx = agent.WithRawUserInput(ctx, text)
56 ctx = withTurnInputOrigin(ctx, true)
57 // ctx may carry the identity already spent on the turn's own user message.
58 if c.executor != nil {
59 ctx = agent.WithUserMessageIdentity(ctx, c.executor.Session(), agent.NewMessageID())
60 }
61 ctx = c.withTurnContext(ctx, false)
62 ctx = c.withPlannerTurnMetadata(ctx, text, true, c.messageCount())
63 return c.runModelTurn(ctx, c.ComposeSynthetic(text))
64 }
65
66 // runSubagentSkillGoalLoop executes a slash-invoked runAs=subagent skill as a
67 // real isolated child turn, then lets an active goal continue just as an inline
68 // skill turn did before.
69 func (o *turnOrchestrator) runSubagentSkillGoalLoop(ctx context.Context, sk skill.Skill, task, raw, display string, runner skill.SubagentRunner, planMode bool) error {
70 return o.runSubagentSkillTurnsGoalLoop(ctx, []skill.Skill{sk}, task, raw, display, runner, planMode)
71 }
72
73 func (o *turnOrchestrator) runSubagentSkillTurnsGoalLoop(ctx context.Context, skills []skill.Skill, task, raw, display string, runner skill.SubagentRunner, planMode bool, frozen ...[]string) error {
74 var userImages, imageCandidates []string
75 if len(frozen) > 0 {
76 imageCandidates = append([]string(nil), frozen[0]...)
77 if o.c.imageInputEnabled() {
78 userImages = append([]string(nil), imageCandidates...)
79 }
80 } else {
81 userImages, imageCandidates = o.c.resolveTurnImages(raw)
82 }
83 ctx = agent.WithSubagentImageCandidates(ctx, imageCandidates)
84 ctx = o.c.withPreparedTurnImages(ctx)
85 return o.runSubagentSkillTurns(ctx, skills, task, raw, display, runner, planMode, userImages, imageCandidates)
86 }
87
88 // runSubagentSkillTurns records the composed user task and distilled child
89 // answers only. Child reasoning and tool chatter stay out of the
90 // provider-visible parent context while their UI events nest under synthetic
91 // top-level run_skill cards.
92 func (o *turnOrchestrator) runSubagentSkillTurns(ctx context.Context, skills []skill.Skill, task, raw, display string, runner skill.SubagentRunner, planMode bool, images, imageCandidates []string) (err error) {
93 c := o.c
94 turnStartedAt := time.Now()
95 c.maybeSessionStart(ctx)
96 parentSession := c.parentSessionID()
97 ctx = agent.WithParentSession(ctx, parentSession)
98 ctx = jobs.WithSession(ctx, parentSession)
99 ctx = agent.WithUserImages(ctx, images)
100 ctx = agent.WithSubagentImageCandidates(ctx, imageCandidates)
101 ctx = agent.WithResponseLanguagePreference(ctx, c.responseLanguage)
102 ctx = agent.WithReasoningLanguagePreference(ctx, c.reasoningLanguage)
103 ctx = c.withTurnContext(ctx, true)
104
105 input := c.compose(task, raw, true)
106 startMessages := c.messageCount()
107 var marker agent.InFlightTurnMeta
108 defer func() { c.finishInFlightTurn(startMessages, marker) }()
109 defer c.recordDisplayForNewUser(startMessages, display)
110 // The checkpoint prompt labels the turn in the rewind picker (and is
111 // prefilled into the composer after a conversation rewind), so it must be
112 // the user's own text — never the composed provider input with its
113 // transient <response-language>/<reasoning-language>/memory/hook blocks.
114 c.beginCheckpoint(ctx, firstNonEmpty(raw, task))
115 if c.guardianSess != nil {
116 c.guardianSess.ResetTurn()
117 }
118 if c.hooks.Enabled() {
119 c.mu.Lock()
120 c.turn++
121 turn := c.turn
122 c.mu.Unlock()
123 if block, _ := c.hooks.PromptSubmit(ctx, input, turn); block {
124 return nil
125 }
126 defer func() { c.hooks.StopResult(context.Background(), lastAssistantText(c.History()), turn, err) }()
127 }
128
129 marker = c.markInFlightTurn(startMessages, true)
130 c.sink.Emit(event.Event{Kind: event.TurnStarted})
131 if c.executor == nil {
132 return fmt.Errorf("subagent slash invocation requires an active session")
133 }
134 message := persistedUserTurn(input, firstNonEmpty(raw, task), images, time.Now().UnixMilli())
135 if prepared, ok := ctx.Value(preparedImageReferencesContextKey{}).(preparedImageReferences); ok && len(prepared.inputs) > 0 {
136 message.Images = nil
137 message.ImageInputs = prepared.inputs
138 }
139 if _, err := c.executor.AppendTurnContextAndUserChecked(ctx, message); err != nil {
140 return err
141 }
142
143 work := c.beginGoalWork()
144 defer func() { c.recordGoalWork(work, time.Now()) }()
145 for _, sk := range skills {
146 sk = c.skills.prepare(sk)
147 callID := fmt.Sprintf("slash-skill-%d", c.slashSkillSeq.Add(1))
148 args, _ := json.Marshal(map[string]string{"name": sk.Name, "arguments": task})
149 toolEvent := event.Tool{
150 ID: callID,
151 Name: "run_skill",
152 Args: string(args),
153 ReadOnly: sk.ReadOnly,
154 }
155 if c.skillProfile != nil {
156 toolEvent.Profile = c.skillProfile(sk)
157 }
158 if err := event.EmitChecked(c.sink, event.Event{Kind: event.ToolDispatch, Tool: toolEvent}); err != nil {
159 return fmt.Errorf("persist skill dispatch: %w", err)
160 }
161 runCtx := agent.WithToolCallContext(ctx, callID, c.sink, c, planMode)
162 runCtx = agent.WithSubagentDepth(runCtx, 0)
163 answer, err := runner(runCtx, sk, input, skill.SubagentRunOptions{HostInitiated: true})
164 if err != nil {
165 toolEvent.Err = err.Error()
166 c.sink.Emit(event.Event{Kind: event.ToolResult, Tool: toolEvent})
167 return err
168 }
169 answer = tool.GuardSubagentHostDecisionText(answer)
170 toolEvent.Output = answer
171 c.sink.Emit(event.Event{Kind: event.ToolResult, Tool: toolEvent})
172 workDurationMs := max(int64(1), time.Since(turnStartedAt).Milliseconds())
173 messageID := agent.NewMessageID()
174 assistant := provider.Message{ID: messageID, Role: provider.RoleAssistant, Content: answer, WorkDurationMs: workDurationMs}
175 if err := c.RecordSessionMessages(ctx, "orchestrated-assistant", []provider.Message{assistant}); err != nil {
176 return err
177 }
178 c.executor.Session().Add(assistant)
179 display := agent.DisplayAssistantText(answer)
180 c.sink.Emit(event.Event{Kind: event.Text, MessageID: messageID, Text: display})
181 c.sink.Emit(event.Event{Kind: event.Message, MessageID: messageID, Text: display})
182 }
183
184 return nil
185 }
186
187 func (o *turnOrchestrator) runOrchestratedTurn(ctx context.Context, turn orchestratedTurn) (err error) {
188 c := o.c
189 c.maybeSessionStart(ctx)
190 parentSession := c.parentSessionID()
191 ctx = agent.WithParentSession(ctx, parentSession)
192 ctx = jobs.WithSession(ctx, parentSession)
193 userImages, imageCandidates := c.imagesForOrchestratedTurn(ctx, turn)
194 ctx = agent.WithUserImages(ctx, userImages)
195 ctx = agent.WithSubagentImageCandidates(ctx, imageCandidates)
196 ctx = agent.WithRawUserInput(ctx, turn.raw)
197 ctx = c.withPreparedTurnImages(ctx)
198 ctx = withTurnInputOrigin(ctx, turn.synthetic)
199 userMessageID := agent.NewMessageID()
200 if _, turnID, active := c.currentTurnToken(); active {
201 if receipt, ok := c.submissionForTurn(turnID); ok {
202 userMessageID = receipt.MessageID
203 }
204 }
205 if c.executor != nil {
206 ctx = agent.WithUserMessageIdentity(ctx, c.executor.Session(), userMessageID)
207 }
208 var input string
209 if turn.goalRound != nil {
210 input = c.ComposeSynthetic(turn.input)
211 } else {
212 input = c.compose(turn.input, turn.raw, !turn.synthetic)
213 }
214 // input.receive: the composed text crosses the extension chain before it
215 // enters the session (checkpoint, hooks, and the model all see the final
216 // text). A block ruling aborts the turn with the redacted reason surfaced,
217 // mirroring the PromptSubmit hook's abort path; a required-class extension
218 // failure fails the turn.
219 input, blocked, interceptErr := c.interceptInputReceive(ctx, input)
220 if interceptErr != nil {
221 return interceptErr
222 }
223 if blocked {
224 return nil
225 }
226 startMessages := c.messageCount()
227 fallback := persistedUserTurn(input, turn.raw, userImages, time.Now().UnixMilli())
228 fallback.ID = userMessageID
229 c.noteTerminationBoundary(fallback, !turn.synthetic)
230 var marker agent.InFlightTurnMeta
231 defer func() { c.finishInFlightTurn(startMessages, marker) }()
232 defer c.recordDisplayForNewUser(startMessages, turn.display)
233 if turn.editedOriginal != "" {
234 defer c.markEditedForNewUser(startMessages, turn.editedOriginal)
235 }
236 // Open a checkpoint only for visible user turns before the user message is
237 // appended, so the recorded message boundary precedes it and pre-edit
238 // snapshots land here. Synthetic continuations stay attached to the visible
239 // turn that spawned them; otherwise hidden user-role messages would advance
240 // backend checkpoint turns without a matching frontend turn. The label is
241 // the user's own text (raw, falling back to the expanded input) — the
242 // composed provider input carries transient prefab blocks that must never
243 // surface in the rewind picker or be prefilled into the composer.
244 if !turn.synthetic {
245 c.beginCheckpoint(ctx, firstNonEmpty(turn.raw, turn.input))
246 }
247 if c.guardianSess != nil {
248 c.guardianSess.ResetTurn()
249 }
250 // UserPromptSubmit / Stop hooks bracket the whole turn (incl. the plan
251 // research + approved-execution sub-turns below): a gating UserPromptSubmit
252 // aborts before any model call; Stop fires once when the turn returns.
253 if c.hooks.Enabled() {
254 c.mu.Lock()
255 c.turn++
256 turn := c.turn
257 c.mu.Unlock()
258 if block, _ := c.hooks.PromptSubmit(ctx, input, turn); block {
259 return nil // the hook's notify callback already surfaced the reason
260 }
261 defer func() { c.hooks.StopResult(context.Background(), lastAssistantText(c.History()), turn, err) }()
262 }
263 marker = c.markInFlightTurn(startMessages, !turn.synthetic)
264 ctx = c.withTurnContext(ctx, !turn.synthetic)
265 if turn.goalRound != nil {
266 if authority, ok := c.goalAuthorityForRound(turn.goalRound); ok {
267 ctx = tool.WithGoalLifecycle(ctx, c, authority)
268 }
269 } else if !turn.synthetic {
270 if authority, ok := c.directHumanGoalAuthority(); ok {
271 ctx = tool.WithGoalLifecycle(ctx, c, authority)
272 }
273 }
274 ctx = c.withPlannerTurnMetadata(ctx, turn.raw, turn.synthetic, startMessages)
275 modelInput := input
276 if !turn.synthetic {
277 modelInput = c.withCapabilityRoute(ctx, input, turn.raw)
278 }
279 modelInput, ctx, err = c.prepareVisionTurn(ctx, modelInput, imageCandidates)
280 if err != nil {
281 return err
282 }
283 err = c.runModelTurn(ctx, modelInput)
284 if err != nil {
285 fallback := persistedUserTurn(input, turn.raw, userImages, time.Now().UnixMilli())
286 fallback.ID = userMessageID
287 // When the user explicitly cancels, keep the real prompt and any fully
288 // paired tool work. Partial reasoning/output remains durable for display
289 // but is marked local-only, and a bounded recovery summary is folded into
290 // the next real user turn (#5499, #6680).
291 if errors.Is(err, context.Canceled) && c.CancelRequested() {
292 if turn.synthetic {
293 c.stripInterruptedSyntheticTurnMessagesAfter(startMessages)
294 } else {
295 c.stripCancelledVisibleTurnMessagesAfterWithFallback(startMessages, fallback)
296 }
297 } else if !turn.synthetic && c.hasInterruptedDisplayAfter(startMessages, fallback) {
298 // Provider/API failures use the same safe recovery path as an explicit
299 // stop once the agent has recorded a partial stream. Completed tool
300 // pairs survive; unsafe stream fragments stay local-only.
301 c.stripCancelledVisibleTurnMessagesAfterWithFallback(startMessages, fallback)
302 }
303 return err
304 }
305 return o.executeApprovedPlan(ctx)
306 }
307
308 func (o *turnOrchestrator) executeApprovedPlan(ctx context.Context) error {
309 c := o.c
310 c.mu.Lock()
311 plan := c.sessionSettings.planMode
312 c.mu.Unlock()
313 if !plan {
314 return nil
315 }
316 proposal := lastAssistantText(c.History())
317 if proposal == "" {
318 return nil // no substantive proposal to gate
319 }
320 // The plan is already visible as the assistant's answer, so the request
321 // carries no subject — it's purely the gate.
322 allow, _, err := c.requestApproval(ctx, planApprovalTool, "", nil)
323 if err != nil {
324 return err
325 }
326 if !allow {
327 // The host decides whether denial means "revise and keep planning" or
328 // "exit without executing" by leaving plan mode on or switching it off.
329 return nil
330 }
331 c.SetPlanMode(false)
332 execStart := c.sessionMessageCount()
333 // The plan is the go-ahead: don't re-prompt for each write of the approved
334 // work. Auto-approve writers for the duration of this execution turn only; a
335 // later turn (even "continue") falls back to the normal per-tool approval.
336 c.approval.setPlanAutoApprove(true)
337 defer c.approval.setPlanAutoApprove(false)
338 err = func() error {
339 marker := c.markInFlightTurn(execStart, false)
340 defer c.finishInFlightTurn(execStart, marker)
341 return o.runComposedSyntheticTurn(ctx, planApprovedMessage)
342 }()
343 if err != nil {
344 if errors.Is(err, context.Canceled) && c.CancelRequested() {
345 c.stripInterruptedSyntheticTurnMessagesAfter(execStart)
346 }
347 return err
348 }
349 return nil
350 }
351
352 func (o *turnOrchestrator) runGoalLoopWithRawDisplay(ctx context.Context, input, raw, display string) error {
353 return o.runGoalLoopWithImageRefsRawDisplay(ctx, input, raw, "", display)
354 }
355
356 func (o *turnOrchestrator) runGoalLoopWithImageRefsRawDisplay(ctx context.Context, input, raw, imageRefs, display string) error {
357 turn := o.c.prepareOrchestratedTurnImages(orchestratedTurn{input: input, raw: raw, imageRefs: imageRefs, display: display})
358 return o.runGoalLoopWithPreparedTurn(ctx, turn)
359 }
360
361 func (o *turnOrchestrator) runGoalLoopWithFrozenImagesRawDisplay(ctx context.Context, input, raw, display string, images []string) error {
362 turn := orchestratedTurn{
363 input: input,
364 raw: raw,
365 display: display,
366 imageCandidates: append([]string(nil), images...),
367 imagesResolved: true,
368 }
369 if o.c.imageInputEnabled() {
370 turn.userImages = append([]string(nil), images...)
371 }
372 return o.runGoalLoopWithPreparedTurn(ctx, turn)
373 }
374
375 func (o *turnOrchestrator) runGoalLoopWithPreparedTurn(ctx context.Context, turn orchestratedTurn) error {
376 // Every accepted input is exactly one top-level turn. Automatic Goal work is
377 // owned exclusively by goalRoundDriver after the runtime becomes idle.
378 ctx = agent.WithSubagentImageCandidates(ctx, turn.imageCandidates)
379 return o.runOrchestratedTurn(ctx, turn)
380 }
381
382 func (o *turnOrchestrator) runEditedGoalLoopWithRawDisplay(ctx context.Context, input, raw, display, original string) error {
383 return o.runEditedGoalLoopWithImageRefsRawDisplay(ctx, input, raw, "", display, original)
384 }
385
386 func (o *turnOrchestrator) runEditedGoalLoopWithImageRefsRawDisplay(ctx context.Context, input, raw, imageRefs, display, original string) error {
387 turn := o.c.prepareOrchestratedTurnImages(orchestratedTurn{
388 input: input, raw: raw, imageRefs: imageRefs, display: display, editedOriginal: original,
389 })
390 ctx = agent.WithSubagentImageCandidates(ctx, turn.imageCandidates)
391 return o.runOrchestratedTurn(ctx, turn)
392 }
393
394 func (o *turnOrchestrator) runEditedGoalLoopWithFrozenImagesRawDisplay(ctx context.Context, input, raw, display, original string, images []string) error {
395 turn := orchestratedTurn{
396 input: input, raw: raw, display: display, editedOriginal: original,
397 imageCandidates: append([]string(nil), images...), imagesResolved: true,
398 }
399 if o.c.imageInputEnabled() {
400 turn.userImages = append([]string(nil), images...)
401 }
402 ctx = agent.WithSubagentImageCandidates(ctx, turn.imageCandidates)
403 return o.runOrchestratedTurn(ctx, turn)
404 }
405
405 lines GO