@sixb/agent 0.0.0-stage → 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 (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/abort.d.ts +6 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/agent-prompt.d.ts +126 -0
  6. package/dist/agent-prompt.d.ts.map +1 -0
  7. package/dist/agent-runtime/errors.d.ts +13 -0
  8. package/dist/agent-runtime/errors.d.ts.map +1 -0
  9. package/dist/agent-runtime/preflight.d.ts +18 -0
  10. package/dist/agent-runtime/preflight.d.ts.map +1 -0
  11. package/dist/agent-runtime/profile.d.ts +14 -0
  12. package/dist/agent-runtime/profile.d.ts.map +1 -0
  13. package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
  14. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
  15. package/dist/artifacts/materialize.d.ts +115 -0
  16. package/dist/artifacts/materialize.d.ts.map +1 -0
  17. package/dist/artifacts/publish-tool.d.ts +86 -0
  18. package/dist/artifacts/publish-tool.d.ts.map +1 -0
  19. package/dist/ask-parent-tool.d.ts +36 -0
  20. package/dist/ask-parent-tool.d.ts.map +1 -0
  21. package/dist/attachments.d.ts +109 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +91 -0
  24. package/dist/child-files.d.ts.map +1 -0
  25. package/dist/child-questions.d.ts +24 -0
  26. package/dist/child-questions.d.ts.map +1 -0
  27. package/dist/computer-runner.d.ts +74 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +34 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +148 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/context-guard.d.ts +69 -0
  34. package/dist/context-guard.d.ts.map +1 -0
  35. package/dist/conversation-memory.d.ts +21 -0
  36. package/dist/conversation-memory.d.ts.map +1 -0
  37. package/dist/conversation-messages.d.ts +33 -0
  38. package/dist/conversation-messages.d.ts.map +1 -0
  39. package/dist/errors.d.ts +46 -0
  40. package/dist/errors.d.ts.map +1 -0
  41. package/dist/execution-plan.d.ts +38 -0
  42. package/dist/execution-plan.d.ts.map +1 -0
  43. package/dist/failure.d.ts +14 -0
  44. package/dist/failure.d.ts.map +1 -0
  45. package/dist/family-mailbox.d.ts +60 -0
  46. package/dist/family-mailbox.d.ts.map +1 -0
  47. package/dist/file-ref.d.ts +6 -0
  48. package/dist/file-ref.d.ts.map +1 -0
  49. package/dist/image-attachments.d.ts +34 -0
  50. package/dist/image-attachments.d.ts.map +1 -0
  51. package/dist/index.d.ts +35 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +14387 -0
  54. package/dist/index.js.map +72 -0
  55. package/dist/inline-images.d.ts +28 -0
  56. package/dist/inline-images.d.ts.map +1 -0
  57. package/dist/message-authors.d.ts +34 -0
  58. package/dist/message-authors.d.ts.map +1 -0
  59. package/dist/message-times.d.ts +9 -0
  60. package/dist/message-times.d.ts.map +1 -0
  61. package/dist/model-adapters.d.ts +59 -0
  62. package/dist/model-adapters.d.ts.map +1 -0
  63. package/dist/model-lines.d.ts +16 -0
  64. package/dist/model-lines.d.ts.map +1 -0
  65. package/dist/prompt-cache.d.ts +28 -0
  66. package/dist/prompt-cache.d.ts.map +1 -0
  67. package/dist/requester.d.ts +15 -0
  68. package/dist/requester.d.ts.map +1 -0
  69. package/dist/run-agent-turn.d.ts +93 -0
  70. package/dist/run-agent-turn.d.ts.map +1 -0
  71. package/dist/run-child.d.ts +77 -0
  72. package/dist/run-child.d.ts.map +1 -0
  73. package/dist/run-conversation-turn.d.ts +42 -0
  74. package/dist/run-conversation-turn.d.ts.map +1 -0
  75. package/dist/run-credential.d.ts +22 -0
  76. package/dist/run-credential.d.ts.map +1 -0
  77. package/dist/run-environment.d.ts +145 -0
  78. package/dist/run-environment.d.ts.map +1 -0
  79. package/dist/run-fate.d.ts +15 -0
  80. package/dist/run-fate.d.ts.map +1 -0
  81. package/dist/run-files-lock.d.ts +16 -0
  82. package/dist/run-files-lock.d.ts.map +1 -0
  83. package/dist/run-sandbox.d.ts +60 -0
  84. package/dist/run-sandbox.d.ts.map +1 -0
  85. package/dist/run-subagent.d.ts +65 -0
  86. package/dist/run-subagent.d.ts.map +1 -0
  87. package/dist/run-workflow-agent-node.d.ts +46 -0
  88. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  89. package/dist/sandbox-api-context.d.ts +34 -0
  90. package/dist/sandbox-api-context.d.ts.map +1 -0
  91. package/dist/sandbox-file-registry.d.ts +9 -0
  92. package/dist/sandbox-file-registry.d.ts.map +1 -0
  93. package/dist/sandbox-files.d.ts +71 -0
  94. package/dist/sandbox-files.d.ts.map +1 -0
  95. package/dist/sandbox-handle.d.ts +15 -0
  96. package/dist/sandbox-handle.d.ts.map +1 -0
  97. package/dist/sandbox-readiness.d.ts +8 -0
  98. package/dist/sandbox-readiness.d.ts.map +1 -0
  99. package/dist/skills/built-in.d.ts +15 -0
  100. package/dist/skills/built-in.d.ts.map +1 -0
  101. package/dist/subagent-context.d.ts +50 -0
  102. package/dist/subagent-context.d.ts.map +1 -0
  103. package/dist/subagent-continuation.d.ts +33 -0
  104. package/dist/subagent-continuation.d.ts.map +1 -0
  105. package/dist/subagent-inbox.d.ts +53 -0
  106. package/dist/subagent-inbox.d.ts.map +1 -0
  107. package/dist/subagent-tools.d.ts +293 -0
  108. package/dist/subagent-tools.d.ts.map +1 -0
  109. package/dist/thread-context.d.ts +17 -0
  110. package/dist/thread-context.d.ts.map +1 -0
  111. package/dist/tools/attachments.d.ts +11 -0
  112. package/dist/tools/attachments.d.ts.map +1 -0
  113. package/dist/tools/bash.d.ts +68 -0
  114. package/dist/tools/bash.d.ts.map +1 -0
  115. package/dist/tools/model-spec.d.ts +9 -0
  116. package/dist/tools/model-spec.d.ts.map +1 -0
  117. package/dist/tools/read.d.ts +43 -0
  118. package/dist/tools/read.d.ts.map +1 -0
  119. package/dist/tools/result-media.d.ts +65 -0
  120. package/dist/tools/result-media.d.ts.map +1 -0
  121. package/dist/tools/result-output.d.ts +18 -0
  122. package/dist/tools/result-output.d.ts.map +1 -0
  123. package/dist/tools/tool-files.d.ts +59 -0
  124. package/dist/tools/tool-files.d.ts.map +1 -0
  125. package/dist/tools/tool-outputs.d.ts +63 -0
  126. package/dist/tools/tool-outputs.d.ts.map +1 -0
  127. package/dist/tools/view-file.d.ts +40 -0
  128. package/dist/tools/view-file.d.ts.map +1 -0
  129. package/dist/tsconfig.json +5 -0
  130. package/dist/turn-runtime.d.ts +19 -0
  131. package/dist/turn-runtime.d.ts.map +1 -0
  132. package/dist/types.d.ts +83 -0
  133. package/dist/types.d.ts.map +1 -0
  134. package/dist/workflow-input-attachments.d.ts +18 -0
  135. package/dist/workflow-input-attachments.d.ts.map +1 -0
  136. package/package.json +59 -4
  137. package/src/abort.ts +40 -0
  138. package/src/agent-prompt.ts +860 -0
  139. package/src/agent-runtime/errors.ts +44 -0
  140. package/src/agent-runtime/preflight.ts +314 -0
  141. package/src/agent-runtime/profile.ts +23 -0
  142. package/src/artifacts/layout-check/check.cjs +478 -0
  143. package/src/artifacts/layout-check/layout-check.ts +460 -0
  144. package/src/artifacts/materialize.ts +380 -0
  145. package/src/artifacts/publish-tool.ts +700 -0
  146. package/src/ask-parent-tool.ts +100 -0
  147. package/src/attachments.ts +1041 -0
  148. package/src/child-files.ts +535 -0
  149. package/src/child-questions.ts +42 -0
  150. package/src/computer-runner.ts +336 -0
  151. package/src/context-budget.ts +177 -0
  152. package/src/context-compaction.ts +1349 -0
  153. package/src/context-guard.ts +826 -0
  154. package/src/conversation-memory.ts +45 -0
  155. package/src/conversation-messages.ts +86 -0
  156. package/src/errors.ts +85 -0
  157. package/src/execution-plan.ts +70 -0
  158. package/src/failure.ts +82 -0
  159. package/src/family-mailbox.ts +189 -0
  160. package/src/file-ref.ts +18 -0
  161. package/src/image-attachments.ts +322 -0
  162. package/src/index.ts +54 -0
  163. package/src/inline-images.ts +69 -0
  164. package/src/message-authors.ts +77 -0
  165. package/src/message-times.ts +24 -0
  166. package/src/model-adapters.ts +273 -0
  167. package/src/model-lines.ts +28 -0
  168. package/src/prompt-cache.ts +40 -0
  169. package/src/requester.ts +21 -0
  170. package/src/run-agent-turn.ts +509 -0
  171. package/src/run-child.ts +344 -0
  172. package/src/run-conversation-turn.ts +272 -0
  173. package/src/run-credential.ts +55 -0
  174. package/src/run-environment.ts +1216 -0
  175. package/src/run-fate.ts +51 -0
  176. package/src/run-files-lock.ts +118 -0
  177. package/src/run-sandbox.ts +63 -0
  178. package/src/run-subagent.ts +433 -0
  179. package/src/run-workflow-agent-node.ts +344 -0
  180. package/src/sandbox-api-context.ts +237 -0
  181. package/src/sandbox-file-registry.ts +26 -0
  182. package/src/sandbox-files.ts +326 -0
  183. package/src/sandbox-handle.ts +19 -0
  184. package/src/sandbox-readiness.ts +22 -0
  185. package/src/skills/built-in.ts +183 -0
  186. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  187. package/src/skills/sixb-artifacts/canvas.md +104 -0
  188. package/src/skills/sixb-artifacts/document.md +63 -0
  189. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  190. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  191. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  192. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  193. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  194. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  195. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  196. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  197. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  198. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  199. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  200. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  201. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  202. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  203. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  204. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  205. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  206. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  207. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  208. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  209. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  210. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  211. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  212. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  213. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  214. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  215. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  216. package/src/skills/sixb-artifacts/file.md +17 -0
  217. package/src/skills/sixb-artifacts/page.md +215 -0
  218. package/src/skills/sixb-artifacts/queries.md +66 -0
  219. package/src/skills/sixb-artifacts/references.md +68 -0
  220. package/src/skills/sixb-artifacts/sheet.md +223 -0
  221. package/src/skills/sixb-artifacts/slides.md +137 -0
  222. package/src/skills/sixb-memory/SKILL.md +68 -0
  223. package/src/skills/text-assets.d.ts +25 -0
  224. package/src/subagent-context.ts +182 -0
  225. package/src/subagent-continuation.ts +56 -0
  226. package/src/subagent-inbox.ts +101 -0
  227. package/src/subagent-tools.ts +1671 -0
  228. package/src/thread-context.ts +31 -0
  229. package/src/tools/attachments.ts +28 -0
  230. package/src/tools/bash.ts +233 -0
  231. package/src/tools/model-spec.ts +27 -0
  232. package/src/tools/read.ts +262 -0
  233. package/src/tools/result-media.ts +351 -0
  234. package/src/tools/result-output.ts +46 -0
  235. package/src/tools/tool-files.ts +204 -0
  236. package/src/tools/tool-outputs.ts +464 -0
  237. package/src/tools/view-file.ts +155 -0
  238. package/src/turn-runtime.ts +33 -0
  239. package/src/types.ts +91 -0
  240. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,1671 @@
1
+ import { isDeepStrictEqual } from "node:util"
2
+ import {
3
+ AGENT_REASONING_LEVELS,
4
+ type AgentApprovalOutcomePart,
5
+ type AgentMailPart,
6
+ type AgentMessage,
7
+ type AgentMessagePart,
8
+ type AgentReasoning,
9
+ AgentToolPublicError,
10
+ type AgentToolResult,
11
+ type LanguageModelRef,
12
+ type LanguageModelTier,
13
+ } from "@sixb/core"
14
+ import {
15
+ type AgentChildApprovalAwaiting,
16
+ type AgentChildDraft,
17
+ AgentExecutionLostError,
18
+ type AgentRunDelegation,
19
+ type AgentRunDelegationModel,
20
+ type AgentRunSession,
21
+ createAgentMessageId,
22
+ createSubagentRunId,
23
+ createSubagentThreadId,
24
+ deferredChildQuestion,
25
+ isAgentToolResult,
26
+ isAwaitingAnswerRun,
27
+ isPausedSubagentRun,
28
+ } from "@sixb/core/internal/agents"
29
+ import { formatLanguageModelTiers, isLanguageModelTier } from "@sixb/core/internal/model-execution"
30
+ import {
31
+ assertJsonValue,
32
+ defineLanguageModel,
33
+ isJsonObject,
34
+ isModelReasoning,
35
+ type JsonObject,
36
+ type ModelTool,
37
+ } from "@sixb/core/models"
38
+ import type {
39
+ ConversationAgentRunRecord,
40
+ SubagentRunFile,
41
+ SubagentRunRecord,
42
+ SubagentRunSpec,
43
+ } from "@sixb/core/storage"
44
+ import { AgentStorageError } from "@sixb/core/storage"
45
+ import { delay } from "./abort"
46
+ import { renderHandedFiles, sentSettings } from "./agent-prompt"
47
+ import { formatBytes, SANDBOX_ATTACHMENT_LIMITS } from "./attachments"
48
+ import {
49
+ handedFileRefs,
50
+ type InstalledChildFile,
51
+ installChildOutputs,
52
+ listHandedSources,
53
+ storeHandedFiles,
54
+ } from "./child-files"
55
+ import { type ChildQuestion, type QuestionRef, renderChildQuestions } from "./child-questions"
56
+ import { ChildMailClosedError, FamilyMailbox } from "./family-mailbox"
57
+ import { agentToolErrorText } from "./model-adapters"
58
+ import { renderModelLine } from "./model-lines"
59
+ import type { TurnChildren } from "./run-agent-turn"
60
+ import { continuationTrigger } from "./subagent-continuation"
61
+ import type { AgentRunFiles, AgentRunSettings } from "./types"
62
+
63
+ /**
64
+ * How long a wait for children goes without reading their runs when nothing woke it. A child's
65
+ * question and its end wake it at once, through the turn's mailbox; this bounds an end recorded
66
+ * outside the runner, which nothing here hears: an API cancel of a child still queued, or a repair
67
+ * pass ending one whose own end could not be recorded. Five seconds keeps such a wait short beside
68
+ * the minutes a child works, and a wait reads storage 12 times a minute.
69
+ */
70
+ export const CHILD_WAIT_RECHECK_MS = 5_000
71
+ /**
72
+ * How often a wait reads a run another turn's mailbox hears, which nothing wakes it for: a child
73
+ * of an earlier turn, or of an earlier attempt of this resume, still stopping. Both are rare and
74
+ * short, so a short poll costs little.
75
+ */
76
+ export const OTHER_TURN_RECHECK_MS = 250
77
+ const OMIT_MODEL = "Omit model to use the project default."
78
+
79
+ /** With tiers, the model guide says how to choose, so only a list adds advice. */
80
+ const TIERED_MODEL_CHOICE = {
81
+ advice: [],
82
+ field: "A tier, or one exact model reference from the models you can delegate to.",
83
+ }
84
+
85
+ const LISTED_MODEL_CHOICE = {
86
+ advice: [
87
+ "Prefer the default model unless another configured model is clearly better suited to the task. Price and runtime speed are not known, so do not infer them from model names.",
88
+ ],
89
+ field: "Copy one exact model reference from the available models.",
90
+ }
91
+
92
+ export interface SpawnSubagentInput {
93
+ readonly key: string
94
+ readonly task: string
95
+ readonly model?: LanguageModelRef | LanguageModelTier
96
+ readonly reasoning?: AgentReasoning
97
+ /** At most this many steps, fewer than the project's limit. */
98
+ readonly maxSteps?: number
99
+ /** Files and directories in the parent's sandbox, copied into the child's at the same paths. */
100
+ readonly files?: readonly string[]
101
+ }
102
+
103
+ export interface SpawnSubagentOutput {
104
+ readonly runId: string
105
+ readonly status: SubagentRunRecord["status"]
106
+ readonly model: LanguageModelRef
107
+ }
108
+
109
+ export interface MessageSubagentInput {
110
+ readonly key: string
111
+ readonly text: string
112
+ }
113
+
114
+ export interface MessageSubagentOutput {
115
+ readonly runId: string
116
+ readonly status: "queued" | "running"
117
+ /**
118
+ * When the child reads it: before its first step while it is queued, else before its next.
119
+ * `answer`: it answers the question the child waits on, now or, once it continues, first.
120
+ */
121
+ readonly delivery: "first-step" | "next-step" | "answer"
122
+ /** The child of an earlier turn, paused on its question, that this answer continues. */
123
+ readonly continues?: string
124
+ }
125
+
126
+ /** A message the parent sent a child this turn. */
127
+ interface SentMessage {
128
+ readonly id: string
129
+ readonly text: string
130
+ }
131
+
132
+ export interface WaitForSubagentsInput {
133
+ readonly runIds: readonly string[]
134
+ }
135
+
136
+ export interface WaitedSubagentResult {
137
+ readonly runId: string
138
+ /**
139
+ * `queued` or `running`: the turn is about to end, so the Agent answers without it.
140
+ * `awaiting_approval`: it paused on calls that wait for the user, and continues once they decide,
141
+ * unless a new message sets the calls aside or the turn is stopped instead.
142
+ */
143
+ readonly status: SubagentRunRecord["status"] | "awaiting_approval" | "awaiting_answer"
144
+ readonly text?: string
145
+ /** The question it waits on: answer it with `message_agent` and its key. */
146
+ readonly question?: QuestionRef
147
+ readonly error?: { readonly code: string; readonly message: string }
148
+ /** The last text a child its step limit stopped wrote: what it found so far, or where it was. */
149
+ readonly partialAnswer?: string
150
+ /** Calls it made that wait for the user's approval. */
151
+ readonly awaitingApproval?: readonly AgentChildApprovalAwaiting[]
152
+ /**
153
+ * What it wrote under `out/`, by path there, and where each is in the parent's sandbox this
154
+ * turn. The first result that lists them holds them as files, which later turns find in
155
+ * `$SIXB_ATTACHMENTS` by their `logicalPath`, `<key>/<path>`.
156
+ */
157
+ readonly files?: readonly {
158
+ readonly path: string
159
+ readonly sandboxPath: string
160
+ readonly sizeBytes: number
161
+ readonly mediaType?: string
162
+ }[]
163
+ /** Why its files are not listed: they did not come back, could not be copied, or wait. */
164
+ readonly filesNote?: string
165
+ /** What this turn sent it that it has not read: a paused child reads it if it continues. */
166
+ readonly unread?: readonly SentMessage[]
167
+ /**
168
+ * What it answered before a message of yours came, which its `text`, written after, replaces.
169
+ * Set when it answered again.
170
+ */
171
+ readonly earlierAnswer?: string
172
+ /** Why its `text` does not account for your last message, when it did not answer again. */
173
+ readonly answerNote?: string
174
+ }
175
+
176
+ type MessagesReport = Pick<WaitedSubagentResult, "unread" | "earlierAnswer" | "answerNote">
177
+
178
+ /** A question a child waits on, with the key to answer it by. */
179
+ export interface WaitedQuestion extends QuestionRef {
180
+ readonly key: string
181
+ readonly runId: string
182
+ }
183
+
184
+ export interface WaitForSubagentsOutput {
185
+ readonly results: readonly WaitedSubagentResult[]
186
+ /** Every question a child of this turn waits on: `wait_agent` returns as soon as one comes. */
187
+ readonly questions?: readonly WaitedQuestion[]
188
+ /** The files no earlier result held, in the order of `results`. */
189
+ readonly files: readonly InstalledChildFile[]
190
+ /** Why what the children published is not all in `$SIXB_ARTIFACTS`. */
191
+ readonly artifactsError?: string
192
+ }
193
+
194
+ /** What a turn offers the children it spawns. */
195
+ export interface TurnDelegation {
196
+ /** The project's language models, from the turn's plan. */
197
+ readonly models: AgentRunDelegation
198
+ /** The project tools each child gets. */
199
+ readonly toolNames: readonly string[]
200
+ }
201
+
202
+ /** Run-scoped boundary used by the parent Agent's framework-owned delegation tools. */
203
+ export class SubagentCoordinator {
204
+ private readonly models: AgentRunDelegation
205
+ #runFiles: AgentRunFiles | undefined
206
+ /** Children whose files are in the parent's sandbox, and in the result that first listed them. */
207
+ readonly #installed = new Map<string, readonly InstalledChildFile[]>()
208
+ /** The spawn being admitted: only this turn adds children to it. */
209
+ #admissions: Promise<unknown> = Promise.resolve()
210
+ /** What this turn sent each child, by its run id, in order. */
211
+ readonly #sent = new Map<string, SentMessage[]>()
212
+ /** What the turn and its children say to each other, in their runner. */
213
+ readonly #family = new FamilyMailbox()
214
+ /** The questions a `wait_agent` returned: one alone no longer stops a wait for other children. */
215
+ readonly #reported = new Set<string>()
216
+ /** What each `message_agent` that answered a question returned, by its mail id, for a replay. */
217
+ readonly #answers = new Map<string, MessageSubagentOutput>()
218
+
219
+ constructor(
220
+ /** What the turn offers its children: the project's language models, and its tools. */
221
+ private readonly delegation: TurnDelegation,
222
+ private readonly context: AgentRunSettings,
223
+ private readonly parentRun: ConversationAgentRunRecord,
224
+ /** The turn's session, through which it reaches its children's runs. */
225
+ private readonly session: AgentRunSession,
226
+ /**
227
+ * Run a child this turn spawned or continues, in the turn's own runner, on the turn's mailbox:
228
+ * it claims the child's run, opens its session and environment, and records its fate.
229
+ * Starting a run already running is a no-op.
230
+ */
231
+ private readonly startChild: (run: SubagentRunRecord, family: FamilyMailbox) => void
232
+ ) {
233
+ this.models = delegation.models
234
+ }
235
+
236
+ /** The turn ended: it sends its children nothing more. */
237
+ close(): void {
238
+ this.#family.close()
239
+ }
240
+
241
+ /**
242
+ * How the turn hears its children's questions: those of earlier turns' children still paused on
243
+ * one, read after the conversation; those it has not read, before its answer ends it; and the
244
+ * pause, before its end, of each child still waiting on one. And how a pausing turn waits for
245
+ * those still at work.
246
+ */
247
+ async turnChildren(): Promise<TurnChildren> {
248
+ let waiting: readonly WaitedQuestion[] = []
249
+ try {
250
+ waiting = await this.waitingQuestions()
251
+ } catch (error) {
252
+ console.error(
253
+ `[SixbAgent] Agent run '${this.parentRun.id}' could not read which earlier sub-agents wait on a question; it goes on without them.`,
254
+ error
255
+ )
256
+ }
257
+ return {
258
+ ...(waiting.length > 0 ? { waiting: renderChildQuestions(waiting, { earlier: true }) } : {}),
259
+ unread: async () => {
260
+ const unread = await this.unreadQuestions()
261
+ return unread.length > 0 ? renderChildQuestions(unread) : undefined
262
+ },
263
+ defer: (signal) => this.deferOpenQuestions(signal),
264
+ settle: (signal) => this.settleChildren(signal),
265
+ }
266
+ }
267
+
268
+ /** The parent's environment, started after its tools are defined and before any of them runs. */
269
+ attach(runFiles: AgentRunFiles): void {
270
+ this.#runFiles = runFiles
271
+ }
272
+
273
+ /**
274
+ * When this turn resumes a paused one, continue each child that paused on its held calls: the
275
+ * next run of its thread, under this turn and the same key, with the paused child's model, task
276
+ * and files, and this turn's mode. The outcomes of its calls start the run. Admitting
277
+ * it again finds it, so a retry of this turn, under its own id, admits its own.
278
+ */
279
+ async continuePausedChildren(signal: AbortSignal): Promise<void> {
280
+ const paused = await this.pausedChildrenToContinue()
281
+ for (const { child, outcomes } of paused) {
282
+ signal.throwIfAborted()
283
+ await this.clearDeadAttempts(child, signal)
284
+ const { spec, continuation } = this.continuationOf(child, outcomes)
285
+ await this.admitInTurn(() =>
286
+ this.admit(
287
+ createSubagentRunId(this.parentRun.id, child.spawnKey),
288
+ child.spawnKey,
289
+ spec,
290
+ signal,
291
+ continuation
292
+ )
293
+ )
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Remove from a paused child's thread what the runs after its pause did under an earlier attempt
299
+ * of this resume, which failed: this turn continues the paused child again, as a retried turn
300
+ * replays from its trigger. A run still stopping is waited for: its lease ends it if nothing else
301
+ * does.
302
+ */
303
+ private async clearDeadAttempts(paused: SubagentRunRecord, signal: AbortSignal): Promise<void> {
304
+ const { children } = this.session
305
+
306
+ for (;;) {
307
+ const runs = await children.threadRuns(paused.threadId)
308
+ const pausedAt = runs.findIndex((run) => run.id === paused.id)
309
+ const dead = (pausedAt < 0 ? [] : runs.slice(pausedAt + 1)).filter(
310
+ (run) => run.parentRunId !== this.parentRun.id
311
+ )
312
+ const stopping = dead.filter((run) => !isTerminalSubagent(run))
313
+ if (stopping.length === 0) {
314
+ for (const run of dead) {
315
+ await children.clearAttempt({ threadId: paused.threadId, runId: run.id })
316
+ }
317
+ return
318
+ }
319
+
320
+ // Its end goes to the mailbox of the attempt it ran under, not this turn's: read it again.
321
+ await delay(OTHER_TURN_RECHECK_MS, signal)
322
+ }
323
+ }
324
+
325
+ /**
326
+ * The children this turn continues: those its trigger, a resume, reported as continuing, as the
327
+ * model reads it. The approvals, not the message, say which calls are the child's and that this
328
+ * message reported them, and the child must still be paused on them.
329
+ */
330
+ private async pausedChildrenToContinue(): Promise<
331
+ readonly {
332
+ readonly child: SubagentRunRecord
333
+ readonly outcomes: readonly AgentApprovalOutcomePart[]
334
+ }[]
335
+ > {
336
+ const { children } = this.session
337
+ const trigger = await this.session.threads.message(this.parentRun.triggerMessageId)
338
+ if (!trigger) return []
339
+
340
+ const parts = trigger.parts.filter(
341
+ (part): part is AgentApprovalOutcomePart => part.type === "approval-outcome"
342
+ )
343
+ const callerIds = [
344
+ ...new Set(parts.flatMap((part) => (part.caller?.continues ? [part.caller.runId] : []))),
345
+ ]
346
+ if (callerIds.length === 0) return []
347
+
348
+ const continuing = []
349
+ for (const child of await children.getMany(callerIds)) {
350
+ if (child.kind !== "subagent" || !isPausedSubagentRun(child)) continue
351
+
352
+ const approvals = await children.approvals(child.parentRunId)
353
+ const reported = new Set(
354
+ approvals
355
+ .filter(
356
+ (approval) =>
357
+ approval.callerRunId === child.id && approval.reportedInMessageId === trigger.id
358
+ )
359
+ .map((approval) => approval.id)
360
+ )
361
+ const outcomes = parts
362
+ .filter((part) => reported.has(part.approvalId))
363
+ .map(({ caller: _caller, ...outcome }) => outcome)
364
+ if (outcomes.length > 0) continuing.push({ child, outcomes })
365
+ }
366
+ return continuing
367
+ }
368
+
369
+ async createTools(): Promise<readonly ModelTool[]> {
370
+ const spawn: ModelTool<SpawnSubagentInput> = {
371
+ name: "spawn_agent",
372
+ description: [
373
+ "Start an isolated child agent and return immediately.",
374
+ "Use a short, stable key for the same logical delegation so retries cannot duplicate work.",
375
+ renderSubagentModelGuide(this.models),
376
+ ...modelChoice(this.models).advice,
377
+ OMIT_MODEL,
378
+ `Pass files to copy files or directories of your sandbox into the child's, at the same paths, before it starts. What the child writes to out/ comes back with wait_agent's result when it finishes, which lists where each file is.`,
379
+ `A child that has not answered after ${this.models.maxSteps} steps (model calls) stops and fails with agent.step_limit_reached; pass maxSteps to stop it sooner.`,
380
+ `At most ${this.context.subagentConcurrencyPerRun} child agents may be active for this run.`,
381
+ ].join("\n"),
382
+ inputSchema: spawnInputSchema(this.models),
383
+ parseInput: parseSpawnInput,
384
+ execute: async (value, { signal }) => {
385
+ const output = await this.spawn(value, signal)
386
+ assertJsonValue(output)
387
+ return output
388
+ },
389
+ errorText: agentToolErrorText,
390
+ }
391
+ const wait: ModelTool<WaitForSubagentsInput> = {
392
+ name: "wait_agent",
393
+ description: [
394
+ "Wait for previously spawned child agents and return their final text or failure, and the files each wrote to out/, each with its path in your sandbox. Pass every run id whose result is needed.",
395
+ "Shortly before this run must end, it returns children still at work as queued or running, so you can answer with what the others found.",
396
+ "A child paused on calls that wait for the user's approval returns as awaiting_approval, with those calls: it continues once the user decides, unless the user sends a new message or stops instead.",
397
+ "A message you sent a child that it has not read is listed in its unread. When one came as it answered, earlierAnswer holds what it answered before, and text what it wrote after.",
398
+ "A child that failed with agent.step_limit_reached did not finish: partialAnswer holds the last text it wrote.",
399
+ "It returns as soon as a child of this turn asks you a question, listed in questions with its key, whichever children you wait for: the child waits for your answer, which you give with message_agent.",
400
+ ].join("\n"),
401
+ inputSchema: waitInputSchema(this.context.subagentConcurrencyPerRun),
402
+ parseInput: (value) => parseWaitInput(value, this.context.subagentConcurrencyPerRun),
403
+ // A rich result, so its files reach later turns through $SIXB_ATTACHMENTS and the work trace.
404
+ execute: async (value, { signal }) => {
405
+ const { files, ...answer } = await this.wait(value, signal)
406
+ const output: AgentToolResult = {
407
+ kind: "agentToolResult",
408
+ content: [
409
+ { type: "text", text: JSON.stringify(answer) },
410
+ ...files.map(({ fileRef }) => ({ type: "file" as const, fileRef })),
411
+ ],
412
+ }
413
+ assertJsonValue(output)
414
+ return output
415
+ },
416
+ // The answer lists each file's path this turn; the Agent reads the ones it needs.
417
+ toModelOutput: (output) => ({
418
+ type: "text",
419
+ value: isAgentToolResult(output)
420
+ ? output.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
421
+ : JSON.stringify(output),
422
+ }),
423
+ errorText: agentToolErrorText,
424
+ }
425
+ const message: ModelTool<MessageSubagentInput> = {
426
+ name: "message_agent",
427
+ description: [
428
+ "Send a message to a child agent still at work, by the key you spawned it with. It reads the message before its next step, or before its first while it is queued, and its answer accounts for it.",
429
+ "Use it to correct its course, add information it needs, or narrow its task, instead of waiting for an answer you would discard. Then collect its answer with wait_agent as usual.",
430
+ "A child that finished, or paused for the user's approval, cannot read one.",
431
+ "While a child waits on the question it asked you, your message is its answer. A child that wait_agent listed as awaiting_answer, paused on its question when an earlier turn ended, continues where it stopped with your message as its answer.",
432
+ ].join("\n"),
433
+ inputSchema: messageInputSchema(),
434
+ parseInput: parseMessageInput,
435
+ execute: async (value, { signal, callId, toolCallId }) => {
436
+ const output = await this.message(value, `${callId}:${toolCallId}`, signal)
437
+ assertJsonValue(output)
438
+ return output
439
+ },
440
+ errorText: agentToolErrorText,
441
+ }
442
+ return [spawn, wait, message]
443
+ }
444
+
445
+ /**
446
+ * Send a child a message, through the turn's mailbox. Its id names this turn, the model call and
447
+ * the tool call in it, so a replay of the call is the same message and the child reads it once,
448
+ * while two calls never share one, whatever ids the provider gives its tool calls.
449
+ */
450
+ async message(
451
+ input: MessageSubagentInput,
452
+ callId: string,
453
+ signal: AbortSignal
454
+ ): Promise<MessageSubagentOutput> {
455
+ signal.throwIfAborted()
456
+ const key = requireNonEmpty("message_agent", input.key, "key", 128)
457
+ const text = requireNonEmpty("message_agent", input.text, "text")
458
+ const sent = { id: `${this.parentRun.id}:${callId}`, text }
459
+ // A replay of the call that answered a question is that answer, sent once.
460
+ const answered = this.#answers.get(sent.id)
461
+ if (answered) return answered
462
+
463
+ const { children } = this.session
464
+ const child = await children.get(createSubagentRunId(this.parentRun.id, key))
465
+ if (!child) {
466
+ const paused = await this.pausedOnQuestion(key)
467
+ if (paused) return this.answerPaused(paused, key, sent, signal)
468
+ }
469
+ if (child?.kind !== "subagent" || child.parentRunId !== this.parentRun.id) {
470
+ throw new AgentToolPublicError(
471
+ (await this.latestChildUnder(key))
472
+ ? `[SixbAgent] '${key}' is a child agent of an earlier turn, which ended with it. Spawn it again in this turn, with the same key if you like, and message it then.`
473
+ : `[SixbAgent] '${key}' is not a child agent of this turn. Use the key you passed to spawn_agent.`
474
+ )
475
+ }
476
+ // Once its call is filed it pauses at the end of its step, before it would read a message.
477
+ if (isPausedSubagentRun(child) || (await children.holdsRun(child.id))) {
478
+ throw new AgentToolPublicError(
479
+ `[SixbAgent] '${key}' is paused for the user's approval and reads no message until it continues, in the turn after the user decides. Message it then, or tell the user what to change.`
480
+ )
481
+ }
482
+ const { status } = child
483
+ if (status !== "queued" && status !== "running") {
484
+ throw new AgentToolPublicError(
485
+ `[SixbAgent] '${key}' already ended (${status}), so it cannot read a message. Spawn a new child with another key to go on.`
486
+ )
487
+ }
488
+
489
+ // While it waits on a question the model read, the message is its answer. The question is
490
+ // claimed before any wait, so of two answers sent at once only the first is one.
491
+ const question = this.#family.question(child.id)
492
+ if (question && status === "running" && this.#reported.has(question.id)) {
493
+ this.#family.answered(question)
494
+ try {
495
+ this.#family.send(child.id, { ...sent, kind: "answer", inReplyTo: question.id })
496
+ } catch (error) {
497
+ this.#family.reopen(question)
498
+ throw stoppedReading(error, key)
499
+ }
500
+ const output = { runId: child.id, status, delivery: "answer" } as const
501
+ this.#answers.set(sent.id, output)
502
+ return output
503
+ }
504
+
505
+ try {
506
+ this.#family.send(child.id, { ...sent, kind: "message" })
507
+ } catch (error) {
508
+ throw stoppedReading(error, key)
509
+ }
510
+ const toChild = this.#sent.get(child.id) ?? []
511
+ if (!toChild.some((message) => message.id === sent.id)) toChild.push(sent)
512
+ this.#sent.set(child.id, toChild)
513
+
514
+ return { runId: child.id, status, delivery: status === "queued" ? "first-step" : "next-step" }
515
+ }
516
+
517
+ /** The latest child under `key` of this conversation's turns, this one's included. */
518
+ private async latestChildUnder(key: string): Promise<SubagentRunRecord | undefined> {
519
+ const [latest] = await this.session.children.inConversation({ spawnKey: key, limit: 1 })
520
+ return latest
521
+ }
522
+
523
+ /**
524
+ * The child paused on its question that a message under `key` would continue: the latest run of
525
+ * the latest thread under the key, or, past the continuations of it that failed or were stopped,
526
+ * the run they continued, so their failure does not hide the question. A later spawn under the
527
+ * key replaces it.
528
+ */
529
+ private async pausedOnQuestion(key: string): Promise<SubagentRunRecord | undefined> {
530
+ const latest = await this.latestChildUnder(key)
531
+ if (!latest) return undefined
532
+
533
+ const runs = await this.session.children.threadRuns(latest.threadId)
534
+ const live = [...runs]
535
+ .reverse()
536
+ .find((run) => run.status !== "failed" && run.status !== "cancelled")
537
+ return live && isAwaitingAnswerRun(live) ? live : undefined
538
+ }
539
+
540
+ /** Whether a continuation went on with its parent's answer, as its trigger says. */
541
+ private async continuesAfterAnswer(run: SubagentRunRecord): Promise<boolean> {
542
+ const trigger = await this.session.threads.message(run.triggerMessageId)
543
+ return trigger?.parts.some((part) => part.type === "mail" && part.kind === "answer") ?? false
544
+ }
545
+
546
+ private async subagentRun(id: string): Promise<SubagentRunRecord | undefined> {
547
+ const run = await this.session.children.get(id)
548
+ return run?.kind === "subagent" ? run : undefined
549
+ }
550
+
551
+ /**
552
+ * The children of this conversation still paused on their question, each with it: one indexed
553
+ * read, which finds none in a conversation that has none, then one per key that has some.
554
+ */
555
+ async waitingQuestions(): Promise<readonly WaitedQuestion[]> {
556
+ const paused = await this.session.children.inConversation({ finishReason: "awaiting_answer" })
557
+ const waiting: WaitedQuestion[] = []
558
+ for (const key of new Set(paused.map((run) => run.spawnKey))) {
559
+ const child = await this.pausedOnQuestion(key)
560
+ const question = child ? await this.deferredQuestionOf(child) : undefined
561
+ if (child && question) waiting.push({ key, runId: child.id, ...question })
562
+ }
563
+ return waiting
564
+ }
565
+
566
+ /**
567
+ * Continue a child paused on its question, as a child of this turn under the same key, with this
568
+ * message as the answer it reads first. Admissions go one at a time, so a second answer in the
569
+ * same step finds the first one's continuation and is refused.
570
+ */
571
+ private async answerPaused(
572
+ paused: SubagentRunRecord,
573
+ key: string,
574
+ sent: SentMessage,
575
+ signal: AbortSignal
576
+ ): Promise<MessageSubagentOutput> {
577
+ const question = await this.deferredQuestionOf(paused)
578
+ if (!question) {
579
+ throw new Error(
580
+ `[SixbAgent] Subagent run '${paused.id}' paused on a question its thread does not hold.`
581
+ )
582
+ }
583
+ const answer: AgentMailPart = {
584
+ type: "mail",
585
+ id: sent.id,
586
+ from: "parent",
587
+ kind: "answer",
588
+ inReplyTo: question.id,
589
+ text: sent.text,
590
+ }
591
+ const runId = createSubagentRunId(this.parentRun.id, key)
592
+ const admitted = await this.admitInTurn(async () => {
593
+ if (await this.subagentRun(runId)) {
594
+ throw new AgentToolPublicError(
595
+ `[SixbAgent] '${key}' already continues with the answer you sent it this turn. Message it again once it is at work, or wait for it with wait_agent.`
596
+ )
597
+ }
598
+ await this.clearDeadAttempts(paused, signal)
599
+ const { spec, continuation } = this.continuationOf(paused, [answer])
600
+ return this.admit(runId, key, spec, signal, continuation)
601
+ })
602
+
603
+ const output: MessageSubagentOutput = {
604
+ runId: admitted.runId,
605
+ status: admitted.status === "queued" ? "queued" : "running",
606
+ delivery: "answer",
607
+ continues: paused.id,
608
+ }
609
+ this.#answers.set(sent.id, output)
610
+ return output
611
+ }
612
+
613
+ /**
614
+ * The question a child paused on, from its thread: the last message of the run that paused, its
615
+ * work since its last delivery. Only one `awaiting_answer` has one.
616
+ */
617
+ private async deferredQuestionOf(run: SubagentRunRecord): Promise<QuestionRef | undefined> {
618
+ if (!isAwaitingAnswerRun(run)) return undefined
619
+
620
+ const { messages } = await this.session.threads.messages({
621
+ threadId: run.threadId,
622
+ order: "desc",
623
+ limit: 2,
624
+ })
625
+ const work = messages.find(
626
+ (message) => message.runId === run.id && message.role === "assistant"
627
+ )
628
+ return work ? deferredChildQuestion([work]) : undefined
629
+ }
630
+
631
+ /**
632
+ * The questions of the turn's children still at work that the model has not read, marked read:
633
+ * its answer would otherwise end the turn without them.
634
+ */
635
+ async unreadQuestions(): Promise<readonly WaitedQuestion[]> {
636
+ const unread = (await this.askingChildren()).filter(
637
+ (question) => !this.#reported.has(question.id)
638
+ )
639
+ for (const question of unread) this.#reported.add(question.id)
640
+ return unread
641
+ }
642
+
643
+ /**
644
+ * Before the turn records its end, while it still runs: tell each child still waiting on its
645
+ * question that the turn ends without an answer, then wait for each to pause on it. The turn's end cancels the children still at work, so a child it told and that has not
646
+ * paused yet would be stopped; while the turn runs, the repair pass leaves its children alone.
647
+ */
648
+ async deferOpenQuestions(signal: AbortSignal): Promise<void> {
649
+ let asking: readonly WaitedQuestion[]
650
+ try {
651
+ asking = await this.askingChildren()
652
+ } catch (error) {
653
+ console.error(
654
+ `[SixbAgent] Could not read the questions of Agent run '${this.parentRun.id}'; its children asking one are cancelled with the turn.`,
655
+ error
656
+ )
657
+ return
658
+ }
659
+
660
+ const deferred: string[] = []
661
+ for (const question of asking) {
662
+ try {
663
+ this.#family.send(question.runId, {
664
+ id: `${this.parentRun.id}:deferred:${question.id}`,
665
+ kind: "deferred",
666
+ inReplyTo: question.id,
667
+ text: "",
668
+ })
669
+ deferred.push(question.runId)
670
+ } catch (error) {
671
+ console.error(
672
+ `[SixbAgent] Could not tell subagent run '${question.runId}' that its question waits for a later turn; it is cancelled with the turn.`,
673
+ error
674
+ )
675
+ }
676
+ }
677
+
678
+ try {
679
+ while (deferred.length > 0) {
680
+ const paused = this.#family.changed()
681
+ const runs = await this.session.children.getMany(deferred)
682
+ if (runs.every((run) => run.status !== "queued" && run.status !== "running")) return
683
+ await delay(CHILD_WAIT_RECHECK_MS, signal, paused)
684
+ }
685
+ } catch (error) {
686
+ // The turn's interruption checks record why it stopped.
687
+ if (signal.aborted) return
688
+ throw error
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Wait until none of the turn's children is queued or running: a pausing turn's end cancels those
694
+ * still at work, and one that holds a call pauses by itself meanwhile.
695
+ */
696
+ async settleChildren(signal: AbortSignal): Promise<void> {
697
+ for (;;) {
698
+ const finished = this.#family.changed()
699
+ if ((await this.session.children.activeCount()) === 0) return
700
+
701
+ try {
702
+ await delay(CHILD_WAIT_RECHECK_MS, signal, finished)
703
+ } catch (error) {
704
+ // The turn's interruption checks record why it stopped, with what it wrote.
705
+ if (signal.aborted) return
706
+ throw error
707
+ }
708
+ }
709
+ }
710
+
711
+ /** The open questions of the turn's children still at work, each with the child's key. */
712
+ private async askingChildren(): Promise<readonly WaitedQuestion[]> {
713
+ const open = this.#family.questions()
714
+ if (open.length === 0) return []
715
+
716
+ const runs = await this.session.children.getMany(open.map((question) => question.runId))
717
+ const byId = new Map(runs.map((run) => [run.id, run]))
718
+ return open.flatMap((question: ChildQuestion) => {
719
+ const run = byId.get(question.runId)
720
+ if (run?.kind !== "subagent" || run.parentRunId !== this.parentRun.id) return []
721
+ if (run.status !== "running") return []
722
+
723
+ return [{ key: run.spawnKey, runId: run.id, id: question.id, text: question.text }]
724
+ })
725
+ }
726
+
727
+ async spawn(input: SpawnSubagentInput, signal: AbortSignal): Promise<SpawnSubagentOutput> {
728
+ signal.throwIfAborted()
729
+ const key = requireNonEmpty("spawn_agent", input.key, "key", 128)
730
+ const task = requireNonEmpty("spawn_agent", input.task, "task")
731
+ const model = this.resolveModel(input.model)
732
+ const reasoning = input.reasoning ?? model.defaultReasoning
733
+ const maxSteps = this.resolveMaxSteps(input.maxSteps)
734
+ const sources = input.files?.length
735
+ ? await listHandedSources({ files: this.runFiles(), paths: input.files, signal })
736
+ : undefined
737
+ const runId = createSubagentRunId(this.parentRun.id, key)
738
+ const specWith = (files: readonly SubagentRunFile[] | undefined) =>
739
+ this.childSpec({ task, model, tier: model.tier, reasoning, maxSteps, files })
740
+
741
+ // One admission at a time: only this turn adds children to it, so admission's answer is known
742
+ // before any file is read, and a refused spawn reads and stores none.
743
+ return this.admitInTurn(async () => {
744
+ const existing = await this.admissionOf(runId, key)
745
+ if (existing) {
746
+ // The same child only if everything is the same, the files' bytes too.
747
+ const files =
748
+ sources && sameSpecBesidesFiles(existing.spec, specWith(undefined), sources)
749
+ ? await handedFileRefs({ files: this.runFiles(), sources, signal })
750
+ : undefined
751
+ const spec = specWith(files)
752
+ if (!isDeepStrictEqual(existing.spec, spec)) throw duplicateKey(key)
753
+ return this.admit(runId, key, spec, signal)
754
+ }
755
+
756
+ const stored = sources
757
+ ? await storeHandedFiles({ files: this.runFiles(), sources, signal })
758
+ : undefined
759
+ try {
760
+ return await this.admit(runId, key, specWith(stored?.files), signal)
761
+ } catch (error) {
762
+ // Nothing was admitted, so the files do not count against the run.
763
+ stored?.release()
764
+ throw error
765
+ }
766
+ })
767
+ }
768
+
769
+ private admitInTurn<T>(admission: () => Promise<T>): Promise<T> {
770
+ const admitted = this.#admissions.then(admission)
771
+ this.#admissions = admitted.catch(() => {})
772
+ return admitted
773
+ }
774
+
775
+ /**
776
+ * What admission will answer, read before the files the child is handed: the child already
777
+ * spawned with this key, else nothing once checked that the turn may spawn another.
778
+ */
779
+ private async admissionOf(runId: string, key: string): Promise<SubagentRunRecord | null> {
780
+ const { children } = this.session
781
+ const maxActive = this.context.subagentConcurrencyPerRun
782
+ const [existing, parent] = await Promise.all([
783
+ children.get(runId),
784
+ children.get(this.parentRun.id),
785
+ ])
786
+ if (existing) {
787
+ // A continuation works in the thread of the turn that spawned it, never this turn's.
788
+ if (
789
+ existing.kind === "subagent" &&
790
+ existing.threadId !== createSubagentThreadId(this.parentRun.id, key)
791
+ ) {
792
+ const after = (await this.continuesAfterAnswer(existing)) ? "your answer" : "the approval"
793
+ throw new AgentToolPublicError(
794
+ isTerminalSubagent(existing)
795
+ ? `[SixbAgent] '${key}' already continued after ${after}, and wait_agent returns how it ended. To run it again, spawn it with a new key.`
796
+ : `[SixbAgent] '${key}' is the sub-agent that continues after ${after}; wait for it with wait_agent.`
797
+ )
798
+ }
799
+ if (existing.kind === "subagent" && existing.parentRunId === this.parentRun.id) {
800
+ return existing
801
+ }
802
+ throw duplicateKey(key)
803
+ }
804
+
805
+ if (parent?.status !== "running") {
806
+ throw publicSpawnError(
807
+ new AgentStorageError("invalid_state", "Parent ended."),
808
+ key,
809
+ maxActive
810
+ )
811
+ }
812
+ if (parent.execution?.token !== requiredExecutionToken(this.parentRun)) {
813
+ throw new AgentExecutionLostError(parent.id)
814
+ }
815
+ if ((await children.activeCount()) >= maxActive) {
816
+ throw publicSpawnError(
817
+ new AgentStorageError("active_child_limit", "Active child limit."),
818
+ key,
819
+ maxActive
820
+ )
821
+ }
822
+ return null
823
+ }
824
+
825
+ /**
826
+ * The run of this turn that continues `paused` in its thread: its model, task and files, this
827
+ * turn's mode, and a trigger of what it goes on with (the outcomes of its calls, or
828
+ * its parent's answer), what came back to its sandbox and when it continues.
829
+ */
830
+ private continuationOf(
831
+ paused: SubagentRunRecord,
832
+ goesOnWith: readonly AgentMessagePart[]
833
+ ): {
834
+ readonly spec: SubagentRunSpec
835
+ readonly continuation: Pick<AgentChildDraft, "thread" | "trigger" | "createdAt">
836
+ } {
837
+ const spec = this.childSpec({
838
+ task: paused.spec.task,
839
+ model: paused.spec.model,
840
+ tier: paused.spec.tier,
841
+ reasoning: paused.spec.reasoning,
842
+ maxSteps: paused.spec.maxSteps,
843
+ files: paused.spec.files,
844
+ })
845
+ const createdAt = new Date()
846
+ const parts = continuationTrigger({
847
+ goesOnWith,
848
+ paused,
849
+ keepsWorkspace: this.context.keepsChildWorkspaces,
850
+ createdAt,
851
+ settings: sentSettings(spec, this.context),
852
+ })
853
+ return {
854
+ spec,
855
+ continuation: {
856
+ thread: { id: paused.threadId, create: false },
857
+ trigger: { id: createAgentMessageId(), parts },
858
+ createdAt,
859
+ },
860
+ }
861
+ }
862
+
863
+ /** A child asks no less than its turn, dates as its requester does, and ends with the turn. */
864
+ private childSpec(input: {
865
+ readonly task: string
866
+ readonly model: LanguageModelRef
867
+ readonly tier: LanguageModelTier | undefined
868
+ readonly reasoning: AgentReasoning | undefined
869
+ readonly maxSteps: number | undefined
870
+ readonly files: readonly SubagentRunFile[] | undefined
871
+ }): SubagentRunSpec {
872
+ const { task, model, tier, reasoning, maxSteps, files } = input
873
+ const { approvalMode, timeZone, locale } = this.parentRun.spec ?? {}
874
+ return {
875
+ model: { provider: model.provider, modelId: model.modelId },
876
+ task,
877
+ toolNames: this.delegation.toolNames,
878
+ ...(tier === undefined ? {} : { tier }),
879
+ ...(reasoning === undefined ? {} : { reasoning }),
880
+ ...(maxSteps === undefined ? {} : { maxSteps }),
881
+ ...(approvalMode === undefined ? {} : { approvalMode }),
882
+ ...(timeZone === undefined ? {} : { timeZone }),
883
+ ...(locale === undefined ? {} : { locale }),
884
+ ...(files === undefined ? {} : { files }),
885
+ }
886
+ }
887
+
888
+ /**
889
+ * Admit a child of this turn. A spawned child works in a thread of its own, which starts with its
890
+ * task and its files; a continuation goes into its thread with the outcomes it continues with.
891
+ */
892
+ private async admit(
893
+ runId: string,
894
+ key: string,
895
+ spec: SubagentRunSpec,
896
+ signal: AbortSignal,
897
+ continuation?: Pick<AgentChildDraft, "thread" | "trigger" | "createdAt">
898
+ ): Promise<SpawnSubagentOutput> {
899
+ let run: SubagentRunRecord
900
+ try {
901
+ run = await this.session.children.spawn({
902
+ spawnKey: key,
903
+ spec,
904
+ ...(continuation ?? {
905
+ thread: { create: true },
906
+ trigger: {
907
+ id: createAgentMessageId(),
908
+ parts: [
909
+ { type: "text", text: spec.task },
910
+ ...(spec.files === undefined
911
+ ? []
912
+ : [{ type: "text" as const, text: renderHandedFiles(spec.files) }]),
913
+ ],
914
+ },
915
+ }),
916
+ })
917
+ if (run.id !== runId) {
918
+ throw new Error(`[SixbAgent] Child '${key}' was admitted as '${run.id}', not '${runId}'.`)
919
+ }
920
+ } catch (error) {
921
+ throw publicSpawnError(error, key, this.context.subagentConcurrencyPerRun)
922
+ }
923
+
924
+ signal.throwIfAborted()
925
+ if (run.status === "queued") this.startChild(run, this.#family)
926
+
927
+ return {
928
+ runId: run.id,
929
+ status: run.status,
930
+ model: { provider: run.spec.model.provider, modelId: run.spec.model.modelId },
931
+ }
932
+ }
933
+
934
+ async wait(input: WaitForSubagentsInput, signal: AbortSignal): Promise<WaitForSubagentsOutput> {
935
+ const passedIds = normalizeRunIds(input.runIds, this.context.subagentConcurrencyPerRun)
936
+ // A child of an earlier turn is waited for as the child of this one that continues it, else
937
+ // as it ended.
938
+ const runIds = await Promise.all(passedIds.map((runId) => this.continuedChildId(runId)))
939
+ const earlierTurns = await this.earlierTurnsOf(runIds)
940
+ for (;;) {
941
+ signal.throwIfAborted()
942
+ // Taken before the reads, so a question or a finish that comes during them wakes the wait.
943
+ const changed = this.#family.changed()
944
+ const runs = await this.session.children.getMany(runIds)
945
+ const byId = new Map(runs.map((run) => [run.id, run]))
946
+ const children = runIds.map((runId, index) => {
947
+ const run = byId.get(runId)
948
+ if (
949
+ !run ||
950
+ run.kind !== "subagent" ||
951
+ (run.parentRunId !== this.parentRun.id && !earlierTurns.has(run.parentRunId))
952
+ ) {
953
+ throw new AgentToolPublicError(
954
+ `[SixbAgent] '${passedIds[index]}' is not a child of the current Agent run.`
955
+ )
956
+ }
957
+ return run
958
+ })
959
+ // A child blocked on its question waits for this turn, so a new question ends any wait,
960
+ // and one already returned ends a wait for its own child.
961
+ const asking = await this.askingChildren()
962
+ const asked = asking.some(
963
+ (question) => !this.#reported.has(question.id) || runIds.includes(question.runId)
964
+ )
965
+ if (children.every(isTerminalSubagent) || asked) {
966
+ const awaiting = await this.session.children.awaitingApproval(runIds)
967
+ const delivered = await this.deliverFiles(children, signal)
968
+ const messages = await Promise.all(
969
+ children.map(async (run) => ({
970
+ ...(await this.messagesTo(run)),
971
+ ...(await this.partialAnswerOf(run)),
972
+ }))
973
+ )
974
+ // It lists the questions it returns first, and those its children wait on.
975
+ const listed = asking.filter(
976
+ (question) => !this.#reported.has(question.id) || runIds.includes(question.runId)
977
+ )
978
+ for (const question of asking) this.#reported.add(question.id)
979
+ const open = new Map(asking.map((question) => [question.runId, question]))
980
+ const questions = await Promise.all(
981
+ children.map(async (run) => open.get(run.id) ?? (await this.deferredQuestionOf(run)))
982
+ )
983
+ return {
984
+ // Each result keeps the id the Agent passed.
985
+ results: children.map((run, index) => ({
986
+ ...waitedResult(
987
+ run,
988
+ awaiting.get(run.id),
989
+ delivered.byChild.get(run.id),
990
+ questions[index]
991
+ ),
992
+ ...messages[index],
993
+ runId: passedIds[index] ?? run.id,
994
+ })),
995
+ ...(listed.length > 0 ? { questions: listed } : {}),
996
+ files: delivered.attached,
997
+ ...(delivered.artifactsError === undefined
998
+ ? {}
999
+ : { artifactsError: delivered.artifactsError }),
1000
+ }
1001
+ }
1002
+ // A child of an earlier turn ends into that turn's mailbox, which this one does not hear.
1003
+ const unheard = children.some(
1004
+ (run) => run.parentRunId !== this.parentRun.id && !isTerminalSubagent(run)
1005
+ )
1006
+ const recheckMs = unheard ? OTHER_TURN_RECHECK_MS : CHILD_WAIT_RECHECK_MS
1007
+ await delay(recheckMs, signal, changed)
1008
+ }
1009
+ }
1010
+
1011
+ /**
1012
+ * What became of what this turn sent an ended child, from its thread, which holds each message
1013
+ * it read: those it did not read, and, when one came as it answered, the answer it gave before.
1014
+ * A failed child's failure is what the parent acts on.
1015
+ */
1016
+ private async messagesTo(run: SubagentRunRecord): Promise<MessagesReport> {
1017
+ const sent = this.#sent.get(run.id)
1018
+ if (!sent || !isTerminalSubagent(run) || run.status === "failed") return {}
1019
+
1020
+ const { messages } = await this.session.threads.messages({
1021
+ threadId: run.threadId,
1022
+ order: "asc",
1023
+ })
1024
+ const read = new Set(
1025
+ messages.flatMap((message) =>
1026
+ message.parts.flatMap((part) => (part.type === "mail" ? [part.id] : []))
1027
+ )
1028
+ )
1029
+ const unread = sent.filter((message) => !read.has(message.id))
1030
+ return {
1031
+ ...(unread.length > 0 ? { unread } : {}),
1032
+ ...answerBeforeLateMessage(
1033
+ messages.filter((message) => message.runId === run.id),
1034
+ run.result?.text ?? ""
1035
+ ),
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * What a child its step limit stopped wrote last, from its thread: its failure says it did not
1041
+ * finish, and its parent decides whether this is enough.
1042
+ */
1043
+ private async partialAnswerOf(
1044
+ run: SubagentRunRecord
1045
+ ): Promise<Pick<WaitedSubagentResult, "partialAnswer">> {
1046
+ if (run.status !== "failed" || run.error?.code !== "agent.step_limit_reached") return {}
1047
+
1048
+ const { messages } = await this.session.threads.messages({
1049
+ threadId: run.threadId,
1050
+ order: "asc",
1051
+ })
1052
+ const written = messages
1053
+ .filter((message) => message.runId === run.id && message.role === "assistant")
1054
+ .flatMap((message) => message.parts)
1055
+ .flatMap((part) => (part.type === "text" && part.text.trim() ? [part.text.trim()] : []))
1056
+ const partialAnswer = written.at(-1)
1057
+ return partialAnswer ? { partialAnswer } : {}
1058
+ }
1059
+
1060
+ /**
1061
+ * The run a child of an earlier turn is waited for as: its thread's latest, the one that continues
1062
+ * it when this turn resumes its pause; else `runId` itself.
1063
+ */
1064
+ private async continuedChildId(runId: string): Promise<string> {
1065
+ const { children } = this.session
1066
+ const waited = await children.get(runId)
1067
+ if (waited?.kind !== "subagent" || waited.parentRunId === this.parentRun.id) return runId
1068
+
1069
+ const latest = await children.threadRuns(waited.threadId)
1070
+ return latest.at(-1)?.id ?? runId
1071
+ }
1072
+
1073
+ /** Which parents of these children are earlier turns of this turn's conversation. */
1074
+ private async earlierTurnsOf(runIds: readonly string[]): Promise<ReadonlySet<string>> {
1075
+ const children = await this.session.children.getMany(runIds)
1076
+ const parentIds = children.flatMap((run) =>
1077
+ run.kind === "subagent" && run.parentRunId !== this.parentRun.id ? [run.parentRunId] : []
1078
+ )
1079
+ if (parentIds.length === 0) return new Set()
1080
+
1081
+ const parents = await this.session.children.getMany(parentIds)
1082
+ return new Set(
1083
+ parents
1084
+ .filter(
1085
+ (parent) =>
1086
+ parent.kind === "conversation" &&
1087
+ parent.threadId === this.parentRun.threadId &&
1088
+ parent.createdAt <= this.parentRun.createdAt
1089
+ )
1090
+ .map((parent) => parent.id)
1091
+ )
1092
+ }
1093
+
1094
+ /**
1095
+ * Copy what each finished child wrote under `out/` into the parent's sandbox, once, and install
1096
+ * what the children published in its `$SIXB_ARTIFACTS`, as the parent's own. A result holds at
1097
+ * most the attachment limits of new files, a child's whole or not at all; a child that does not
1098
+ * fit, or whose files cannot be copied, says so, and its files come with a later wait.
1099
+ */
1100
+ private async deliverFiles(
1101
+ children: readonly SubagentRunRecord[],
1102
+ signal: AbortSignal
1103
+ ): Promise<{
1104
+ readonly byChild: ReadonlyMap<string, ChildFiles>
1105
+ readonly attached: readonly InstalledChildFile[]
1106
+ readonly artifactsError?: string
1107
+ }> {
1108
+ const byChild = new Map<string, ChildFiles>()
1109
+ const attached: InstalledChildFile[] = []
1110
+ let attachedBytes = 0
1111
+
1112
+ for (const child of children) {
1113
+ if (child.status !== "succeeded") continue
1114
+ if (isAwaitingAnswerRun(child)) {
1115
+ if (child.result?.files?.length) {
1116
+ byChild.set(child.id, { note: "They come back once it continues and finishes." })
1117
+ }
1118
+ continue
1119
+ }
1120
+ if (isPausedSubagentRun(child)) {
1121
+ if (child.result?.files?.length) {
1122
+ byChild.set(child.id, {
1123
+ note: "They come back if it continues once the user decides, when it finishes.",
1124
+ })
1125
+ }
1126
+ continue
1127
+ }
1128
+ const { files: outputs = [], filesError } = child.result ?? {}
1129
+ if (filesError) byChild.set(child.id, { note: filesError })
1130
+
1131
+ const installed = this.#installed.get(child.id)
1132
+ if (installed) {
1133
+ byChild.set(child.id, { files: installed })
1134
+ continue
1135
+ }
1136
+ if (outputs.length === 0) continue
1137
+
1138
+ const bytes = outputs.reduce((sum, file) => sum + file.fileRef.sizeBytes, 0)
1139
+ const { maxFiles, totalMaxBytes } = SANDBOX_ATTACHMENT_LIMITS
1140
+ const fits =
1141
+ attached.length + outputs.length <= maxFiles && attachedBytes + bytes <= totalMaxBytes
1142
+ if (!fits && attached.length > 0) {
1143
+ byChild.set(child.id, {
1144
+ note: `Its ${outputs.length} files did not fit in this result, which holds at most ${maxFiles} files, ${formatBytes(totalMaxBytes)} in all. Wait for this child again to get them.`,
1145
+ })
1146
+ continue
1147
+ }
1148
+
1149
+ try {
1150
+ const copied = await installChildOutputs({
1151
+ files: this.runFiles(),
1152
+ key: child.spawnKey,
1153
+ outputs,
1154
+ signal,
1155
+ })
1156
+ this.#installed.set(child.id, copied)
1157
+ attached.push(...copied)
1158
+ attachedBytes += bytes
1159
+ byChild.set(child.id, { files: copied })
1160
+ } catch (error) {
1161
+ if (signal.aborted) throw error
1162
+ byChild.set(child.id, {
1163
+ note: `Its files could not be copied into your sandbox (${errorMessage(error)}). Wait for this child again to retry.`,
1164
+ })
1165
+ }
1166
+ }
1167
+
1168
+ let artifactsError: string | undefined
1169
+ try {
1170
+ await this.#runFiles?.installArtifactsFrom(
1171
+ children.map((child) => child.id),
1172
+ signal
1173
+ )
1174
+ } catch (error) {
1175
+ if (signal.aborted) throw error
1176
+ artifactsError = `What these children published could not all be installed in $SIXB_ARTIFACTS (${errorMessage(error)}). The addresses in their answers still work.`
1177
+ }
1178
+ return { byChild, attached, ...(artifactsError === undefined ? {} : { artifactsError }) }
1179
+ }
1180
+
1181
+ private runFiles(): AgentRunFiles {
1182
+ if (!this.#runFiles) {
1183
+ throw new Error("[SixbAgent] Delegation tools ran before their run's environment.")
1184
+ }
1185
+ return this.#runFiles
1186
+ }
1187
+
1188
+ /** A spawn may ask for fewer steps than the project allows, never more. */
1189
+ private resolveMaxSteps(maxSteps: number | undefined): number | undefined {
1190
+ const limit = this.models.maxSteps
1191
+ if (maxSteps !== undefined && maxSteps > limit) {
1192
+ throw new AgentToolPublicError(
1193
+ `[SixbAgent] spawn_agent maxSteps must be at most ${limit}, the project's limit. Omit it to use that limit.`
1194
+ )
1195
+ }
1196
+ return maxSteps
1197
+ }
1198
+
1199
+ private resolveModel(
1200
+ ref: LanguageModelRef | LanguageModelTier | undefined
1201
+ ): AgentRunDelegationModel {
1202
+ const { models, defaultModel } = this.models
1203
+ const byRef = (wanted: LanguageModelRef) => models.find((model) => sameModel(model, wanted))
1204
+ const projectDefault = () => {
1205
+ const model = byRef(defaultModel)
1206
+ if (!model)
1207
+ throw new Error("[SixbAgent] The project's default model is not among its models.")
1208
+ return model
1209
+ }
1210
+ if (ref === undefined) return projectDefault()
1211
+ // A tier's first model; a tier left out, or any tier of a list, gives the default.
1212
+ if (typeof ref === "string")
1213
+ return models.find((model) => model.tier === ref) ?? projectDefault()
1214
+ const model = byRef(ref)
1215
+ if (model) return model
1216
+ const available = models.map(formatModelRef).join(", ")
1217
+ throw new AgentToolPublicError(
1218
+ `[SixbAgent] Language model ${formatModelRef(ref)} is not configured for this project. ` +
1219
+ `Use one of: ${available}. Omit model to use the project default.`
1220
+ )
1221
+ }
1222
+ }
1223
+
1224
+ /**
1225
+ * Built from each model's configured definition, never from its provider catalog: the guide is in
1226
+ * every turn's tools, so it stays the same for the process and catalog I/O cannot fail a turn.
1227
+ */
1228
+ export function renderSubagentModelGuide(models: AgentRunDelegation): string {
1229
+ const entries = models.models.map((entry) => {
1230
+ const metadata = defineLanguageModel(entry.definition)
1231
+ if (metadata.providerId !== entry.provider || metadata.modelId !== entry.modelId) {
1232
+ throw new Error(
1233
+ "[SixbAgent] Delegation model definition identity does not match its catalog entry."
1234
+ )
1235
+ }
1236
+ const details: string[] = []
1237
+ if (sameModel(entry, models.defaultModel)) details.push("default")
1238
+ if (metadata.contextWindow !== undefined)
1239
+ details.push(`context ${formatTokenCount(metadata.contextWindow)} tokens`)
1240
+ if (metadata.maxInputTokens !== undefined)
1241
+ details.push(`max input ${formatTokenCount(metadata.maxInputTokens)} tokens`)
1242
+ if (metadata.capabilities.reasoning) details.push("reasoning")
1243
+ if (metadata.capabilities.localTools) details.push("tools")
1244
+ const media = metadata.capabilities.inputMediaTypes
1245
+ if (media === "any") details.push("multimodal input")
1246
+ else if (media?.length) details.push(`input: ${media.join(", ")}`)
1247
+ if (details.length === 0 || (details.length === 1 && details[0] === "default"))
1248
+ details.push("metadata unavailable")
1249
+
1250
+ return renderModelLine({
1251
+ ...(entry.tier === undefined ? {} : { tier: entry.tier }),
1252
+ reference: formatModelRef(entry),
1253
+ ...(metadata.name === undefined ? {} : { name: metadata.name }),
1254
+ details: `(${details.join("; ")})`,
1255
+ ...(metadata.description === undefined ? {} : { description: metadata.description }),
1256
+ })
1257
+ })
1258
+
1259
+ const { tiers } = models
1260
+ if (tiers.length === 0) {
1261
+ return ["Available models (provider-declared metadata when available):", ...entries].join("\n")
1262
+ }
1263
+
1264
+ return [
1265
+ "Models you can delegate to:",
1266
+ ...entries,
1267
+ "Tiers rank cost and strength: light is the cheapest and fastest, heavy the strongest.",
1268
+ `Use a tier by default (model: ${tiers.map((tier) => `"${tier}"`).join(" | ")}). Use a specific model when its description fits the task.`,
1269
+ ].join("\n")
1270
+ }
1271
+
1272
+ function modelChoice(models: AgentRunDelegation): typeof LISTED_MODEL_CHOICE {
1273
+ return models.tiers.length > 0 ? TIERED_MODEL_CHOICE : LISTED_MODEL_CHOICE
1274
+ }
1275
+
1276
+ function formatModelRef({ provider, modelId }: LanguageModelRef): string {
1277
+ return JSON.stringify({ provider, modelId })
1278
+ }
1279
+
1280
+ function sameModel(
1281
+ left: { readonly provider: string; readonly modelId: string },
1282
+ right: { readonly provider: string; readonly modelId: string }
1283
+ ): boolean {
1284
+ return left.provider === right.provider && left.modelId === right.modelId
1285
+ }
1286
+
1287
+ function formatTokenCount(value: number): string {
1288
+ if (value >= 1_000_000) return `${formatScaled(value, 1_000_000)}M`
1289
+ if (value >= 1_000) return `${formatScaled(value, 1_000)}k`
1290
+ return String(value)
1291
+ }
1292
+
1293
+ function formatScaled(value: number, scale: number): string {
1294
+ return (Math.round((value / scale) * 100) / 100).toString()
1295
+ }
1296
+
1297
+ function spawnInputSchema(models: AgentRunDelegation): JsonObject {
1298
+ return {
1299
+ type: "object",
1300
+ properties: {
1301
+ key: {
1302
+ type: "string",
1303
+ minLength: 1,
1304
+ maxLength: 128,
1305
+ description: "Stable key for this logical delegation, for example 'compare-suppliers'.",
1306
+ },
1307
+ task: { type: "string", minLength: 1, description: "Focused task for the child agent." },
1308
+ model: {
1309
+ description: `${modelChoice(models).field} Keep provider and modelId unchanged, including any '/' inside modelId. ${OMIT_MODEL}`,
1310
+ anyOf: [...tierChoice(models.tiers), ...modelRefChoices(models)],
1311
+ },
1312
+ reasoning: {
1313
+ anyOf: [
1314
+ { type: "string", enum: [...AGENT_REASONING_LEVELS] },
1315
+ {
1316
+ type: "object",
1317
+ properties: { budgetTokens: { type: "integer", minimum: 0 } },
1318
+ required: ["budgetTokens"],
1319
+ additionalProperties: false,
1320
+ },
1321
+ ],
1322
+ },
1323
+ maxSteps: {
1324
+ type: "integer",
1325
+ minimum: 1,
1326
+ maximum: models.maxSteps,
1327
+ description:
1328
+ "At most this many steps (model calls) for the child. Omit it to use the limit.",
1329
+ },
1330
+ files: {
1331
+ type: "array",
1332
+ minItems: 1,
1333
+ maxItems: SANDBOX_ATTACHMENT_LIMITS.maxFiles,
1334
+ uniqueItems: true,
1335
+ items: { type: "string", minLength: 1 },
1336
+ description:
1337
+ "Paths of files or directories in your sandbox, such as an attachment from $SIXB_ATTACHMENTS or out/chart.png.",
1338
+ },
1339
+ },
1340
+ required: ["key", "task"],
1341
+ additionalProperties: false,
1342
+ }
1343
+ }
1344
+
1345
+ function tierChoice(tiers: readonly LanguageModelTier[]): readonly JsonObject[] {
1346
+ return tiers.length > 0 ? [{ type: "string", enum: [...tiers] }] : []
1347
+ }
1348
+
1349
+ // Keep each pair together: independent enums would also admit unconfigured bindings.
1350
+ function modelRefChoices(models: AgentRunDelegation): readonly JsonObject[] {
1351
+ return models.models.map(({ provider, modelId }) => ({
1352
+ type: "object",
1353
+ properties: {
1354
+ provider: { type: "string", enum: [provider] },
1355
+ modelId: { type: "string", enum: [modelId] },
1356
+ },
1357
+ required: ["provider", "modelId"],
1358
+ additionalProperties: false,
1359
+ }))
1360
+ }
1361
+
1362
+ function messageInputSchema(): JsonObject {
1363
+ return {
1364
+ type: "object",
1365
+ properties: {
1366
+ key: {
1367
+ type: "string",
1368
+ minLength: 1,
1369
+ maxLength: 128,
1370
+ description: "The key you spawned the child with.",
1371
+ },
1372
+ text: {
1373
+ type: "string",
1374
+ minLength: 1,
1375
+ description: "What the child should change or know, as an instruction for its task.",
1376
+ },
1377
+ },
1378
+ required: ["key", "text"],
1379
+ additionalProperties: false,
1380
+ }
1381
+ }
1382
+
1383
+ function waitInputSchema(maxRunIds: number): JsonObject {
1384
+ return {
1385
+ type: "object",
1386
+ properties: {
1387
+ runIds: {
1388
+ type: "array",
1389
+ minItems: 1,
1390
+ maxItems: maxRunIds,
1391
+ uniqueItems: true,
1392
+ items: { type: "string", minLength: 1 },
1393
+ },
1394
+ },
1395
+ required: ["runIds"],
1396
+ additionalProperties: false,
1397
+ }
1398
+ }
1399
+
1400
+ function normalizeRunIds(value: readonly string[], maxRunIds: number): readonly string[] {
1401
+ if (!Array.isArray(value) || value.length < 1 || value.length > maxRunIds) {
1402
+ throw new AgentToolPublicError(
1403
+ `[SixbAgent] wait_agent requires between 1 and ${maxRunIds} child run ids.`
1404
+ )
1405
+ }
1406
+ const runIds = value.map((runId) => requireNonEmpty("wait_agent", runId, "runId"))
1407
+ if (new Set(runIds).size !== runIds.length) {
1408
+ throw new AgentToolPublicError("[SixbAgent] wait_agent run ids must be unique.")
1409
+ }
1410
+ return runIds
1411
+ }
1412
+
1413
+ function requireNonEmpty(
1414
+ toolName: "spawn_agent" | "wait_agent" | "message_agent",
1415
+ value: unknown,
1416
+ field: string,
1417
+ maxLength?: number
1418
+ ): string {
1419
+ if (typeof value !== "string" || value.trim().length === 0) {
1420
+ throw new AgentToolPublicError(`[SixbAgent] ${toolName} ${field} must not be empty.`)
1421
+ }
1422
+ const normalized = value.trim()
1423
+ if (maxLength !== undefined && normalized.length > maxLength) {
1424
+ throw new AgentToolPublicError(
1425
+ `[SixbAgent] ${toolName} ${field} must not exceed ${maxLength} characters.`
1426
+ )
1427
+ }
1428
+ return normalized
1429
+ }
1430
+
1431
+ function requiredExecutionToken(run: ConversationAgentRunRecord): string {
1432
+ if (!run.execution?.token) {
1433
+ throw new Error(`[SixbAgent] Parent Agent run '${run.id}' has no execution token.`)
1434
+ }
1435
+ return run.execution.token
1436
+ }
1437
+
1438
+ function publicSpawnError(error: unknown, key: string, maxActive: number): unknown {
1439
+ if (!(error instanceof AgentStorageError)) return error
1440
+ switch (error.code) {
1441
+ case "active_child_limit":
1442
+ return new AgentToolPublicError(
1443
+ `[SixbAgent] The current Agent run already has ${maxActive} active children. Wait for one before spawning another.`
1444
+ )
1445
+ case "duplicate_id":
1446
+ return new AgentToolPublicError(
1447
+ `[SixbAgent] spawn_agent key '${key}' was already used with different inputs.`
1448
+ )
1449
+ case "invalid_state":
1450
+ return new AgentToolPublicError("[SixbAgent] The parent Agent run is no longer active.")
1451
+ default:
1452
+ return error
1453
+ }
1454
+ }
1455
+
1456
+ /**
1457
+ * When a message came as the child answered (`afterAnswer`), the answer it gave before: kept for
1458
+ * the parent beside the one it wrote after, which may only amend it. If it wrote none after, its
1459
+ * answer is the one before, and the parent is told it predates the message.
1460
+ */
1461
+ function answerBeforeLateMessage(
1462
+ transcript: readonly AgentMessage[],
1463
+ answer: string
1464
+ ): Pick<WaitedSubagentResult, "earlierAnswer" | "answerNote"> {
1465
+ const isLate = (message: AgentMessage) =>
1466
+ message.parts.some((part) => part.type === "mail" && part.afterAnswer === true)
1467
+ const late = transcript.map(isLate).lastIndexOf(true)
1468
+ const before = late > 0 ? transcript[late - 1] : undefined
1469
+ if (before?.role !== "assistant") return {}
1470
+
1471
+ const earlier = answerOfSteps(before.parts)
1472
+ if (!earlier) return {}
1473
+ return earlier === answer
1474
+ ? {
1475
+ answerNote:
1476
+ "It wrote this answer before your last message came, and did not answer again after reading it.",
1477
+ }
1478
+ : { earlierAnswer: earlier }
1479
+ }
1480
+
1481
+ /** The text written after the last local tool call of these steps, as a child's answer is. */
1482
+ function answerOfSteps(parts: readonly AgentMessagePart[]): string {
1483
+ const steps: AgentMessagePart[][] = []
1484
+ for (const part of parts) {
1485
+ if (part.type === "step-start" || steps.length === 0) steps.push([])
1486
+ if (part.type !== "step-start") steps.at(-1)?.push(part)
1487
+ }
1488
+ const ranTools = steps.map((step) =>
1489
+ step.some((part) => part.type === "tool-call" && part.providerExecuted !== true)
1490
+ )
1491
+ return steps
1492
+ .slice(ranTools.lastIndexOf(true) + 1)
1493
+ .flat()
1494
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
1495
+ .join("\n")
1496
+ .trim()
1497
+ }
1498
+
1499
+ function isTerminalSubagent(
1500
+ run: SubagentRunRecord
1501
+ ): run is SubagentRunRecord & { readonly status: "succeeded" | "failed" | "cancelled" } {
1502
+ return run.status !== "queued" && run.status !== "running"
1503
+ }
1504
+
1505
+ interface ChildFiles {
1506
+ readonly files?: readonly InstalledChildFile[]
1507
+ readonly note?: string
1508
+ }
1509
+
1510
+ function waitedResult(
1511
+ run: SubagentRunRecord,
1512
+ awaitingApproval: readonly AgentChildApprovalAwaiting[] | undefined,
1513
+ files: ChildFiles | undefined,
1514
+ question: QuestionRef | undefined
1515
+ ): WaitedSubagentResult {
1516
+ return {
1517
+ runId: run.id,
1518
+ status: isPausedSubagentRun(run)
1519
+ ? "awaiting_approval"
1520
+ : isAwaitingAnswerRun(run)
1521
+ ? "awaiting_answer"
1522
+ : run.status,
1523
+ ...(run.result?.text ? { text: run.result.text } : {}),
1524
+ ...(question === undefined ? {} : { question: { id: question.id, text: question.text } }),
1525
+ ...(run.error === undefined
1526
+ ? {}
1527
+ : { error: { code: run.error.code, message: run.error.message } }),
1528
+ ...(awaitingApproval?.length ? { awaitingApproval } : {}),
1529
+ ...(files?.files?.length
1530
+ ? {
1531
+ files: files.files.map(({ path, sandboxPath, fileRef }) => ({
1532
+ path,
1533
+ sandboxPath,
1534
+ sizeBytes: fileRef.sizeBytes,
1535
+ ...(fileRef.mediaType === undefined ? {} : { mediaType: fileRef.mediaType }),
1536
+ })),
1537
+ }
1538
+ : {}),
1539
+ ...(files?.note === undefined ? {} : { filesNote: files.note }),
1540
+ }
1541
+ }
1542
+
1543
+ /** Whether a spawn under a key in use may be its replay, before reading its files' bytes. */
1544
+ function sameSpecBesidesFiles(
1545
+ existing: SubagentRunSpec,
1546
+ spec: SubagentRunSpec,
1547
+ sources: readonly { readonly path: string; readonly sizeBytes?: number }[]
1548
+ ): boolean {
1549
+ const { files: existingFiles = [], ...existingRest } = existing
1550
+ const { files: _files, ...rest } = spec
1551
+ return (
1552
+ isDeepStrictEqual(existingRest, rest) &&
1553
+ existingFiles.length === sources.length &&
1554
+ existingFiles.every(
1555
+ (file, index) =>
1556
+ file.path === sources[index]?.path &&
1557
+ (sources[index]?.sizeBytes ?? file.fileRef.sizeBytes) === file.fileRef.sizeBytes
1558
+ )
1559
+ )
1560
+ }
1561
+
1562
+ function duplicateKey(key: string): AgentToolPublicError {
1563
+ return new AgentToolPublicError(
1564
+ `[SixbAgent] spawn_agent key '${key}' was already used with different inputs.`
1565
+ )
1566
+ }
1567
+
1568
+ function errorMessage(error: unknown): string {
1569
+ return (error instanceof Error ? error.message : String(error)).replace(/^\[\w+\] /, "")
1570
+ }
1571
+
1572
+ function parseSpawnInput(value: unknown): SpawnSubagentInput {
1573
+ if (
1574
+ !isJsonObject(value) ||
1575
+ Object.keys(value).some(
1576
+ (key) => !["key", "task", "model", "reasoning", "maxSteps", "files"].includes(key)
1577
+ )
1578
+ ) {
1579
+ throw new AgentToolPublicError(
1580
+ "[SixbAgent] spawn_agent expects key, task, and optional model/reasoning/maxSteps/files."
1581
+ )
1582
+ }
1583
+ const key = requireNonEmpty("spawn_agent", value.key, "key", 128)
1584
+ const task = requireNonEmpty("spawn_agent", value.task, "task")
1585
+ let model: LanguageModelRef | LanguageModelTier | undefined
1586
+ if (typeof value.model === "string") {
1587
+ if (!isLanguageModelTier(value.model)) {
1588
+ throw new AgentToolPublicError(
1589
+ `[SixbAgent] Unknown spawn_agent model tier '${value.model}'. Use ${formatLanguageModelTiers()}, or a model reference.`
1590
+ )
1591
+ }
1592
+ model = value.model
1593
+ } else if (value.model !== undefined) {
1594
+ if (
1595
+ !isJsonObject(value.model) ||
1596
+ Object.keys(value.model).some((key) => !["provider", "modelId"].includes(key))
1597
+ ) {
1598
+ throw new AgentToolPublicError("[SixbAgent] spawn_agent model requires provider and modelId.")
1599
+ }
1600
+ model = {
1601
+ provider: requireNonEmpty("spawn_agent", value.model.provider, "model.provider"),
1602
+ modelId: requireNonEmpty("spawn_agent", value.model.modelId, "model.modelId"),
1603
+ }
1604
+ }
1605
+ if (value.reasoning !== undefined && !isModelReasoning(value.reasoning)) {
1606
+ throw new AgentToolPublicError("[SixbAgent] spawn_agent reasoning is invalid.")
1607
+ }
1608
+ if (
1609
+ value.maxSteps !== undefined &&
1610
+ (typeof value.maxSteps !== "number" ||
1611
+ !Number.isSafeInteger(value.maxSteps) ||
1612
+ value.maxSteps < 1)
1613
+ ) {
1614
+ throw new AgentToolPublicError("[SixbAgent] spawn_agent maxSteps must be a positive integer.")
1615
+ }
1616
+ const files = parseSpawnFiles(value.files)
1617
+ return {
1618
+ key,
1619
+ task,
1620
+ ...(model === undefined ? {} : { model }),
1621
+ ...(value.reasoning === undefined ? {} : { reasoning: value.reasoning }),
1622
+ ...(value.maxSteps === undefined ? {} : { maxSteps: value.maxSteps }),
1623
+ ...(files === undefined ? {} : { files }),
1624
+ }
1625
+ }
1626
+
1627
+ function parseSpawnFiles(value: unknown): readonly string[] | undefined {
1628
+ if (value === undefined) return undefined
1629
+
1630
+ const { maxFiles } = SANDBOX_ATTACHMENT_LIMITS
1631
+ if (!Array.isArray(value) || value.length > maxFiles) {
1632
+ throw new AgentToolPublicError(
1633
+ `[SixbAgent] spawn_agent files must be a list of at most ${maxFiles} sandbox paths.`
1634
+ )
1635
+ }
1636
+ const files = value.map((path) => requireNonEmpty("spawn_agent", path, "files entry"))
1637
+ if (new Set(files).size !== files.length) {
1638
+ throw new AgentToolPublicError("[SixbAgent] spawn_agent files must not repeat a path.")
1639
+ }
1640
+ return files.length > 0 ? files : undefined
1641
+ }
1642
+
1643
+ function parseMessageInput(value: unknown): MessageSubagentInput {
1644
+ if (!isJsonObject(value) || Object.keys(value).some((key) => key !== "key" && key !== "text")) {
1645
+ throw new AgentToolPublicError("[SixbAgent] message_agent expects key and text.")
1646
+ }
1647
+ return {
1648
+ key: requireNonEmpty("message_agent", value.key, "key", 128),
1649
+ text: requireNonEmpty("message_agent", value.text, "text"),
1650
+ }
1651
+ }
1652
+
1653
+ function parseWaitInput(value: unknown, maxRunIds: number): WaitForSubagentsInput {
1654
+ if (
1655
+ !isJsonObject(value) ||
1656
+ Object.keys(value).some((key) => key !== "runIds") ||
1657
+ !Array.isArray(value.runIds) ||
1658
+ !value.runIds.every((id) => typeof id === "string")
1659
+ ) {
1660
+ throw new AgentToolPublicError("[SixbAgent] wait_agent expects an array of child run ids.")
1661
+ }
1662
+ return { runIds: normalizeRunIds(value.runIds, maxRunIds) }
1663
+ }
1664
+
1665
+ /** A child that stopped reading as the turn sent to it: it paused or ended just then. */
1666
+ function stoppedReading(error: unknown, key: string): unknown {
1667
+ if (!(error instanceof ChildMailClosedError)) return error
1668
+ return new AgentToolPublicError(
1669
+ `[SixbAgent] '${key}' stopped as you sent this, so it will not read it: it paused or ended. Wait for it with wait_agent to see which.`
1670
+ )
1671
+ }