@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,8 +1,11 @@
1
1
  import { posix } from "node:path"
2
2
  import type { Principal } from "@sixb/core"
3
3
  import {
4
+ type AgentContextBudget,
4
5
  type AgentRunArtifacts,
5
6
  type AgentRunSession,
7
+ type AgentSystemPromptSize,
8
+ type AgentToolCallFile,
6
9
  type AgentTurnHistory,
7
10
  conversationThreadId,
8
11
  subagentSandboxFiles,
@@ -11,13 +14,20 @@ import type { RenderedOntologyDocs } from "@sixb/core/internal/ontology"
11
14
  import type { WorkflowIOSnapshot } from "@sixb/core/internal/workflows"
12
15
  import type { ModelTool } from "@sixb/core/models"
13
16
  import type {
17
+ AgentContextCheckpointReason,
18
+ AgentMessageRecord,
14
19
  AgentThreadRecord,
15
20
  ConversationAgentRunRecord,
16
21
  SubagentRunRecord,
17
22
  WorkflowAgentNodeRunRecord,
18
23
  } from "@sixb/core/storage"
19
24
  import { NEVER_ABORTED_SIGNAL, waitForAbort } from "./abort"
20
- import { type AgentExecutionMode, agentRuntimeFacts, renderAgentSystemPrompt } from "./agent-prompt"
25
+ import {
26
+ type AgentExecutionMode,
27
+ measureAgentSystemPrompt,
28
+ renderCurrentTime,
29
+ sentSettings,
30
+ } from "./agent-prompt"
21
31
  import { assertAgentRuntimeProfile } from "./agent-runtime/preflight"
22
32
  import {
23
33
  type InstalledArtifacts,
@@ -32,12 +42,22 @@ import {
32
42
  prepareAgentAttachments,
33
43
  } from "./attachments"
34
44
  import { prepareHandedFiles } from "./child-files"
35
- import type { AgentContextBudget } from "./context-budget"
36
- import { type LoadConversationMemory, prepareAgentConversationContext } from "./context-compaction"
45
+ import {
46
+ type AgentThreadCompactionInput,
47
+ type BuildConversationRequest,
48
+ type ConversationRequest,
49
+ compactAgentConversationInTurn,
50
+ compactAgentThreadInRun,
51
+ contextEstimateTools,
52
+ type LoadConversationMemory,
53
+ prepareAgentConversationContext,
54
+ } from "./context-compaction"
37
55
  import { type ConversationMemory, loadConversationMemory } from "./conversation-memory"
56
+ import { conversationModelMessages } from "./conversation-messages"
38
57
  import { isLostExecution } from "./errors"
39
58
  import type { ResolvedAgentExecutionPlan } from "./execution-plan"
40
- import type { ConversationReaders } from "./message-authors"
59
+ import { InlineImageBudget } from "./inline-images"
60
+ import { type ConversationReaders, conversationAuthors } from "./message-authors"
41
61
  import { type AgentErrorDetails, type AgentToolCaller, projectModelTools } from "./model-adapters"
42
62
  import type { AcquiredRunSandbox, BeforeFinalizeOptions, RunSandbox } from "./run-sandbox"
43
63
  import {
@@ -49,13 +69,31 @@ import {
49
69
  import { AgentSandboxFileRegistry } from "./sandbox-file-registry"
50
70
  import type { AgentSandboxHandle } from "./sandbox-handle"
51
71
  import { MEMORY_SKILL } from "./skills/built-in"
72
+ import {
73
+ preflightSubagentContext,
74
+ type SubagentThreadContext,
75
+ subagentModelMessages,
76
+ subagentPromptCaching,
77
+ subagentThreadContext,
78
+ } from "./subagent-context"
52
79
  import type { SubagentHistory } from "./subagent-continuation"
53
80
  import { agentThreadModelContext, type LoadedAgentThreadModelContext } from "./thread-context"
54
81
  import { createBashTool } from "./tools/bash"
82
+ import { agentModelToolSpecs } from "./tools/model-spec"
55
83
  import { createReadTool } from "./tools/read"
56
- import { AgentToolResultMediaBridge } from "./tools/result-media"
84
+ import {
85
+ AgentToolResultMediaBridge,
86
+ allocateInlineImages,
87
+ replayToolFiles,
88
+ type SuppliesToolFiles,
89
+ } from "./tools/result-media"
57
90
  import { AgentFileBudget, createAgentToolFiles, installAgentToolFiles } from "./tools/tool-files"
58
- import { createViewFileTool } from "./tools/view-file"
91
+ import {
92
+ restoreSavedToolOutputs,
93
+ savedToolOutputFiles,
94
+ ToolOutputFiles,
95
+ } from "./tools/tool-outputs"
96
+ import { createViewFileTool, VIEW_FILE_TOOL_SPEC } from "./tools/view-file"
59
97
  import type { AgentTurnRuntime } from "./turn-runtime"
60
98
  import type { AgentExecutionContext, AgentRunFiles, AgentTurnContext } from "./types"
61
99
  import { prepareWorkflowInputAttachments } from "./workflow-input-attachments"
@@ -72,6 +110,16 @@ export interface AgentExecutionEnvironment {
72
110
  export interface ConversationAgentExecutionEnvironment extends AgentExecutionEnvironment {
73
111
  /** The history the turn runs on: as it started, or as its compaction left it. */
74
112
  readonly threadContext: LoadedAgentThreadModelContext
113
+ /**
114
+ * Compact the history before the turn from within it, once: the request the turn's calls then
115
+ * start with. Undefined when it could not. Only a turn whose environment ran its preflight has
116
+ * it.
117
+ */
118
+ readonly compactInTurn?: (input: {
119
+ readonly reason: AgentContextCheckpointReason
120
+ }) => Promise<ConversationRequest | undefined>
121
+ /** The bytes per token the preflight measured the history at, which the turn's calls go by. */
122
+ readonly bytesPerToken?: number
75
123
  }
76
124
 
77
125
  /**
@@ -138,6 +186,23 @@ export interface CreateSubagentEnvironmentInput extends CreateAgentEnvironmentIn
138
186
  readonly history: SubagentHistory
139
187
  /** Framework-owned tools of a child: `ask_parent`. */
140
188
  readonly frameworkTools?: readonly ModelTool[]
189
+ /** Weigh the thread before the first call, and compact it on the child's thread when needed. */
190
+ readonly preflight?: { readonly budget: AgentContextBudget; readonly runtime: AgentTurnRuntime }
191
+ }
192
+
193
+ export interface SubagentAgentExecutionEnvironment extends AgentExecutionEnvironment {
194
+ /** The thread the child runs on: as it started, or as its compaction left it. */
195
+ readonly thread: SubagentThreadContext
196
+ /**
197
+ * Compact the thread before the run from within it, once: the request the run's calls then
198
+ * start with. Undefined when it could not. Only a child whose environment ran its preflight has
199
+ * it.
200
+ */
201
+ readonly compactInRun?: (input: {
202
+ readonly reason: AgentContextCheckpointReason
203
+ }) => Promise<ConversationRequest | undefined>
204
+ /** The bytes per token the preflight measured the thread at, which the run's calls go by. */
205
+ readonly bytesPerToken?: number
141
206
  }
142
207
 
143
208
  export interface CreateWorkflowAgentNodeEnvironmentInput extends CreateAgentEnvironmentInput {
@@ -165,6 +230,14 @@ export async function createConversationAgentEnvironment(
165
230
  onFailure: (error) => failure.abort(error),
166
231
  })
167
232
  let environment: AgentExecutionEnvironment | undefined
233
+ // A workspace the prompt describes is acquired once: by the summary that continues the turn's
234
+ // prompt when the turn compacts, else when the environment starts.
235
+ let acquisition: Promise<AcquiredRunSandbox> | undefined
236
+ let provisioning = false
237
+ const acquire = () => {
238
+ acquisition ??= sandbox.acquire()
239
+ return acquisition
240
+ }
168
241
  // The prompt shows memory as of the thread's start or its latest compaction (see
169
242
  // loadConversationMemory).
170
243
  const threadCreatedAt = input.thread?.createdAt ?? run.createdAt
@@ -173,40 +246,20 @@ export async function createConversationAgentEnvironment(
173
246
  session: input.session,
174
247
  asOf: checkpoint?.createdAt ?? threadCreatedAt,
175
248
  })
176
- try {
177
- const { ontologyDocs } = plan
178
- // Resolve application access before any compaction model call. Once acquired, this
179
- // environment owns preservation even if history, attachments or runtime preparation fail.
180
- const prepared = preflight
181
- ? await prepareAgentConversationContext({
182
- context,
183
- session: input.session,
184
- plan,
185
- ontologyIndex: ontologyDocs.index,
186
- contextDirectory: sandbox.contextDirectory,
187
- run,
188
- history: input.history,
189
- ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
190
- budget: preflight.budget,
191
- runtime: {
192
- ...preflight.runtime,
193
- signal: sandboxSignal,
194
- assertCanContinue() {
195
- preflight.runtime.assertCanContinue()
196
- failure.signal.throwIfAborted()
197
- },
198
- },
199
- frameworkTools: input.frameworkTools,
200
- loadMemory,
201
- })
249
+ const publishing =
250
+ input.thread && run.execution
251
+ ? {
252
+ artifacts: input.session.artifacts,
253
+ threadId: input.thread.id,
254
+ owner: input.thread.ownerPrincipal,
255
+ }
202
256
  : undefined
203
- const threadContext = prepared?.threadContext ?? agentThreadModelContext(input.history)
204
- const messages = threadContext.retainedMessages
205
- const [inlineImages, memory] = await Promise.all([
206
- modelSupportsInlineImages(plan.model),
207
- prepared ? prepared.memory : loadMemory(threadContext.checkpoint),
208
- ])
209
- const attachmentContext = await prepareAgentAttachments({
257
+
258
+ // What a history's files make of the request: its attachments and the images its tools showed,
259
+ // within one request's inline image budget, the history first.
260
+ const prepareFiles = async (messages: readonly AgentMessageRecord[]) => {
261
+ const inlineImages = await modelSupportsInlineImages(plan.model)
262
+ const attachments = await prepareAgentAttachments({
210
263
  projectId: context.id,
211
264
  threadId: run.threadId,
212
265
  messages,
@@ -216,40 +269,160 @@ export async function createConversationAgentEnvironment(
216
269
  inlineImages,
217
270
  signal: sandboxSignal,
218
271
  })
272
+
273
+ const imageBudget = new InlineImageBudget()
274
+ const attachmentContext = await allocateInlineImages({
275
+ messages,
276
+ attachments,
277
+ toolFiles: replayToolFiles({
278
+ messages,
279
+ suppliesToolFiles: suppliesToolFiles(plan),
280
+ supportsImages: inlineImages,
281
+ }),
282
+ budget: imageBudget,
283
+ blobStorage: context.blobStorage,
284
+ signal: sandboxSignal,
285
+ })
286
+ return { attachmentContext, imageBudget }
287
+ }
288
+ const authorsOf = (messages: readonly AgentMessageRecord[]) =>
289
+ input.conversation
290
+ ? conversationAuthors({ conversation: input.conversation, messages }).section
291
+ : undefined
292
+
293
+ // The request this turn's calls would send for a history, built as the environment and
294
+ // runAgentTurn build it: the summary continues it, so the provider reads it from its cache.
295
+ const conversationRequest: BuildConversationRequest = async ({ threadContext, memory }) => {
296
+ const { attachmentContext } = await prepareFiles(threadContext.retainedMessages)
297
+ const workspace = sandbox.waitBeforeModel
298
+ ? await waitForAbort(acquire(), sandboxSignal)
299
+ : undefined
300
+ const conversation = authorsOf(threadContext.retainedMessages)
301
+
302
+ const systemPrompt = measureEnvironmentSystemPrompt({
303
+ mode: "conversation",
304
+ sandbox,
305
+ context,
306
+ plan,
307
+ ontologyDocs: plan.ontologyDocs,
308
+ ...(workspace ? { workspace } : {}),
309
+ ...(conversation === undefined ? {} : { conversation }),
310
+ ...(memory ? { memory } : {}),
311
+ })
312
+
313
+ return {
314
+ systemPrompt: systemPrompt.text,
315
+ systemPromptSize: systemPrompt,
316
+ tools: [
317
+ ...agentModelToolSpecs(plan.tools, { publishes: publishing !== undefined }),
318
+ ...(input.frameworkTools ?? []),
319
+ ],
320
+ messages: conversationModelMessages({
321
+ threadContext,
322
+ attachmentContext,
323
+ ...(input.conversation ? { conversation: input.conversation } : {}),
324
+ project: { timeZone: context.timeZone, locale: context.locale },
325
+ }),
326
+ }
327
+ }
328
+
329
+ try {
330
+ const { ontologyDocs } = plan
331
+ // What the conversation's compaction reads and writes through, before the turn or during it.
332
+ const compaction = preflight && {
333
+ context,
334
+ session: input.session,
335
+ plan,
336
+ ontologyIndex: ontologyDocs.index,
337
+ contextDirectory: sandbox.contextDirectory,
338
+ run,
339
+ ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
340
+ budget: preflight.budget,
341
+ runtime: {
342
+ ...preflight.runtime,
343
+ signal: sandboxSignal,
344
+ assertCanContinue() {
345
+ preflight.runtime.assertCanContinue()
346
+ failure.signal.throwIfAborted()
347
+ },
348
+ },
349
+ frameworkTools: input.frameworkTools,
350
+ loadMemory,
351
+ conversationRequest,
352
+ }
353
+ // Resolve application access before any compaction model call. Once acquired, this
354
+ // environment owns preservation even if history, attachments or runtime preparation fail.
355
+ const prepared = compaction
356
+ ? await prepareAgentConversationContext({ ...compaction, history: input.history })
357
+ : undefined
358
+ const threadContext = prepared?.threadContext ?? agentThreadModelContext(input.history)
359
+ const messages = threadContext.retainedMessages
360
+ const conversation = authorsOf(messages)
361
+ const [{ attachmentContext, imageBudget }, memory] = await Promise.all([
362
+ prepareFiles(messages),
363
+ prepared ? prepared.memory : loadMemory(threadContext.checkpoint),
364
+ ])
219
365
  environment = await startAgentEnvironment({
220
366
  mode: "conversation",
221
367
  sandbox,
368
+ // From here the environment gives back what it acquires.
369
+ acquire: () => {
370
+ provisioning = true
371
+ return acquire()
372
+ },
222
373
  sandboxSignal,
223
374
  failureSignal: failure.signal,
224
375
  context,
225
376
  plan,
226
377
  runId: run.id,
227
378
  threadId: run.threadId,
228
- callTool: (call, options) => input.session.callTool(call, options),
229
- ...(input.thread && run.execution
230
- ? {
231
- publishing: {
232
- artifacts: input.session.artifacts,
233
- threadId: input.thread.id,
234
- owner: input.thread.ownerPrincipal,
235
- },
236
- }
379
+ ...(input.thread?.movedAt
380
+ ? { workspaceMovedAt: new Date(input.thread.movedAt).toISOString() }
237
381
  : {}),
382
+ callTool: (call, options) => input.session.callTool(call, options),
383
+ ...(publishing ? { publishing } : {}),
238
384
  apiBaseUrl,
239
385
  attachmentContext,
386
+ toolOutputs: savedToolOutputFiles(messages),
387
+ imageBudget,
240
388
  ontologyDocs,
241
389
  frameworkTools: input.frameworkTools,
242
390
  ...(memory ? { memory } : {}),
391
+ ...(conversation === undefined ? {} : { conversation }),
243
392
  onDetachedTeardown: input.onDetachedTeardown,
244
393
  })
245
- return { ...environment, threadContext }
394
+
395
+ // The turn compacts from within at most once: a run writes one checkpoint.
396
+ const compactInTurn: ConversationAgentExecutionEnvironment["compactInTurn"] =
397
+ compaction &&
398
+ (async ({ reason }) => {
399
+ const compacted = await compactAgentConversationInTurn({
400
+ ...compaction,
401
+ threadContext,
402
+ memory,
403
+ reason,
404
+ coldCache: false,
405
+ })
406
+ return (
407
+ compacted &&
408
+ conversationRequest({ threadContext: compacted.threadContext, memory: compacted.memory })
409
+ )
410
+ })
411
+ return {
412
+ ...environment,
413
+ threadContext,
414
+ ...(compactInTurn ? { compactInTurn } : {}),
415
+ ...(prepared?.bytesPerToken === undefined ? {} : { bytesPerToken: prepared.bytesPerToken }),
416
+ }
246
417
  } catch (error) {
247
418
  // Preparation can fail before the worker receives this environment. Preserve here, before
248
419
  // the worker records the run's terminal outcome; a lost execution must touch nothing.
249
420
  try {
250
421
  if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.()
251
422
  } finally {
252
- await environment?.dispose()
423
+ // A workspace the summary acquired goes back as the environment would have given it.
424
+ if (environment) await environment.dispose()
425
+ else if (acquisition && !provisioning) await releaseAcquisition(sandbox, acquisition)
253
426
  }
254
427
  throw error
255
428
  }
@@ -266,20 +439,42 @@ export async function createConversationAgentEnvironment(
266
439
  */
267
440
  export async function createSubagentEnvironment(
268
441
  input: CreateSubagentEnvironmentInput
269
- ): Promise<AgentExecutionEnvironment> {
442
+ ): Promise<SubagentAgentExecutionEnvironment> {
270
443
  // A child's workspace is blank, so it has no source credentials to lose.
271
444
  const { sandbox, resumed = false } = await input.openSandbox({
272
445
  signal: input.signal ?? NEVER_ABORTED_SIGNAL,
273
446
  onFailure: () => {},
274
447
  })
448
+ // A workspace the prompt describes is acquired once: by the summary that continues the child's
449
+ // prompt when it compacts, else when the environment starts.
450
+ let acquisition: Promise<AcquiredRunSandbox> | undefined
451
+ let provisioning = false
452
+ const acquire = () => {
453
+ acquisition ??= sandbox.acquire()
454
+ return acquisition
455
+ }
275
456
 
276
457
  try {
277
- return await startSubagentEnvironment({ ...input, sandbox, resumed })
458
+ return await startSubagentEnvironment({
459
+ ...input,
460
+ sandbox,
461
+ resumed,
462
+ acquireBeforeStart: acquire,
463
+ acquire: () => {
464
+ provisioning = true
465
+ return acquire()
466
+ },
467
+ })
278
468
  } catch (error) {
279
469
  // Preparation failed before the worker got this environment: the child ends here, so its
280
470
  // workspace goes, as the worker's failure path would destroy it. A lost execution must touch
281
471
  // nothing.
282
- if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.({ discard: true })
472
+ try {
473
+ if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.({ discard: true })
474
+ } finally {
475
+ // A workspace the summary acquired goes back as the environment would have given it.
476
+ if (acquisition && !provisioning) await releaseAcquisition(sandbox, acquisition)
477
+ }
283
478
  throw error
284
479
  }
285
480
  }
@@ -289,13 +484,18 @@ async function startSubagentEnvironment(
289
484
  readonly sandbox: RunSandbox
290
485
  /** Whether the sandbox is the workspace the paused run left: it holds its files already. */
291
486
  readonly resumed: boolean
487
+ /** How the summary acquires the workspace its prompt describes, before the environment. */
488
+ readonly acquireBeforeStart: () => Promise<AcquiredRunSandbox>
489
+ /** How provisioning acquires it, which from then gives it back. */
490
+ readonly acquire: () => Promise<AcquiredRunSandbox>
292
491
  }
293
- ): Promise<AgentExecutionEnvironment> {
294
- const { context, plan, run, conversation, sandbox, resumed } = input
492
+ ): Promise<SubagentAgentExecutionEnvironment> {
493
+ const { context, plan, run, conversation, sandbox, resumed, preflight } = input
494
+ const signal = input.signal ?? NEVER_ABORTED_SIGNAL
295
495
  // Still listed, as handed over, but never copied over what the child made of them.
296
496
  const files = resumed ? (run.spec.files ?? []) : subagentSandboxFiles(run, input.history.paused)
297
- const history = input.history.messages
298
- const [memory, handedContext, historyContext] = await Promise.all([
497
+ const inlineImages = modelSupportsInlineImages(plan.model)
498
+ const [memory, handedContext] = await Promise.all([
299
499
  // As of the thread's start, as a conversation's: each run of the child reads the same memory.
300
500
  loadConversationMemory({ session: input.session, asOf: input.thread.createdAt }),
301
501
  files.length
@@ -309,27 +509,136 @@ async function startSubagentEnvironment(
309
509
  signal: input.signal,
310
510
  })
311
511
  : emptyAttachmentContext(context.id),
312
- history.length && context.apiBaseUrl
313
- ? prepareAgentAttachments({
314
- projectId: context.id,
315
- // Its messages are its thread's, so their files are read there.
316
- threadId: input.thread.id,
317
- messages: history,
318
- blobStorage: context.blobStorage,
319
- apiBaseUrl: context.apiBaseUrl,
320
- contextDirectory: sandbox.contextDirectory,
321
- inlineImages: modelSupportsInlineImages(plan.model),
322
- signal: input.signal,
323
- })
324
- : undefined,
325
512
  ])
326
- const attachmentContext = historyContext
327
- ? mergeAttachmentContexts(handedContext, historyContext)
328
- : handedContext
513
+ const publishing = conversation
514
+ ? {
515
+ artifacts: input.session.artifacts,
516
+ threadId: conversation.id,
517
+ owner: conversation.ownerPrincipal,
518
+ }
519
+ : undefined
329
520
 
330
- return startAgentEnvironment({
521
+ // What a history's files make of the request: the handed files, its attachments and the images
522
+ // its tools showed, within one request's inline image budget, the history first.
523
+ const prepareFiles = async (messages: readonly AgentMessageRecord[]) => {
524
+ const historyContext =
525
+ messages.length && context.apiBaseUrl
526
+ ? await prepareAgentAttachments({
527
+ projectId: context.id,
528
+ // Its messages are its thread's, so their files are read there.
529
+ threadId: input.thread.id,
530
+ messages,
531
+ blobStorage: context.blobStorage,
532
+ apiBaseUrl: context.apiBaseUrl,
533
+ contextDirectory: sandbox.contextDirectory,
534
+ inlineImages,
535
+ signal: input.signal,
536
+ })
537
+ : undefined
538
+
539
+ const imageBudget = new InlineImageBudget()
540
+ const attachmentContext = await allocateInlineImages({
541
+ messages,
542
+ attachments: historyContext
543
+ ? mergeAttachmentContexts(handedContext, historyContext)
544
+ : handedContext,
545
+ toolFiles: replayToolFiles({
546
+ messages,
547
+ suppliesToolFiles: suppliesToolFiles(plan),
548
+ supportsImages: inlineImages,
549
+ }),
550
+ budget: imageBudget,
551
+ blobStorage: context.blobStorage,
552
+ signal,
553
+ })
554
+ return { attachmentContext, imageBudget }
555
+ }
556
+
557
+ // The request the child's calls would send for a history, built as the environment and
558
+ // runSubagent build it: the summary continues it, so the provider reads it from its cache.
559
+ const createdAt = renderCurrentTime(
560
+ input.thread.createdAt,
561
+ sentSettings(plan, { timeZone: context.timeZone, locale: context.locale })
562
+ )
563
+ const initial = subagentThreadContext(input.history)
564
+ const task = initial.task
565
+ const threadOf = (threadContext: LoadedAgentThreadModelContext): SubagentThreadContext => ({
566
+ ...(task ? { task } : {}),
567
+ threadContext,
568
+ })
569
+ const tools = [
570
+ ...agentModelToolSpecs(plan.tools, { publishes: publishing !== undefined }),
571
+ ...(input.frameworkTools ?? []),
572
+ ]
573
+ const childRequest: BuildConversationRequest = async ({ threadContext }) => {
574
+ const { attachmentContext } = await prepareFiles(threadContext.retainedMessages)
575
+ const workspace = sandbox.waitBeforeModel
576
+ ? await waitForAbort(input.acquireBeforeStart(), input.signal)
577
+ : undefined
578
+
579
+ return {
580
+ systemPrompt: renderEnvironmentSystemPrompt({
581
+ mode: "subagent",
582
+ sandbox,
583
+ context,
584
+ plan,
585
+ ontologyDocs: plan.ontologyDocs,
586
+ ...(workspace ? { workspace } : {}),
587
+ ...(memory ? { memory } : {}),
588
+ }),
589
+ tools,
590
+ messages: subagentModelMessages({
591
+ thread: threadOf(threadContext),
592
+ attachmentContext,
593
+ createdAt,
594
+ }),
595
+ }
596
+ }
597
+
598
+ // What the child's estimates count besides the thread: its prompt, its tools, and the task
599
+ // every request opens with.
600
+ const estimateShape = {
601
+ systemPrompt: renderEnvironmentSystemPrompt({
602
+ mode: "subagent",
603
+ sandbox,
604
+ context,
605
+ plan,
606
+ ontologyDocs: plan.ontologyDocs,
607
+ ...(memory ? { memory } : {}),
608
+ }),
609
+ tools: contextEstimateTools(tools),
610
+ ...(task ? { head: [task] } : {}),
611
+ }
612
+ // What the child's compaction reads and writes through, before the run or during it.
613
+ const compaction: AgentThreadCompactionInput | undefined = preflight && {
614
+ context,
615
+ session: input.session,
616
+ plan,
617
+ budget: preflight.budget,
618
+ run,
619
+ runtime: preflight.runtime,
620
+ // No `loadMemory`: a child's prompt shows memory as of its thread's start, whatever it
621
+ // compacted, so its summary and its calls send the same prompt.
622
+ conversationRequest: childRequest,
623
+ estimateShape: () => estimateShape,
624
+ caching: subagentPromptCaching({
625
+ projectId: context.id,
626
+ thread: input.thread,
627
+ run,
628
+ history: input.history,
629
+ }),
630
+ }
631
+ // Compacted before its files are read: the inline image budget goes to what the run sends.
632
+ const prepared = compaction
633
+ ? await preflightSubagentContext({ ...compaction, threadContext: initial.threadContext })
634
+ : undefined
635
+ const threadContext = prepared?.threadContext ?? initial.threadContext
636
+ const { attachmentContext, imageBudget } = await prepareFiles(threadContext.retainedMessages)
637
+
638
+ const environment = await startAgentEnvironment({
331
639
  mode: "subagent",
332
640
  sandbox,
641
+ acquire: input.acquire,
333
642
  sandboxSignal: input.signal,
334
643
  context,
335
644
  plan,
@@ -337,23 +646,39 @@ async function startSubagentEnvironment(
337
646
  parentRunId: run.parentRunId,
338
647
  threadId: conversationThreadId(input.thread),
339
648
  callTool: (call, options) => input.session.callTool(call, options),
340
- ...(conversation
341
- ? {
342
- publishing: {
343
- artifacts: input.session.artifacts,
344
- threadId: conversation.id,
345
- owner: conversation.ownerPrincipal,
346
- },
347
- }
348
- : {}),
649
+ ...(publishing ? { publishing } : {}),
349
650
  apiBaseUrl: context.apiBaseUrl,
350
651
  attachmentContext,
652
+ toolOutputs: savedToolOutputFiles(threadContext.retainedMessages),
653
+ imageBudget,
351
654
  ontologyDocs: plan.ontologyDocs,
352
655
  ...(memory ? { memory } : {}),
353
656
  frameworkTools: input.frameworkTools,
354
657
  errorDetails: { parentRunId: run.parentRunId, runId: run.id },
355
658
  onDetachedTeardown: input.onDetachedTeardown,
356
659
  })
660
+
661
+ // The run compacts from within at most once: a run writes one checkpoint.
662
+ const compactInRun: SubagentAgentExecutionEnvironment["compactInRun"] =
663
+ compaction &&
664
+ (async ({ reason }) => {
665
+ const compacted = await compactAgentThreadInRun({
666
+ ...compaction,
667
+ threadContext,
668
+ memory: undefined,
669
+ reason,
670
+ coldCache: false,
671
+ })
672
+ return (
673
+ compacted && childRequest({ threadContext: compacted.threadContext, memory: undefined })
674
+ )
675
+ })
676
+ return {
677
+ ...environment,
678
+ thread: threadOf(threadContext),
679
+ ...(compactInRun ? { compactInRun } : {}),
680
+ ...(prepared ? { bytesPerToken: prepared.bytesPerToken } : {}),
681
+ }
357
682
  }
358
683
 
359
684
  /** Build the same tool/sandbox environment for a fresh, headless workflow task. */
@@ -398,6 +723,8 @@ export async function createWorkflowAgentNodeEnvironment(
398
723
  callTool: input.callTool,
399
724
  apiBaseUrl: context.apiBaseUrl,
400
725
  attachmentContext,
726
+ // A step's inputs are files, never inline images: its own steps have the whole budget.
727
+ imageBudget: new InlineImageBudget(),
401
728
  ontologyDocs: plan.ontologyDocs,
402
729
  errorDetails: input.errorDetails,
403
730
  onDetachedTeardown: input.onDetachedTeardown,
@@ -414,6 +741,8 @@ export async function createWorkflowAgentNodeEnvironment(
414
741
  interface AgentEnvironmentSetup
415
742
  extends Omit<CreateAgentEnvironmentInput, "signal" | "openSandbox"> {
416
743
  readonly sandbox: RunSandbox
744
+ /** How provisioning acquires the sandbox, when the run may have acquired it already. */
745
+ readonly acquire?: () => Promise<AcquiredRunSandbox>
417
746
  /**
418
747
  * Run end or environment failure: stops waiting for a sandbox the first model call needs, and
419
748
  * stops reading the artifacts it installs.
@@ -430,6 +759,13 @@ interface AgentEnvironmentSetup
430
759
  readonly threadId?: string
431
760
  readonly apiBaseUrl: string
432
761
  readonly attachmentContext: PreparedAgentAttachmentContext
762
+ /**
763
+ * The outputs the history saved to files, which provisioning writes back where their previews
764
+ * name them: read from the store while the model starts, unless the sandbox holds them.
765
+ */
766
+ readonly toolOutputs?: readonly AgentToolCallFile[]
767
+ /** What the history left of the request's inline image budget, which the run's steps take. */
768
+ readonly imageBudget: InlineImageBudget
433
769
  /** Installed under `$SIXB_ONTOLOGY_DIR`; a workflow step's prompt does not list them. */
434
770
  readonly ontologyDocs?: RenderedOntologyDocs
435
771
  readonly errorDetails?: AgentErrorDetails
@@ -446,6 +782,10 @@ interface AgentEnvironmentSetup
446
782
  }
447
783
  /** A conversation's memory, or a child's to read: installed in the sandbox and in the prompt. */
448
784
  readonly memory?: ConversationMemory
785
+ /** When the conversation's turns last moved to where they run now: see its `movedAt`. */
786
+ readonly workspaceMovedAt?: string
787
+ /** Who takes part in a conversation several people write in, for its prompt. */
788
+ readonly conversation?: string
449
789
  }
450
790
 
451
791
  /**
@@ -465,7 +805,14 @@ async function startAgentEnvironment(
465
805
  const fileBudget = new AgentFileBudget()
466
806
  const mediaBridge = new AgentToolResultMediaBridge({
467
807
  blobStorage: context.blobStorage,
468
- sandboxPathForFileRef: (fileRef) => fileRegistry.pathFor(fileRef),
808
+ suppliesToolFiles: suppliesToolFiles(plan),
809
+ inlineImages: input.imageBudget,
810
+ // As the agent names it, so the output a later turn replays names the path that turn
811
+ // materializes the file at, in its own sandbox.
812
+ sandboxPathForFileRef: async (fileRef) => {
813
+ const path = fileRegistry.pathFor(fileRef)
814
+ return path === undefined ? undefined : agentSandboxPath(await ready, path)
815
+ },
469
816
  })
470
817
  const filesForToolCall = (input: {
471
818
  readonly toolName: string
@@ -484,6 +831,7 @@ async function startAgentEnvironment(
484
831
  specs: plan.tools,
485
832
  runId,
486
833
  callTool: input.callTool,
834
+ contextDirectory: sandbox.contextDirectory,
487
835
  fileBytesLeft: () => fileBudget.maxBytes - fileBudget.reservedBytes,
488
836
  installFiles: ({ toolName, files, signal }) =>
489
837
  installAgentToolFiles({
@@ -512,6 +860,11 @@ async function startAgentEnvironment(
512
860
  })
513
861
  )
514
862
  const resolveSandbox = () => ready
863
+ // Its own budget: saving outputs never takes what published artifacts and tool files need.
864
+ const toolOutputFiles = new ToolOutputFiles({
865
+ sandbox: resolveSandbox,
866
+ blobStorage: context.blobStorage,
867
+ })
515
868
  appendBuiltInTool(tools, createReadTool(resolveSandbox))
516
869
  appendBuiltInTool(tools, createBashTool(resolveSandbox))
517
870
  let installedArtifacts: Promise<InstalledArtifacts> | undefined
@@ -544,11 +897,14 @@ async function startAgentEnvironment(
544
897
 
545
898
  ready = provisionSandbox({
546
899
  sandbox,
900
+ ...(input.acquire ? { acquire: input.acquire } : {}),
547
901
  context,
548
902
  actorId,
549
903
  run: { id: runId, ...(threadId ? { threadId } : {}) },
550
904
  apiBaseUrl,
551
905
  attachmentContext,
906
+ ...(input.toolOutputs ? { toolOutputs: input.toolOutputs } : {}),
907
+ ...(input.sandboxSignal ? { signal: input.sandboxSignal } : {}),
552
908
  // A conversation's memory section names the memory skill; other runs never see it.
553
909
  skills: input.memory && mode === "conversation" ? [...plan.skills, MEMORY_SKILL] : plan.skills,
554
910
  ontologyFiles: input.ontologyDocs?.files ?? [],
@@ -567,30 +923,22 @@ async function startAgentEnvironment(
567
923
 
568
924
  const dispose = () => disposeEnvironment(ready, () => settled, sandbox, input.onDetachedTeardown)
569
925
 
570
- let systemPrompt: string
926
+ let systemPrompt: AgentSystemPromptSize
571
927
  try {
572
928
  const workspace = sandbox.waitBeforeModel
573
929
  ? await waitForAbort(ready, input.sandboxSignal)
574
930
  : undefined
575
931
 
576
- systemPrompt = renderAgentSystemPrompt({
932
+ systemPrompt = measureEnvironmentSystemPrompt({
577
933
  mode,
578
- contextDirectory: sandbox.contextDirectory,
579
- instructions: plan.instructions,
580
- skills: plan.skills,
581
- // Workflow prompts are kept lean: their steps get the files without the index.
582
- ...(mode !== "workflow-task" && input.ontologyDocs
583
- ? { ontologyIndex: input.ontologyDocs.index }
584
- : {}),
585
- sandboxResetAt: workspace?.resetAt,
586
- workspace: workspace?.promptContext,
587
- facts: agentRuntimeFacts({
588
- settings: plan,
589
- project: context,
590
- requester: context.requester,
591
- }),
592
- ...(plan.sandboxModels ? { sandboxModels: plan.sandboxModels } : {}),
593
- ...(input.memory ? { memory: input.memory.prompt } : {}),
934
+ sandbox,
935
+ context,
936
+ plan,
937
+ ...(input.ontologyDocs ? { ontologyDocs: input.ontologyDocs } : {}),
938
+ ...(workspace ? { workspace } : {}),
939
+ ...(input.workspaceMovedAt ? { workspaceMovedAt: input.workspaceMovedAt } : {}),
940
+ ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
941
+ ...(input.memory ? { memory: input.memory } : {}),
594
942
  })
595
943
  } catch (error) {
596
944
  // Provisioning has started: give back what it acquires, or the sandbox outlives the run.
@@ -634,16 +982,94 @@ async function startAgentEnvironment(
634
982
  blobStorage: context.blobStorage,
635
983
  apiBaseUrl,
636
984
  attachmentContext,
637
- tools,
985
+ tools: toolOutputFiles.wrap(tools),
986
+ outputFileOf: (toolCallId) => toolOutputFiles.fileOf(toolCallId),
638
987
  prepareStep: mediaBridge.prepareStep,
639
- systemPrompt,
988
+ systemPrompt: systemPrompt.text,
989
+ systemPromptSize: systemPrompt,
990
+ contextDirectory: sandbox.contextDirectory,
640
991
  projectTimeZone: context.timeZone,
992
+ projectLocale: context.locale,
641
993
  sandboxReady: ready,
642
994
  },
643
995
  dispose,
644
996
  }
645
997
  }
646
998
 
999
+ /**
1000
+ * A run's system prompt, from its plan and what its sandbox tells it: the environment renders it,
1001
+ * and so does the summary that continues a conversation's prompt.
1002
+ */
1003
+ function renderEnvironmentSystemPrompt(
1004
+ input: Parameters<typeof measureEnvironmentSystemPrompt>[0]
1005
+ ): string {
1006
+ return measureEnvironmentSystemPrompt(input).text
1007
+ }
1008
+
1009
+ /** The same, with each section's bytes, for the turn's steps to record what they sent. */
1010
+ function measureEnvironmentSystemPrompt(input: {
1011
+ readonly mode: AgentExecutionMode
1012
+ readonly sandbox: RunSandbox
1013
+ readonly context: AgentExecutionContext
1014
+ readonly plan: ResolvedAgentExecutionPlan
1015
+ readonly ontologyDocs?: RenderedOntologyDocs
1016
+ /** The acquired workspace, when the prompt describes it. */
1017
+ readonly workspace?: Pick<AcquiredRunSandbox, "promptContext" | "resetAt">
1018
+ readonly workspaceMovedAt?: string
1019
+ readonly conversation?: string
1020
+ readonly memory?: ConversationMemory
1021
+ }): AgentSystemPromptSize {
1022
+ const { mode, plan, workspace } = input
1023
+ const { requester } = input.context
1024
+
1025
+ return measureAgentSystemPrompt({
1026
+ mode,
1027
+ contextDirectory: input.sandbox.contextDirectory,
1028
+ instructions: plan.instructions,
1029
+ skills: plan.skills,
1030
+ // Workflow prompts are kept lean: their steps get the files without the index.
1031
+ ...(mode !== "workflow-task" && input.ontologyDocs
1032
+ ? { ontologyIndex: input.ontologyDocs.index }
1033
+ : {}),
1034
+ sandboxResetAt: workspace?.resetAt,
1035
+ ...(input.workspaceMovedAt ? { workspaceMovedAt: input.workspaceMovedAt } : {}),
1036
+ workspace: workspace?.promptContext,
1037
+ facts: requester === undefined ? {} : { requester },
1038
+ ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
1039
+ ...(plan.sandboxModels ? { sandboxModels: plan.sandboxModels } : {}),
1040
+ ...(input.memory ? { memory: input.memory.prompt } : {}),
1041
+ })
1042
+ }
1043
+
1044
+ /** Give back a sandbox acquired for a run whose environment never started. */
1045
+ async function releaseAcquisition(
1046
+ sandbox: RunSandbox,
1047
+ acquisition: Promise<AcquiredRunSandbox>
1048
+ ): Promise<void> {
1049
+ // A failed acquisition gave back what it held.
1050
+ const acquired = await acquisition.catch(() => undefined)
1051
+ if (!acquired || !sandbox.release) return
1052
+
1053
+ await sandbox.release(acquired).catch((error) => {
1054
+ console.error("[SixbAgent] Could not release agent run sandbox:", error)
1055
+ })
1056
+ }
1057
+
1058
+ /** An absolute sandbox path relative to the working directory when it is inside it. */
1059
+ function agentSandboxPath(handle: AgentSandboxHandle, path: string): string {
1060
+ const relative = posix.relative(handle.sandbox.workingDirectory, path)
1061
+ return relative && !relative.startsWith("../") && !posix.isAbsolute(relative) ? relative : path
1062
+ }
1063
+
1064
+ /**
1065
+ * The tools whose images reach the model after their step: the project's and `view_file`, whose
1066
+ * outputs go through the run's media bridge. A replay asks the same of the stored trace.
1067
+ */
1068
+ function suppliesToolFiles(plan: Pick<ResolvedAgentExecutionPlan, "tools">): SuppliesToolFiles {
1069
+ const names = new Set([...plan.tools.map((tool) => tool.name), VIEW_FILE_TOOL_SPEC.name])
1070
+ return (toolName) => names.has(toolName)
1071
+ }
1072
+
647
1073
  /** The handed files' context, with what a continuation's history showed its tools. */
648
1074
  function mergeAttachmentContexts(
649
1075
  handed: PreparedAgentAttachmentContext,
@@ -659,6 +1085,7 @@ function mergeAttachmentContexts(
659
1085
  ...history.modelFileDataByPartKey,
660
1086
  ]),
661
1087
  sandboxFiles: [...handed.sandboxFiles, ...history.sandboxFiles],
1088
+ ...(history.pendingImages === undefined ? {} : { pendingImages: history.pendingImages }),
662
1089
  manifestJson: JSON.stringify(
663
1090
  {
664
1091
  ...handedManifest,
@@ -685,11 +1112,15 @@ function emptyAttachmentContext(projectId: string): PreparedAgentAttachmentConte
685
1112
 
686
1113
  interface ProvisionSandboxInput {
687
1114
  readonly sandbox: RunSandbox
1115
+ readonly acquire?: () => Promise<AcquiredRunSandbox>
688
1116
  readonly context: AgentExecutionContext
689
1117
  readonly actorId?: string
690
1118
  readonly run: { readonly id: string; readonly threadId?: string }
691
1119
  readonly apiBaseUrl: string
692
1120
  readonly attachmentContext: PreparedAgentAttachmentContext
1121
+ readonly toolOutputs?: readonly AgentToolCallFile[]
1122
+ /** Stops reading the saved outputs it writes back. */
1123
+ readonly signal?: AbortSignal
693
1124
  readonly skills: ResolvedAgentExecutionPlan["skills"]
694
1125
  readonly ontologyFiles: RenderedOntologyDocs["files"]
695
1126
  /** The conversation's artifacts, read while the sandbox starts. */
@@ -702,7 +1133,7 @@ type ProvisionedRunSandbox = AcquiredRunSandbox & AgentSandboxHandle
702
1133
 
703
1134
  async function provisionSandbox(input: ProvisionSandboxInput): Promise<ProvisionedRunSandbox> {
704
1135
  const { context, actorId, run, apiBaseUrl, skills, ontologyFiles } = input
705
- const acquired = await input.sandbox.acquire()
1136
+ const acquired = await (input.acquire?.() ?? input.sandbox.acquire())
706
1137
  const { sandbox } = acquired
707
1138
  const { contextDirectory } = input.sandbox
708
1139
  try {
@@ -725,7 +1156,23 @@ async function provisionSandbox(input: ProvisionSandboxInput): Promise<Provision
725
1156
  env: apiContext.env,
726
1157
  projectId: context.id,
727
1158
  })
728
- return { ...acquired, contextDirectory, env: { ...acquired.env, ...apiContext.env } }
1159
+ const provisioned = {
1160
+ ...acquired,
1161
+ contextDirectory,
1162
+ env: { ...acquired.env, ...apiContext.env },
1163
+ }
1164
+
1165
+ // Best effort: an output not written back is still in its message, cut, and in the store.
1166
+ await restoreSavedToolOutputs({
1167
+ handle: provisioned,
1168
+ files: input.toolOutputs ?? [],
1169
+ blobStorage: context.blobStorage,
1170
+ signal: input.signal ?? NEVER_ABORTED_SIGNAL,
1171
+ }).catch((error: unknown) => {
1172
+ input.signal?.throwIfAborted()
1173
+ console.warn("[SixbAgent] Could not write the saved tool outputs back:", error)
1174
+ })
1175
+ return provisioned
729
1176
  } catch (error) {
730
1177
  // Give back a half-provisioned sandbox before propagating to the awaiter.
731
1178
  await input.sandbox.release?.(acquired).catch(() => {})