@sixb/agent 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/agent-prompt.d.ts +34 -28
  2. package/dist/agent-prompt.d.ts.map +1 -1
  3. package/dist/artifacts/publish-tool.d.ts +1 -1
  4. package/dist/attachments.d.ts +42 -1
  5. package/dist/attachments.d.ts.map +1 -1
  6. package/dist/child-files.d.ts +0 -5
  7. package/dist/child-files.d.ts.map +1 -1
  8. package/dist/computer-runner.d.ts +16 -7
  9. package/dist/computer-runner.d.ts.map +1 -1
  10. package/dist/context-budget.d.ts +23 -17
  11. package/dist/context-budget.d.ts.map +1 -1
  12. package/dist/context-compaction.d.ts +118 -18
  13. package/dist/context-compaction.d.ts.map +1 -1
  14. package/dist/context-guard.d.ts +69 -0
  15. package/dist/context-guard.d.ts.map +1 -0
  16. package/dist/conversation-messages.d.ts +33 -0
  17. package/dist/conversation-messages.d.ts.map +1 -0
  18. package/dist/execution-plan.d.ts +5 -1
  19. package/dist/execution-plan.d.ts.map +1 -1
  20. package/dist/failure.d.ts.map +1 -1
  21. package/dist/index.js +4916 -2697
  22. package/dist/index.js.map +41 -34
  23. package/dist/inline-images.d.ts +28 -0
  24. package/dist/inline-images.d.ts.map +1 -0
  25. package/dist/message-authors.d.ts +4 -4
  26. package/dist/message-authors.d.ts.map +1 -1
  27. package/dist/message-times.d.ts +4 -3
  28. package/dist/message-times.d.ts.map +1 -1
  29. package/dist/model-adapters.d.ts +6 -2
  30. package/dist/model-adapters.d.ts.map +1 -1
  31. package/dist/prompt-cache.d.ts +28 -0
  32. package/dist/prompt-cache.d.ts.map +1 -0
  33. package/dist/run-agent-turn.d.ts +33 -3
  34. package/dist/run-agent-turn.d.ts.map +1 -1
  35. package/dist/run-child.d.ts.map +1 -1
  36. package/dist/run-conversation-turn.d.ts.map +1 -1
  37. package/dist/run-environment.d.ts +35 -5
  38. package/dist/run-environment.d.ts.map +1 -1
  39. package/dist/run-files-lock.d.ts +16 -0
  40. package/dist/run-files-lock.d.ts.map +1 -0
  41. package/dist/run-subagent.d.ts +15 -1
  42. package/dist/run-subagent.d.ts.map +1 -1
  43. package/dist/run-workflow-agent-node.d.ts +5 -0
  44. package/dist/run-workflow-agent-node.d.ts.map +1 -1
  45. package/dist/sandbox-api-context.d.ts.map +1 -1
  46. package/dist/subagent-context.d.ts +50 -0
  47. package/dist/subagent-context.d.ts.map +1 -0
  48. package/dist/subagent-continuation.d.ts +10 -4
  49. package/dist/subagent-continuation.d.ts.map +1 -1
  50. package/dist/subagent-tools.d.ts +11 -0
  51. package/dist/subagent-tools.d.ts.map +1 -1
  52. package/dist/thread-context.d.ts +7 -2
  53. package/dist/thread-context.d.ts.map +1 -1
  54. package/dist/tools/bash.d.ts +8 -0
  55. package/dist/tools/bash.d.ts.map +1 -1
  56. package/dist/tools/model-spec.d.ts +7 -2
  57. package/dist/tools/model-spec.d.ts.map +1 -1
  58. package/dist/tools/result-media.d.ts +53 -10
  59. package/dist/tools/result-media.d.ts.map +1 -1
  60. package/dist/tools/result-output.d.ts +1 -1
  61. package/dist/tools/result-output.d.ts.map +1 -1
  62. package/dist/tools/tool-outputs.d.ts +63 -0
  63. package/dist/tools/tool-outputs.d.ts.map +1 -0
  64. package/dist/types.d.ts +9 -2
  65. package/dist/types.d.ts.map +1 -1
  66. package/package.json +4 -4
  67. package/src/agent-prompt.ts +178 -76
  68. package/src/attachments.ts +275 -84
  69. package/src/child-files.ts +1 -6
  70. package/src/computer-runner.ts +75 -23
  71. package/src/context-budget.ts +110 -94
  72. package/src/context-compaction.ts +1007 -187
  73. package/src/context-guard.ts +826 -0
  74. package/src/conversation-messages.ts +86 -0
  75. package/src/execution-plan.ts +22 -2
  76. package/src/failure.ts +11 -0
  77. package/src/inline-images.ts +69 -0
  78. package/src/message-authors.ts +5 -5
  79. package/src/message-times.ts +8 -5
  80. package/src/model-adapters.ts +59 -13
  81. package/src/prompt-cache.ts +40 -0
  82. package/src/run-agent-turn.ts +234 -72
  83. package/src/run-child.ts +30 -5
  84. package/src/run-conversation-turn.ts +16 -1
  85. package/src/run-environment.ts +553 -106
  86. package/src/run-files-lock.ts +118 -0
  87. package/src/run-subagent.ts +132 -46
  88. package/src/run-workflow-agent-node.ts +84 -10
  89. package/src/sandbox-api-context.ts +3 -0
  90. package/src/skills/sixb-artifacts/canvas.md +1 -1
  91. package/src/skills/sixb-artifacts/page.md +1 -1
  92. package/src/skills/sixb-artifacts/slides.md +1 -1
  93. package/src/subagent-context.ts +182 -0
  94. package/src/subagent-continuation.ts +11 -6
  95. package/src/subagent-tools.ts +73 -11
  96. package/src/thread-context.ts +9 -3
  97. package/src/tools/bash.ts +17 -1
  98. package/src/tools/model-spec.ts +9 -4
  99. package/src/tools/result-media.ts +286 -82
  100. package/src/tools/result-output.ts +4 -2
  101. package/src/tools/tool-outputs.ts +464 -0
  102. package/src/types.ts +14 -2
@@ -1,25 +1,31 @@
1
- import type { AgentMessage, AgentMessagePart } from "@sixb/core"
1
+ import type { AgentMessage, AgentMessagePart, AgentStepRequestSize } from "@sixb/core"
2
2
  import {
3
+ type AgentContextBudget,
3
4
  type AgentRunSession,
4
5
  createAgentMessageId,
6
+ measureAgentStepRequest,
5
7
  type PausableModelLoopResult,
8
+ type PrepareModelStepInput,
9
+ type RecoverModelStepInput,
6
10
  runModelLoop,
7
- toModelMessages,
8
11
  } from "@sixb/core/internal/agents"
9
12
  import { isAbortError } from "@sixb/core/internal/workers"
13
+ import { type ModelMessage, ModelProviderError, type ModelStep } from "@sixb/core/models"
10
14
  import {
11
15
  type AgentRunDiagnostic,
12
16
  type AgentRunFinishReason,
13
17
  type AgentRunRecord,
18
+ type AppendAgentMessageInput,
14
19
  type ConversationAgentRunRecord,
15
20
  coerceAgentRunFinishReason,
16
21
  } from "@sixb/core/storage"
17
- import { attachmentKey, toolResultAttachmentKey } from "./attachments"
18
- import { throwIfExecutionLost } from "./errors"
22
+ import { createAgentContextGuard } from "./context-guard"
23
+ import { conversationModelMessages, conversationModelSettings } from "./conversation-messages"
24
+ import { AgentContextCompactionError, throwIfExecutionLost } from "./errors"
19
25
  import type { ResolvedAgentExecutionPlan } from "./execution-plan"
20
- import { type ConversationReaders, conversationAuthors } from "./message-authors"
21
- import { userMessageTimes } from "./message-times"
26
+ import type { ConversationReaders } from "./message-authors"
22
27
  import { agentTraceFromModelSteps, agentTraceFromPartialModelLoop } from "./model-adapters"
28
+ import type { ConversationAgentExecutionEnvironment } from "./run-environment"
23
29
  import { monitorSandboxReadiness } from "./sandbox-readiness"
24
30
  import type { LoadedAgentThreadModelContext } from "./thread-context"
25
31
  import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
@@ -48,6 +54,24 @@ export interface RunAgentTurnInput {
48
54
  readonly threadContext: LoadedAgentThreadModelContext
49
55
  /** What the turn's children ask it, and the work it waits for, when it can delegate. */
50
56
  readonly children?: TurnChildren
57
+ /**
58
+ * The model's limit every call of the turn keeps under (see createAgentContextGuard), and how
59
+ * it compacts the history before it from within. Without them, only the turn's start was
60
+ * weighed.
61
+ */
62
+ readonly contextLimits?: {
63
+ readonly budget: AgentContextBudget
64
+ /** The bytes per token the turn's history was measured at, else its run's starting one. */
65
+ readonly bytesPerToken?: number
66
+ /** What the run's latest counted call measured (see prepareAgentModel). */
67
+ readonly measuredBytesPerToken?: () => number | undefined
68
+ readonly compactInTurn?: ConversationAgentExecutionEnvironment["compactInTurn"]
69
+ }
70
+ /**
71
+ * Handed the answer so far after each step that completed, as the message the turn would
72
+ * append: a turn that fails then records it with its failure, and keeps that work.
73
+ */
74
+ readonly onWork?: (message: AppendAgentMessageInput) => void
51
75
  }
52
76
 
53
77
  /**
@@ -77,45 +101,11 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
77
101
  const { id: projectId, tools } = context
78
102
  const runId = run.id
79
103
 
80
- const { threadContext } = input
81
- const { attachmentContext } = context
82
- const sentTimes = userMessageTimes(threadContext.history, context.projectTimeZone)
83
- const authors = input.conversation
84
- ? conversationAuthors({
85
- conversation: input.conversation,
86
- messages: threadContext.retainedMessages,
87
- })
88
- : undefined
89
- const newestUserMessageId = threadContext.retainedMessages
90
- .filter((message) => message.role === "user")
91
- .at(-1)?.id
92
-
93
- const modelMessages = toModelMessages(threadContext.modelMessages, {
94
- // Who takes part, then when, then who wrote it: `<sixb_author>` stays the message's last tag.
95
- userMessageSuffix: (message) => {
96
- if (!message.id) return undefined
97
-
98
- const closing = [
99
- message.id === newestUserMessageId ? authors?.section : undefined,
100
- sentTimes.get(message.id),
101
- authors?.byMessageId.get(message.id),
102
- ]
103
- return closing.filter(Boolean).join("\n") || undefined
104
- },
105
- fileText: ({ message, partIndex }) =>
106
- message.id
107
- ? attachmentContext?.promptTextByPartKey.get(attachmentKey(message.id, partIndex))
108
- : undefined,
109
- fileData: ({ message, partIndex }) =>
110
- message.id
111
- ? attachmentContext?.modelFileDataByPartKey.get(attachmentKey(message.id, partIndex))
112
- : undefined,
113
- toolResultFileText: ({ message, partIndex, contentIndex }) =>
114
- message.id
115
- ? attachmentContext?.promptTextByPartKey.get(
116
- toolResultAttachmentKey(message.id, partIndex, contentIndex)
117
- )
118
- : undefined,
104
+ const modelMessages = conversationModelMessages({
105
+ threadContext: input.threadContext,
106
+ ...(context.attachmentContext ? { attachmentContext: context.attachmentContext } : {}),
107
+ ...(input.conversation ? { conversation: input.conversation } : {}),
108
+ project: { timeZone: context.projectTimeZone, locale: context.projectLocale },
119
109
  })
120
110
 
121
111
  const sandboxReadiness = monitorSandboxReadiness(context.sandboxReady)
@@ -146,30 +136,129 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
146
136
  })
147
137
  }
148
138
 
139
+ // What every request starts with: the system prompt, the conversation, then what children of
140
+ // earlier turns still wait on.
141
+ const requestHead = (systemPrompt: string, conversation: readonly ModelMessage[]) => [
142
+ { role: "system" as const, content: systemPrompt },
143
+ ...conversation,
144
+ ...(input.children?.waiting
145
+ ? [
146
+ {
147
+ role: "user" as const,
148
+ content: [{ type: "text" as const, text: input.children.waiting }],
149
+ },
150
+ ]
151
+ : []),
152
+ ]
153
+ // What each step's request carried, as it was sent, for its step-start to record. The prompt's
154
+ // sections are known for the prompt the turn rendered, then for the one its compaction rendered.
155
+ const stepRequests: AgentStepRequestSize[] = []
156
+ let systemPromptSize = context.systemPromptSize
157
+ const recordRequest = (stepIndex: number, messages: readonly ModelMessage[]) => {
158
+ stepRequests[stepIndex] = measureAgentStepRequest({
159
+ messages,
160
+ tools,
161
+ ...(systemPromptSize ? { systemPrompt: systemPromptSize } : {}),
162
+ ...(context.contextDirectory === undefined
163
+ ? {}
164
+ : { contextDirectory: context.contextDirectory }),
165
+ })
166
+ }
167
+
168
+ const limits = input.contextLimits
169
+ const compactInTurn = limits?.compactInTurn
170
+ const guard =
171
+ limits &&
172
+ createAgentContextGuard({
173
+ budget: limits.budget,
174
+ ...(limits.bytesPerToken === undefined ? {} : { bytesPerToken: limits.bytesPerToken }),
175
+ ...(limits.measuredBytesPerToken === undefined
176
+ ? {}
177
+ : { measuredBytesPerToken: limits.measuredBytesPerToken }),
178
+ tools: tools.map((tool) => ({
179
+ name: tool.name,
180
+ description: tool.description,
181
+ inputSchema: tool.inputSchema,
182
+ })),
183
+ ...(compactInTurn
184
+ ? {
185
+ compact: async (compaction) => {
186
+ const request = await compactInTurn(compaction)
187
+ if (request) systemPromptSize = request.systemPromptSize
188
+ return request && requestHead(request.systemPrompt, request.messages)
189
+ },
190
+ }
191
+ : {}),
192
+ })
193
+ const guardedStep = guard
194
+ ? async (step: Parameters<typeof guard.prepareStep>[0]) => {
195
+ const prepared = await context.prepareStep?.(step)
196
+ const guarded = await guard.prepareStep({
197
+ ...step,
198
+ messages: prepared?.messages ?? step.messages,
199
+ })
200
+ // The guard's request, when it reduced the one prepared, and the room its answer has.
201
+ return { ...prepared, ...guarded }
202
+ }
203
+ : context.prepareStep
204
+ const prepareStep = async (step: PrepareModelStepInput) => {
205
+ const prepared = await guardedStep?.(step)
206
+ recordRequest(step.stepIndex, prepared?.messages ?? step.messages)
207
+ return prepared
208
+ }
209
+ const recoverStep =
210
+ guard &&
211
+ (async (step: RecoverModelStepInput) => {
212
+ const recovered = await guard.recoverStep(step)
213
+ if (recovered?.messages) recordRequest(step.stepIndex, recovered.messages)
214
+ return recovered
215
+ })
216
+
217
+ // The answer so far, as one message whatever step it is at.
218
+ const workMessageId = createAgentMessageId()
219
+ const finishedSteps: ModelStep[] = []
220
+ const recordStep = (step: ModelStep) => {
221
+ finishedSteps.push(step)
222
+ input.onWork?.({
223
+ id: workMessageId,
224
+ projectId,
225
+ threadId: run.threadId,
226
+ runId,
227
+ role: "assistant",
228
+ parts: recordStepRequests(
229
+ markReducedSteps(
230
+ agentTraceFromModelSteps(
231
+ finishedSteps,
232
+ { threadId: run.threadId, runId },
233
+ context.outputFileOf
234
+ ),
235
+ guard?.reducedFromStep()
236
+ ),
237
+ stepRequests
238
+ ),
239
+ ...(context.authorPrincipal === undefined
240
+ ? {}
241
+ : { authorPrincipal: context.authorPrincipal }),
242
+ })
243
+ }
244
+
149
245
  try {
150
246
  let chunkIndex = 0
151
247
  let result: PausableModelLoopResult
152
248
  try {
153
249
  result = await runModelLoop({
154
250
  model: plan.model,
155
- messages: [
156
- {
157
- role: "system",
158
- content: context.systemPrompt,
159
- },
160
- ...modelMessages,
161
- ...(input.children?.waiting
162
- ? [
163
- {
164
- role: "user" as const,
165
- content: [{ type: "text" as const, text: input.children.waiting }],
166
- },
167
- ]
168
- : []),
169
- ],
251
+ messages: requestHead(context.systemPrompt, modelMessages),
170
252
  tools,
171
- ...(plan.reasoning === undefined ? {} : { reasoning: plan.reasoning }),
172
- ...(context.prepareStep === undefined ? {} : { prepareStep: context.prepareStep }),
253
+ ...conversationModelSettings({
254
+ reasoning: plan.reasoning,
255
+ projectId,
256
+ threadId: run.threadId,
257
+ }),
258
+ ...(plan.maxSteps === undefined ? {} : { maxSteps: plan.maxSteps }),
259
+ prepareStep,
260
+ ...(recoverStep ? { recoverStep } : {}),
261
+ onStepEnd: recordStep,
173
262
  // A child's question the model has not read comes before its answer ends the turn.
174
263
  ...(input.children === undefined
175
264
  ? {}
@@ -193,16 +282,37 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
193
282
  } catch (error) {
194
283
  const interrupted = await finalizeIfInterrupted(error)
195
284
  if (interrupted) return interrupted
285
+
286
+ // Compacted and asked again, the request still did not fit the model's window.
287
+ if (error instanceof ModelProviderError && error.reason === "context-window-exceeded") {
288
+ throw new AgentContextCompactionError(
289
+ "context_limit_exceeded",
290
+ runId,
291
+ "The conversation still exceeds the model's context window after it was reduced. Start a new conversation or select a model with a larger context window.",
292
+ { cause: error }
293
+ )
294
+ }
196
295
  throw error
197
296
  }
198
297
 
199
- interruptedParts =
200
- result.status === "aborted"
201
- ? agentTraceFromPartialModelLoop(result.steps, result.partialContent, {
202
- threadId: run.threadId,
203
- runId,
204
- })
205
- : agentTraceFromModelSteps(result.steps, { threadId: run.threadId, runId })
298
+ interruptedParts = recordStepRequests(
299
+ markReducedSteps(
300
+ result.status === "aborted"
301
+ ? agentTraceFromPartialModelLoop(
302
+ result.steps,
303
+ result.partialContent,
304
+ { threadId: run.threadId, runId },
305
+ context.outputFileOf
306
+ )
307
+ : agentTraceFromModelSteps(
308
+ result.steps,
309
+ { threadId: run.threadId, runId },
310
+ context.outputFileOf
311
+ ),
312
+ guard?.reducedFromStep()
313
+ ),
314
+ stepRequests
315
+ )
206
316
 
207
317
  const interruptedAfterModel = await finalizeIfInterrupted()
208
318
  if (interruptedAfterModel) return interruptedAfterModel
@@ -235,9 +345,10 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
235
345
  ? "awaiting_approval"
236
346
  : (coerceAgentRunFinishReason(result.finishReason) ?? "unknown")
237
347
  const assistant: AgentMessage = { role: "assistant", parts: interruptedParts }
238
- const diagnostics = [outputLimitDiagnostic(finishReason)].filter(
239
- (diagnostic) => diagnostic !== undefined
240
- )
348
+ const diagnostics = [
349
+ outputLimitDiagnostic(finishReason),
350
+ finishReason === "awaiting_approval" ? undefined : stepLimitDiagnostic(result),
351
+ ].filter((diagnostic) => diagnostic !== undefined)
241
352
  const assistantMessageId = createAgentMessageId()
242
353
 
243
354
  const interruptedBeforeCommit = await finalizeIfInterrupted()
@@ -279,6 +390,43 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
279
390
  * waiting, or decided and not reported to the model yet, its children's included.
280
391
  */
281
392
 
393
+ /**
394
+ * Mark each step from `fromStep` on as answering a request the turn reduced, for the next turn's
395
+ * estimate not to go by what those calls read.
396
+ */
397
+ export function markReducedSteps(
398
+ parts: readonly AgentMessagePart[],
399
+ fromStep: number | undefined
400
+ ): readonly AgentMessagePart[] {
401
+ if (fromStep === undefined) return parts
402
+
403
+ let step = -1
404
+ return parts.map((part) => {
405
+ if (part.type !== "step-start") return part
406
+
407
+ step += 1
408
+ return step >= fromStep ? { type: "step-start", reducedRequest: true } : part
409
+ })
410
+ }
411
+
412
+ /**
413
+ * Record on each step-start what its request carried, by step: the next turn's context meter
414
+ * reads the system prompt and tools the latest one sent.
415
+ */
416
+ export function recordStepRequests(
417
+ parts: readonly AgentMessagePart[],
418
+ requests: readonly (AgentStepRequestSize | undefined)[]
419
+ ): readonly AgentMessagePart[] {
420
+ let step = -1
421
+ return parts.map((part) => {
422
+ if (part.type !== "step-start") return part
423
+
424
+ step += 1
425
+ const request = requests[step]
426
+ return request ? { ...part, request } : part
427
+ })
428
+ }
429
+
282
430
  /**
283
431
  * Whether the worker's stop, rather than the user's, ended the turn. Whichever fired first wins:
284
432
  * the combined turn signal carries the reason of the first source that aborted it.
@@ -302,6 +450,20 @@ function outputLimitDiagnostic(finishReason: AgentRunFinishReason): AgentRunDiag
302
450
  }
303
451
  }
304
452
 
453
+ /**
454
+ * A turn the project's `maxSteps` stopped keeps its work as its answer, and says so: Continue starts
455
+ * a turn that goes on from it, as a retry would only stop at the same place.
456
+ */
457
+ function stepLimitDiagnostic(result: PausableModelLoopResult): AgentRunDiagnostic | undefined {
458
+ if (result.status !== "completed" || !result.stepLimitReached) return undefined
459
+ return {
460
+ code: "step_limit_reached",
461
+ severity: "warning",
462
+ scope: "run",
463
+ message: "The agent reached its step limit before producing a final answer.",
464
+ }
465
+ }
466
+
305
467
  /** Persist a cancelled turn, retaining coherent partial content when any was produced. */
306
468
  async function finalizeInterruptedTurn(input: {
307
469
  readonly session: AgentRunSession
package/src/run-child.ts CHANGED
@@ -195,13 +195,14 @@ export class ChildRunner {
195
195
  const prepared = await (this.host.prepare
196
196
  ? this.host.prepare(prepare, turnSignal)
197
197
  : prepare())
198
- const { context, execution, thread, conversation, plan, history } = prepared
198
+ const { context, execution, thread, conversation, plan, budget, history } = prepared
199
+ const { measuredBytesPerToken } = prepared
199
200
  await session.events.publishStarted(run)
200
201
  runtime = createAgentTurnRuntime({ signal: turnSignal })
201
202
  // A message its parent sent while it was queued is read at its first step. What a paused run
202
203
  // it continues never read is in its trigger already.
203
204
  const inbox = new SubagentInbox(parent.family.child(run.id), run)
204
- environment = await createSubagentEnvironment({
205
+ const childEnvironment = await createSubagentEnvironment({
205
206
  session,
206
207
  openSandbox: this.host.openSandbox({ session, context, execution, thread }),
207
208
  context,
@@ -214,12 +215,22 @@ export class ChildRunner {
214
215
  history,
215
216
  signal: runtime.signal,
216
217
  onDetachedTeardown: (teardown) => this.host.onDetachedTeardown(teardown),
218
+ preflight: { budget, runtime },
217
219
  })
220
+ environment = childEnvironment
221
+ const { compactInRun, bytesPerToken } = childEnvironment
218
222
  await runSubagent({
219
223
  history,
220
224
  inbox,
221
225
  context: environment.turnContext,
222
226
  plan,
227
+ contextLimits: {
228
+ budget,
229
+ measuredBytesPerToken,
230
+ thread: childEnvironment.thread,
231
+ ...(compactInRun ? { compactInRun } : {}),
232
+ ...(bytesPerToken === undefined ? {} : { bytesPerToken }),
233
+ },
223
234
  run,
224
235
  session,
225
236
  thread,
@@ -302,15 +313,29 @@ export class ChildRunner {
302
313
  const configured = resolveRunPlan(runPlan, {
303
314
  model: await session.models.language(runPlan.model),
304
315
  })
305
- const plan = Object.freeze({ ...configured, model: prepareAgentModel(configured).model })
316
+ const { model, budget, measuredBytesPerToken } = prepareAgentModel(configured)
317
+ const plan = Object.freeze({ ...configured, model })
306
318
  const requester = agentRequester(execution.requestedBy, child.names)
307
319
  const context: AgentExecutionContext = {
308
320
  ...this.host.settings,
309
321
  ...(requester === undefined ? {} : { requester }),
310
322
  blobStorage: session.files,
311
323
  }
312
- const history = { messages: child.messages, ...(child.paused ? { paused: child.paused } : {}) }
313
- return { context, execution, thread, conversation: child.conversation, plan, history }
324
+ const history = {
325
+ ...child.history,
326
+ ...(child.task ? { task: child.task } : {}),
327
+ ...(child.paused ? { paused: child.paused } : {}),
328
+ }
329
+ return {
330
+ context,
331
+ execution,
332
+ thread,
333
+ conversation: child.conversation,
334
+ plan,
335
+ budget,
336
+ measuredBytesPerToken,
337
+ history,
338
+ }
314
339
  }
315
340
  }
316
341
 
@@ -12,6 +12,7 @@ import type {
12
12
  AgentRunRecord,
13
13
  AgentThreadParticipantRecord,
14
14
  AgentThreadRecord,
15
+ AppendAgentMessageInput,
15
16
  ConversationAgentRunRecord,
16
17
  ExecutionRecord,
17
18
  SubagentRunRecord,
@@ -78,6 +79,8 @@ export async function runConversationTurn(input: {
78
79
  let environment: ConversationAgentExecutionEnvironment | null = null
79
80
  let runtime: AgentTurnRuntime | null = null
80
81
  let delegation: SubagentCoordinator | undefined
82
+ // The answer so far: a turn that fails keeps the steps it completed.
83
+ let work: AppendAgentMessageInput | undefined
81
84
  // A user cancel joins the turn's abort sources, so it stops the model stream as a shutdown does.
82
85
  const turnSignal = AbortSignal.any([signal, session.cancelled])
83
86
 
@@ -134,6 +137,17 @@ export async function runConversationTurn(input: {
134
137
  runtime,
135
138
  threadContext: environment.threadContext,
136
139
  children: await delegation.turnChildren(),
140
+ contextLimits: {
141
+ budget: prepared.model.budget,
142
+ measuredBytesPerToken: prepared.model.measuredBytesPerToken,
143
+ ...(environment.compactInTurn ? { compactInTurn: environment.compactInTurn } : {}),
144
+ ...(environment.bytesPerToken === undefined
145
+ ? {}
146
+ : { bytesPerToken: environment.bytesPerToken }),
147
+ },
148
+ onWork: (message) => {
149
+ work = message
150
+ },
137
151
  })
138
152
  } catch (caughtError) {
139
153
  let error = caughtError
@@ -163,7 +177,8 @@ export async function runConversationTurn(input: {
163
177
  const finalized = await recordFate(
164
178
  session,
165
179
  aborted ? "cancelled" : "failed",
166
- interrupted ? new AgentTurnInterruptedError(run.id) : error
180
+ interrupted ? new AgentTurnInterruptedError(run.id) : error,
181
+ !aborted && work ? [work] : undefined
167
182
  )
168
183
  if (finalized) {
169
184
  if (finalized.run.status === "failed") {