@providerkit/agents 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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/README.md +2328 -2
  4. package/THIRD_PARTY_NOTICES.md +521 -0
  5. package/dist/a2a/auth.d.ts +10 -0
  6. package/dist/a2a/auth.d.ts.map +1 -0
  7. package/dist/a2a/auth.js +52 -0
  8. package/dist/a2a/auth.js.map +1 -0
  9. package/dist/a2a/client.d.ts +74 -0
  10. package/dist/a2a/client.d.ts.map +1 -0
  11. package/dist/a2a/client.js +601 -0
  12. package/dist/a2a/client.js.map +1 -0
  13. package/dist/a2a/index.d.ts +22 -0
  14. package/dist/a2a/index.d.ts.map +1 -0
  15. package/dist/a2a/index.js +11 -0
  16. package/dist/a2a/index.js.map +1 -0
  17. package/dist/a2a/memory-runs.d.ts +62 -0
  18. package/dist/a2a/memory-runs.d.ts.map +1 -0
  19. package/dist/a2a/memory-runs.js +349 -0
  20. package/dist/a2a/memory-runs.js.map +1 -0
  21. package/dist/a2a/policy.d.ts +15 -0
  22. package/dist/a2a/policy.d.ts.map +1 -0
  23. package/dist/a2a/policy.js +114 -0
  24. package/dist/a2a/policy.js.map +1 -0
  25. package/dist/a2a/push.d.ts +34 -0
  26. package/dist/a2a/push.d.ts.map +1 -0
  27. package/dist/a2a/push.js +180 -0
  28. package/dist/a2a/push.js.map +1 -0
  29. package/dist/a2a/remote.d.ts +155 -0
  30. package/dist/a2a/remote.d.ts.map +1 -0
  31. package/dist/a2a/remote.js +1196 -0
  32. package/dist/a2a/remote.js.map +1 -0
  33. package/dist/a2a/server.d.ts +110 -0
  34. package/dist/a2a/server.d.ts.map +1 -0
  35. package/dist/a2a/server.js +1139 -0
  36. package/dist/a2a/server.js.map +1 -0
  37. package/dist/a2a/signing.d.ts +21 -0
  38. package/dist/a2a/signing.d.ts.map +1 -0
  39. package/dist/a2a/signing.js +305 -0
  40. package/dist/a2a/signing.js.map +1 -0
  41. package/dist/a2a/tasks.d.ts +88 -0
  42. package/dist/a2a/tasks.d.ts.map +1 -0
  43. package/dist/a2a/tasks.js +170 -0
  44. package/dist/a2a/tasks.js.map +1 -0
  45. package/dist/a2a/wire.d.ts +267 -0
  46. package/dist/a2a/wire.d.ts.map +1 -0
  47. package/dist/a2a/wire.js +1202 -0
  48. package/dist/a2a/wire.js.map +1 -0
  49. package/dist/background-types.d.ts +76 -0
  50. package/dist/background-types.d.ts.map +1 -0
  51. package/dist/background-types.js +2 -0
  52. package/dist/background-types.js.map +1 -0
  53. package/dist/child.d.ts +25 -0
  54. package/dist/child.d.ts.map +1 -0
  55. package/dist/child.js +129 -0
  56. package/dist/child.js.map +1 -0
  57. package/dist/code-driver.d.ts +40 -0
  58. package/dist/code-driver.d.ts.map +1 -0
  59. package/dist/code-driver.js +2 -0
  60. package/dist/code-driver.js.map +1 -0
  61. package/dist/code-mode.d.ts +3 -0
  62. package/dist/code-mode.d.ts.map +1 -0
  63. package/dist/code-mode.js +2 -0
  64. package/dist/code-mode.js.map +1 -0
  65. package/dist/code-script.d.ts +3 -0
  66. package/dist/code-script.d.ts.map +1 -0
  67. package/dist/code-script.js +149 -0
  68. package/dist/code-script.js.map +1 -0
  69. package/dist/code.d.ts +75 -0
  70. package/dist/code.d.ts.map +1 -0
  71. package/dist/code.js +326 -0
  72. package/dist/code.js.map +1 -0
  73. package/dist/compaction.d.ts +15 -0
  74. package/dist/compaction.d.ts.map +1 -0
  75. package/dist/compaction.js +168 -0
  76. package/dist/compaction.js.map +1 -0
  77. package/dist/delegation.d.ts +135 -0
  78. package/dist/delegation.d.ts.map +1 -0
  79. package/dist/delegation.js +401 -0
  80. package/dist/delegation.js.map +1 -0
  81. package/dist/evals/driver.d.ts +10 -0
  82. package/dist/evals/driver.d.ts.map +1 -0
  83. package/dist/evals/driver.js +192 -0
  84. package/dist/evals/driver.js.map +1 -0
  85. package/dist/evals/journal.d.ts +26 -0
  86. package/dist/evals/journal.d.ts.map +1 -0
  87. package/dist/evals/journal.js +483 -0
  88. package/dist/evals/journal.js.map +1 -0
  89. package/dist/evals/judge.d.ts +31 -0
  90. package/dist/evals/judge.d.ts.map +1 -0
  91. package/dist/evals/judge.js +142 -0
  92. package/dist/evals/judge.js.map +1 -0
  93. package/dist/evals/report.d.ts +38 -0
  94. package/dist/evals/report.d.ts.map +1 -0
  95. package/dist/evals/report.js +241 -0
  96. package/dist/evals/report.js.map +1 -0
  97. package/dist/evals/runner.d.ts +24 -0
  98. package/dist/evals/runner.d.ts.map +1 -0
  99. package/dist/evals/runner.js +655 -0
  100. package/dist/evals/runner.js.map +1 -0
  101. package/dist/evals/scorers.d.ts +36 -0
  102. package/dist/evals/scorers.d.ts.map +1 -0
  103. package/dist/evals/scorers.js +259 -0
  104. package/dist/evals/scorers.js.map +1 -0
  105. package/dist/evals/simulation.d.ts +7 -0
  106. package/dist/evals/simulation.d.ts.map +1 -0
  107. package/dist/evals/simulation.js +38 -0
  108. package/dist/evals/simulation.js.map +1 -0
  109. package/dist/evals/testing.d.ts +36 -0
  110. package/dist/evals/testing.d.ts.map +1 -0
  111. package/dist/evals/testing.js +87 -0
  112. package/dist/evals/testing.js.map +1 -0
  113. package/dist/evals/trajectory.d.ts +11 -0
  114. package/dist/evals/trajectory.d.ts.map +1 -0
  115. package/dist/evals/trajectory.js +180 -0
  116. package/dist/evals/trajectory.js.map +1 -0
  117. package/dist/evals/types.d.ts +431 -0
  118. package/dist/evals/types.d.ts.map +1 -0
  119. package/dist/evals/types.js +4 -0
  120. package/dist/evals/types.js.map +1 -0
  121. package/dist/evals.d.ts +14 -0
  122. package/dist/evals.d.ts.map +1 -0
  123. package/dist/evals.js +9 -0
  124. package/dist/evals.js.map +1 -0
  125. package/dist/extensions.d.ts +33 -0
  126. package/dist/extensions.d.ts.map +1 -0
  127. package/dist/extensions.js +188 -0
  128. package/dist/extensions.js.map +1 -0
  129. package/dist/handoff.d.ts +58 -0
  130. package/dist/handoff.d.ts.map +1 -0
  131. package/dist/handoff.js +160 -0
  132. package/dist/handoff.js.map +1 -0
  133. package/dist/index.d.ts +19 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +11 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/input.d.ts +42 -0
  138. package/dist/input.d.ts.map +1 -0
  139. package/dist/input.js +266 -0
  140. package/dist/input.js.map +1 -0
  141. package/dist/mcp.d.ts +77 -0
  142. package/dist/mcp.d.ts.map +1 -0
  143. package/dist/mcp.js +505 -0
  144. package/dist/mcp.js.map +1 -0
  145. package/dist/memory-store.d.ts +11 -0
  146. package/dist/memory-store.d.ts.map +1 -0
  147. package/dist/memory-store.js +272 -0
  148. package/dist/memory-store.js.map +1 -0
  149. package/dist/memory.d.ts +212 -0
  150. package/dist/memory.d.ts.map +1 -0
  151. package/dist/memory.js +613 -0
  152. package/dist/memory.js.map +1 -0
  153. package/dist/otel.d.ts +74 -0
  154. package/dist/otel.d.ts.map +1 -0
  155. package/dist/otel.js +427 -0
  156. package/dist/otel.js.map +1 -0
  157. package/dist/progress.d.ts +17 -0
  158. package/dist/progress.d.ts.map +1 -0
  159. package/dist/progress.js +193 -0
  160. package/dist/progress.js.map +1 -0
  161. package/dist/quickjs.d.ts +19 -0
  162. package/dist/quickjs.d.ts.map +1 -0
  163. package/dist/quickjs.js +519 -0
  164. package/dist/quickjs.js.map +1 -0
  165. package/dist/recovery.d.ts +10 -0
  166. package/dist/recovery.d.ts.map +1 -0
  167. package/dist/recovery.js +62 -0
  168. package/dist/recovery.js.map +1 -0
  169. package/dist/request.d.ts +88 -0
  170. package/dist/request.d.ts.map +1 -0
  171. package/dist/request.js +422 -0
  172. package/dist/request.js.map +1 -0
  173. package/dist/run.d.ts +20 -0
  174. package/dist/run.d.ts.map +1 -0
  175. package/dist/run.js +2407 -0
  176. package/dist/run.js.map +1 -0
  177. package/dist/runs.d.ts +110 -0
  178. package/dist/runs.d.ts.map +1 -0
  179. package/dist/runs.js +438 -0
  180. package/dist/runs.js.map +1 -0
  181. package/dist/schema-to-ts.d.ts +4 -0
  182. package/dist/schema-to-ts.d.ts.map +1 -0
  183. package/dist/schema-to-ts.js +191 -0
  184. package/dist/schema-to-ts.js.map +1 -0
  185. package/dist/session.d.ts +23 -0
  186. package/dist/session.d.ts.map +1 -0
  187. package/dist/session.js +137 -0
  188. package/dist/session.js.map +1 -0
  189. package/dist/snapshot.d.ts +75 -0
  190. package/dist/snapshot.d.ts.map +1 -0
  191. package/dist/snapshot.js +1607 -0
  192. package/dist/snapshot.js.map +1 -0
  193. package/dist/steering.d.ts +75 -0
  194. package/dist/steering.d.ts.map +1 -0
  195. package/dist/steering.js +214 -0
  196. package/dist/steering.js.map +1 -0
  197. package/dist/subagents.d.ts +141 -0
  198. package/dist/subagents.d.ts.map +1 -0
  199. package/dist/subagents.js +746 -0
  200. package/dist/subagents.js.map +1 -0
  201. package/dist/tool-retry.d.ts +12 -0
  202. package/dist/tool-retry.d.ts.map +1 -0
  203. package/dist/tool-retry.js +53 -0
  204. package/dist/tool-retry.js.map +1 -0
  205. package/dist/tree.d.ts +98 -0
  206. package/dist/tree.d.ts.map +1 -0
  207. package/dist/tree.js +320 -0
  208. package/dist/tree.js.map +1 -0
  209. package/dist/types.d.ts +1007 -0
  210. package/dist/types.d.ts.map +1 -0
  211. package/dist/types.js +2 -0
  212. package/dist/types.js.map +1 -0
  213. package/dist/workflow-snapshot.d.ts +8 -0
  214. package/dist/workflow-snapshot.d.ts.map +1 -0
  215. package/dist/workflow-snapshot.js +276 -0
  216. package/dist/workflow-snapshot.js.map +1 -0
  217. package/dist/workflow-types.d.ts +171 -0
  218. package/dist/workflow-types.d.ts.map +1 -0
  219. package/dist/workflow-types.js +2 -0
  220. package/dist/workflow-types.js.map +1 -0
  221. package/dist/workflow.d.ts +19 -0
  222. package/dist/workflow.d.ts.map +1 -0
  223. package/dist/workflow.js +1053 -0
  224. package/dist/workflow.js.map +1 -0
  225. package/examples/a2a-remote.ts +85 -0
  226. package/examples/a2a-server.ts +100 -0
  227. package/examples/background.ts +59 -0
  228. package/examples/basic.ts +44 -0
  229. package/examples/code-mode.ts +76 -0
  230. package/examples/conversation.ts +57 -0
  231. package/examples/evals.ts +79 -0
  232. package/examples/guardrails.ts +56 -0
  233. package/examples/handoff.ts +79 -0
  234. package/examples/memory.ts +44 -0
  235. package/examples/otel.ts +99 -0
  236. package/examples/specialists.ts +99 -0
  237. package/examples/steering.ts +69 -0
  238. package/examples/structured-handoff.ts +92 -0
  239. package/examples/subagents.ts +127 -0
  240. package/examples/workflow.ts +74 -0
  241. package/package.json +114 -4
  242. package/src/a2a/auth.ts +62 -0
  243. package/src/a2a/client.ts +733 -0
  244. package/src/a2a/index.ts +74 -0
  245. package/src/a2a/memory-runs.ts +448 -0
  246. package/src/a2a/policy.ts +148 -0
  247. package/src/a2a/push.ts +251 -0
  248. package/src/a2a/remote.ts +1652 -0
  249. package/src/a2a/server.ts +1390 -0
  250. package/src/a2a/signing.ts +348 -0
  251. package/src/a2a/tasks.ts +260 -0
  252. package/src/a2a/wire.ts +1443 -0
  253. package/src/background-types.ts +86 -0
  254. package/src/child.ts +181 -0
  255. package/src/code-driver.ts +48 -0
  256. package/src/code-mode.ts +12 -0
  257. package/src/code-script.ts +149 -0
  258. package/src/code.ts +424 -0
  259. package/src/compaction.ts +212 -0
  260. package/src/delegation.ts +694 -0
  261. package/src/evals/driver.ts +222 -0
  262. package/src/evals/journal.ts +605 -0
  263. package/src/evals/judge.ts +188 -0
  264. package/src/evals/report.ts +295 -0
  265. package/src/evals/runner.ts +826 -0
  266. package/src/evals/scorers.ts +339 -0
  267. package/src/evals/simulation.ts +46 -0
  268. package/src/evals/testing.ts +126 -0
  269. package/src/evals/trajectory.ts +223 -0
  270. package/src/evals/types.ts +463 -0
  271. package/src/evals.ts +72 -0
  272. package/src/extensions.ts +247 -0
  273. package/src/handoff.ts +214 -0
  274. package/src/index.ts +62 -0
  275. package/src/input.ts +319 -0
  276. package/src/mcp.ts +690 -0
  277. package/src/memory-store.ts +366 -0
  278. package/src/memory.ts +893 -0
  279. package/src/otel.ts +568 -0
  280. package/src/progress.ts +214 -0
  281. package/src/quickjs.ts +524 -0
  282. package/src/recovery.ts +90 -0
  283. package/src/request.ts +513 -0
  284. package/src/run.ts +3199 -0
  285. package/src/runs.ts +696 -0
  286. package/src/schema-to-ts.ts +194 -0
  287. package/src/session.ts +178 -0
  288. package/src/snapshot.ts +2099 -0
  289. package/src/steering.ts +329 -0
  290. package/src/subagents.ts +1084 -0
  291. package/src/tool-retry.ts +86 -0
  292. package/src/tree.ts +366 -0
  293. package/src/types.ts +944 -0
  294. package/src/workflow-snapshot.ts +366 -0
  295. package/src/workflow-types.ts +213 -0
  296. package/src/workflow.ts +1316 -0
@@ -0,0 +1,746 @@
1
+ // Adapted from PydanticAI Harness / Vstorm (MIT), sub_agents/_toolset.py and
2
+ // _control.py, and TanStack AI (MIT), first-party/agents.ts. Fork behavior follows Mastra's
3
+ // agent-controller/tools.ts (Apache-2.0). See THIRD_PARTY_NOTICES.md.
4
+ // Changed: versioned host templates, journaled grants, bounded host-selected history and
5
+ // opaque child keys. No detached work, dynamic credentials or second execution loop.
6
+ import { parseToolArgs } from "@providerkit/core";
7
+ import { AGENT_RUNTIME, SUBAGENT_CONTEXT, isDelegation, } from "./delegation.js";
8
+ import { jsonBytes } from "./extensions.js";
9
+ import { conversationOnly, isHandoff } from "./handoff.js";
10
+ import { conversationOf, readInput } from "./input.js";
11
+ import { copyData, childRunId, equalData, immutableCopy, isId, isNames, isRecord, readLimits, readModelSettings, } from "./snapshot.js";
12
+ import { childJournals, fail, Halt, isLocalStop, untilAbort } from "./tree.js";
13
+ const MARK = Symbol("subagent-tool");
14
+ const NAME = /^[A-Za-z0-9_-]{1,64}$/;
15
+ /** UTF-8 JSON bytes for one model-supplied batch or one prepared helper. */
16
+ export const SUBAGENT_SPEC_BYTES = 65_536;
17
+ export function isSubagentTool(tool) {
18
+ return MARK in tool;
19
+ }
20
+ function count(value, zero = false) {
21
+ return Number.isSafeInteger(value) && value >= (zero ? 0 : 1) && value <= 1_024;
22
+ }
23
+ export function subagentLimits(base, lower) {
24
+ if (lower !== undefined &&
25
+ (!isRecord(lower) ||
26
+ Object.keys(lower).some((key) => !Object.hasOwn(base, key)) ||
27
+ Object.entries(lower).some(([key, value]) => {
28
+ const ceiling = Object.entries(base).find(([name]) => name === key)?.[1];
29
+ return typeof value !== "number" || ceiling === undefined || value > ceiling;
30
+ })))
31
+ throw new TypeError("A helper's limits may only lower its host template's limits.");
32
+ return readLimits({ ...base, ...lower });
33
+ }
34
+ export function subagentInstructions(base, instructions) {
35
+ return instructions === undefined
36
+ ? base
37
+ : `${base}\n\nInstructions from the agent that created you:\n${instructions}`;
38
+ }
39
+ function readDraft(raw, host = false) {
40
+ if (!isRecord(raw) ||
41
+ !isId(raw.name) ||
42
+ !NAME.test(raw.name) ||
43
+ !isId(raw.task) ||
44
+ (raw.instructions !== undefined && !isId(raw.instructions)) ||
45
+ (raw.tools !== undefined && !isNames(raw.tools)) ||
46
+ (raw.model !== undefined && (!isId(raw.model) || !NAME.test(raw.model))) ||
47
+ (raw.fork !== undefined && typeof raw.fork !== "boolean") ||
48
+ (raw.continues !== undefined && !isId(raw.continues)) ||
49
+ (raw.continues !== undefined &&
50
+ (raw.fork !== undefined ||
51
+ (!host &&
52
+ [raw.instructions, raw.tools, raw.model].some((value) => value !== undefined)))) ||
53
+ Object.keys(raw).some((key) => ![
54
+ "name",
55
+ "task",
56
+ "instructions",
57
+ "tools",
58
+ "model",
59
+ "fork",
60
+ "continues",
61
+ ...(host ? ["limits"] : []),
62
+ ].includes(key)) ||
63
+ (raw.limits !== undefined && !isRecord(raw.limits)))
64
+ throw new TypeError("Give each helper a unique name (1 to 64 letters, digits, _ or -), a task and only the offered tools and model alias.");
65
+ // Limits are checked by subagentLimits against the actual template before admission.
66
+ const limits = {};
67
+ if (raw.limits !== undefined) {
68
+ for (const key of [
69
+ "turns",
70
+ "toolCalls",
71
+ "elapsedMs",
72
+ "parallelTools",
73
+ "inlineBytes",
74
+ ]) {
75
+ const value = raw.limits[key];
76
+ if (value !== undefined) {
77
+ if (typeof value !== "number")
78
+ throw new TypeError("Helper limits must be numbers.");
79
+ limits[key] = value;
80
+ }
81
+ }
82
+ if (Object.keys(raw.limits).some((key) => !Object.hasOwn(limits, key)))
83
+ throw new TypeError("Use only the template's run limits.");
84
+ }
85
+ return {
86
+ name: raw.name,
87
+ task: raw.task,
88
+ tools: raw.tools === undefined ? [] : [...raw.tools],
89
+ ...(raw.instructions !== undefined ? { instructions: raw.instructions } : {}),
90
+ ...(raw.model !== undefined ? { model: raw.model } : {}),
91
+ ...(raw.fork === true ? { fork: true } : {}),
92
+ ...(raw.continues !== undefined ? { continues: raw.continues } : {}),
93
+ ...(raw.limits !== undefined ? { limits } : {}),
94
+ };
95
+ }
96
+ /** Shape check only; the bound descriptor checks authority and identity during restore. */
97
+ export function isSubagentRecord(value) {
98
+ if (!isRecord(value) ||
99
+ !isRecord(value.identity) ||
100
+ !isId(value.identity.id) ||
101
+ !isId(value.identity.rootRunId) ||
102
+ !isId(value.identity.creatorRunId) ||
103
+ !isId(value.identity.originRunId) ||
104
+ (value.previousRunId !== undefined && !isId(value.previousRunId)) ||
105
+ (value.fork !== undefined &&
106
+ (!isRecord(value.fork) ||
107
+ !Array.isArray(value.fork.indices) ||
108
+ !value.fork.indices.every((index) => Number.isSafeInteger(index) && index >= 0))) ||
109
+ !isId(value.tool) ||
110
+ !isRecord(value.policy) ||
111
+ !isRecord(value.template) ||
112
+ typeof value.policy.maxLevels !== "number" ||
113
+ !count(value.policy.maxLevels) ||
114
+ typeof value.policy.maxPerCall !== "number" ||
115
+ !count(value.policy.maxPerCall) ||
116
+ typeof value.policy.maxPerRun !== "number" ||
117
+ !count(value.policy.maxPerRun, true) ||
118
+ !["none", "all"].includes(String(value.policy.defaultTools)) ||
119
+ !isRecord(value.policy.models) ||
120
+ typeof value.policy.prepare !== "boolean" ||
121
+ typeof value.policy.self !== "boolean" ||
122
+ typeof value.policy.needsApproval !== "boolean" ||
123
+ typeof value.policy.followUp !== "boolean" ||
124
+ (value.policy.fork !== null && !isForkPolicy(value.policy.fork)))
125
+ return false;
126
+ try {
127
+ return (equalData(value.requested, readDraft(value.requested, true)) &&
128
+ equalData(value.spec, readDraft(value.spec, true)) &&
129
+ jsonBytes([value.requested, value.spec]) <= SUBAGENT_SPEC_BYTES * 2 &&
130
+ isRecord(value.base));
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ function isForkPolicy(value) {
137
+ return (isRecord(value) &&
138
+ isId(value.identity) &&
139
+ typeof value.maxMessages === "number" &&
140
+ count(value.maxMessages) &&
141
+ typeof value.maxBytes === "number" &&
142
+ Number.isSafeInteger(value.maxBytes) &&
143
+ value.maxBytes > 0 &&
144
+ value.maxBytes <= 1_000_000);
145
+ }
146
+ function failure(content) {
147
+ return { ok: false, kind: "invalid_input", content };
148
+ }
149
+ export function subagentTool(spec) {
150
+ if (spec.fork !== undefined &&
151
+ (!isForkPolicy(spec.fork) || typeof spec.fork.select !== "function"))
152
+ throw new TypeError("A fork needs a policy identity, a select function, maxMessages from 1 to 1024 and maxBytes from 1 to 1000000.");
153
+ if (!isId(spec.name) ||
154
+ !isId(spec.description) ||
155
+ (spec.agent !== "self" && !spec.agent?.[AGENT_RUNTIME]) ||
156
+ (spec.defaultTools !== undefined && !["none", "all"].includes(spec.defaultTools)) ||
157
+ (spec.prepare !== undefined && typeof spec.prepare !== "function") ||
158
+ (spec.summarize !== undefined && typeof spec.summarize !== "function") ||
159
+ (spec.needsApproval !== undefined && typeof spec.needsApproval !== "boolean") ||
160
+ (spec.followUp !== undefined && typeof spec.followUp !== "boolean") ||
161
+ (spec.models !== undefined && !isRecord(spec.models)))
162
+ throw new TypeError("A subagent tool needs a name, description and a host agent or self.");
163
+ const models = Object.fromEntries(Object.entries(spec.models ?? {}).map(([alias, choice]) => {
164
+ if (!NAME.test(alias) || !isRecord(choice) || !isId(choice.description))
165
+ throw new TypeError("Each model alias needs a short name and a description.");
166
+ const settings = readModelSettings(choice.settings);
167
+ if ([settings.hostedTools, settings.toolChoice, settings.onActivity, settings.onRateLimit].some((value) => value !== undefined))
168
+ throw new TypeError("Model choices cannot change hosted tools, tool choice or callbacks.");
169
+ return [alias, { description: choice.description, settings }];
170
+ }));
171
+ const policy = immutableCopy({
172
+ models,
173
+ defaultTools: spec.defaultTools ?? "none",
174
+ maxLevels: spec.maxLevels ?? 1,
175
+ maxPerCall: spec.maxPerCall ?? 4,
176
+ maxPerRun: spec.maxPerRun ?? 8,
177
+ needsApproval: spec.needsApproval ?? false,
178
+ prepare: !!spec.prepare,
179
+ self: spec.agent === "self",
180
+ fork: spec.fork
181
+ ? {
182
+ identity: spec.fork.identity,
183
+ maxMessages: spec.fork.maxMessages,
184
+ maxBytes: spec.fork.maxBytes,
185
+ }
186
+ : null,
187
+ followUp: spec.followUp ?? false,
188
+ });
189
+ if (!count(policy.maxLevels) || !count(policy.maxPerCall) || !count(policy.maxPerRun, true))
190
+ throw new TypeError("Helper counts must be whole numbers up to 1024; only maxPerRun may be 0.");
191
+ const { name, description, prepare, summarize } = spec;
192
+ const selectFork = spec.fork?.select;
193
+ const target = spec.agent;
194
+ const descriptor = Object.freeze({
195
+ [MARK]: true,
196
+ kind: "delegation",
197
+ name,
198
+ needsApproval: policy.needsApproval,
199
+ specialists: target === "self" ? [] : [target],
200
+ definition() {
201
+ throw new TypeError("Register subagentTool on an agent before reading its definition.");
202
+ },
203
+ async execute() {
204
+ throw new TypeError("Start model-created helpers through their registered agent.");
205
+ },
206
+ bind(holder) {
207
+ const template = () => (target === "self" ? holder() : target);
208
+ function grantable() {
209
+ const owner = holder()[AGENT_RUNTIME];
210
+ const worker = template()[AGENT_RUNTIME];
211
+ // TanStack filters the starting turn's tools. Match objects too: an identically named
212
+ // tool with a different implementation is not the same capability.
213
+ return worker.tools.filter((tool) => owner.tools.includes(tool) &&
214
+ (owner.enabledTools === undefined || owner.enabledTools.includes(tool.name)) &&
215
+ (worker.enabledTools === undefined || worker.enabledTools.includes(tool.name)) &&
216
+ !isHandoff(tool) &&
217
+ (!isDelegation(tool) || (tool === descriptor && policy.maxLevels > 1)));
218
+ }
219
+ function allowed(parent) {
220
+ return grantable()
221
+ .map((tool) => tool.name)
222
+ .filter((name) => parent.definition.enabledTools.includes(name));
223
+ }
224
+ function drafts(raw, parent) {
225
+ if (jsonBytes(raw) > SUBAGENT_SPEC_BYTES)
226
+ throw new TypeError(`The helper definitions exceed ${SUBAGENT_SPEC_BYTES} UTF-8 JSON bytes. Send less text.`);
227
+ if (!isRecord(raw) ||
228
+ Object.keys(raw).length !== 1 ||
229
+ !Array.isArray(raw.agents) ||
230
+ raw.agents.length < 1 ||
231
+ raw.agents.length > policy.maxPerCall)
232
+ throw new TypeError(`Pass agents with 1 to ${policy.maxPerCall} helper definitions.`);
233
+ const available = allowed(parent);
234
+ const result = raw.agents.map((raw) => {
235
+ const draft = readDraft(raw);
236
+ if (draft.fork && !policy.fork)
237
+ throw new TypeError("The host has not allowed history forks. Send only a task.");
238
+ if (draft.continues && !policy.followUp)
239
+ throw new TypeError("The host has not allowed follow-ups. Start a new helper.");
240
+ if (!draft.continues &&
241
+ isRecord(raw) &&
242
+ raw.tools === undefined &&
243
+ policy.defaultTools === "all")
244
+ draft.tools = [...available];
245
+ if (draft.tools.some((tool) => !available.includes(tool)))
246
+ throw new TypeError("A helper may use only tools enabled on its creator and offered by its host template.");
247
+ if (draft.model !== undefined && !Object.hasOwn(models, draft.model))
248
+ throw new TypeError("Choose a model alias from the host's menu, or omit model.");
249
+ draft.tools = available.filter((name) => draft.tools.includes(name));
250
+ return draft;
251
+ });
252
+ if (new Set(result.map((draft) => draft.name)).size !== result.length)
253
+ throw new TypeError("Use a different name for each helper in this call.");
254
+ const targets = result.flatMap((draft) => (draft.continues ? [draft.continues] : []));
255
+ if (new Set(targets).size !== targets.length)
256
+ throw new TypeError("Send only one follow-up per helper in a call. Wait for it to finish before sending another.");
257
+ return result;
258
+ }
259
+ function nodes(parent, before) {
260
+ const ordered = parent.models.flatMap((model) => model.status === "completed"
261
+ ? model.tools.flatMap((tool) => {
262
+ const entry = parent.delegations.find((entry) => entry.operationId === tool.id);
263
+ return entry ? [entry] : [];
264
+ })
265
+ : []);
266
+ const entries = before ? ordered.slice(0, ordered.indexOf(before)) : ordered;
267
+ return entries.flatMap((entry) => entry.children.flatMap((child) => child.snapshot.kind === "agent" && child.snapshot.subagent?.tool === name
268
+ ? [child.snapshot]
269
+ : []));
270
+ }
271
+ function records(parent) {
272
+ return nodes(parent).flatMap((node) => (node.subagent ? [node.subagent] : []));
273
+ }
274
+ function previous(parent, journal, requested) {
275
+ const node = nodes(parent, journal)
276
+ .reverse()
277
+ .find((node) => node.subagent?.identity.id === requested.continues);
278
+ if (!node?.subagent ||
279
+ node.subagent.spec.name !== requested.name ||
280
+ node.subagent.identity.creatorRunId !== parent.runId ||
281
+ node.subagent.identity.rootRunId !== parent.tree.runId)
282
+ throw new TypeError("Use the helperId and name returned by this tool in this run. Other helpers cannot be continued here.");
283
+ if (!equalData(node.subagent.policy, policy) ||
284
+ !equalData(node.subagent.template, template()[AGENT_RUNTIME].configuration()))
285
+ throw new TypeError("The helper's host template changed. Restore its admitted configuration before continuing.");
286
+ if (node.state.status !== "completed" ||
287
+ node.models.some((model) => model.status !== "completed" ||
288
+ model.tools.some((tool) => tool.status !== "completed")))
289
+ throw new TypeError("This helper has unfinished or uncertain work. Resolve its requests or reconcile it on the host before continuing.");
290
+ return node;
291
+ }
292
+ function followupSpec(prior, task, helperId) {
293
+ const { fork: _fork, ...original } = prior.spec;
294
+ return { ...original, task, continues: helperId };
295
+ }
296
+ function forkHistory(parent, journal, indices) {
297
+ const bound = policy.fork;
298
+ const position = parent.models.findIndex((model) => model.status === "completed" &&
299
+ model.tools.some((tool) => tool.id === journal.operationId));
300
+ const source = conversationOnly(conversationOf(parent, position));
301
+ if (!bound ||
302
+ position < 0 ||
303
+ !Array.isArray(indices) ||
304
+ indices.length > bound.maxMessages ||
305
+ indices.some((index, i) => !Number.isSafeInteger(index) ||
306
+ index < 0 ||
307
+ index >= source.length ||
308
+ index <= (indices[i - 1] ?? -1)))
309
+ throw new TypeError("The fork must select an ordered subset within the host's message limit.");
310
+ const history = indices.flatMap((index) => (source[index] ? [source[index]] : []));
311
+ if (jsonBytes(history) > bound.maxBytes)
312
+ throw new TypeError("The selected fork history exceeds the host's byte limit. Select fewer messages.");
313
+ return history;
314
+ }
315
+ function check(parent, journal) {
316
+ const runtime = template()[AGENT_RUNTIME];
317
+ const model = parent.models.find((model) => model.status === "completed" &&
318
+ model.tools.some((tool) => tool.id === journal.operationId));
319
+ const position = model?.status === "completed"
320
+ ? model.tools.findIndex((tool) => tool.id === journal.operationId)
321
+ : -1;
322
+ const execution = model?.status === "completed" ? model.tools[position] : undefined;
323
+ const call = model?.status === "completed" ? model.turn.message.toolCalls?.[position] : undefined;
324
+ if (!call || !execution || journal.kind !== "delegation")
325
+ throw new TypeError("Missing helper creation call.");
326
+ // An expired approval may have edited the original call. Its admission remains pinned;
327
+ // a later edit is checked again by execute, never used to redefine an admitted child.
328
+ const sources = [
329
+ parseToolArgs(call.arguments),
330
+ ...(execution.asks ?? []).flatMap((ask) => ask.decision?.type === "approve" && ask.decision.arguments !== undefined
331
+ ? [ask.decision.arguments]
332
+ : []),
333
+ ];
334
+ const candidates = sources.flatMap((raw) => {
335
+ try {
336
+ return [drafts(raw, parent)];
337
+ }
338
+ catch {
339
+ return [];
340
+ }
341
+ });
342
+ for (const child of journal.children) {
343
+ if (child.snapshot.kind !== "agent")
344
+ throw new TypeError("A generated helper must be an agent.");
345
+ const index = Number(child.key.slice("helper-".length)) - 1;
346
+ const record = child.snapshot.subagent;
347
+ if (!record ||
348
+ !Number.isSafeInteger(index) ||
349
+ index < 0 ||
350
+ index >= policy.maxPerCall ||
351
+ child.key !== `helper-${index + 1}` ||
352
+ record.tool !== name ||
353
+ !equalData(record.policy, policy) ||
354
+ !equalData(record.template, runtime.configuration()) ||
355
+ !candidates.some((items) => equalData(items[index], record.requested)))
356
+ throw new TypeError("The saved helper definition or capabilities changed. Restore its host configuration before resuming.");
357
+ const prior = record.requested.continues
358
+ ? previous(parent, journal, record.requested)
359
+ : undefined;
360
+ if (record.identity.rootRunId !== parent.tree.runId ||
361
+ record.identity.creatorRunId !== parent.runId ||
362
+ (prior
363
+ ? !equalData(record.identity, prior.subagent?.identity) ||
364
+ record.previousRunId !== prior.runId
365
+ : record.previousRunId !== undefined ||
366
+ record.identity.originRunId !== child.snapshot.runId))
367
+ throw new TypeError("The helper identity does not belong to this creator or conversation.");
368
+ let history = [];
369
+ if (prior?.subagent) {
370
+ if (!policy.followUp ||
371
+ jsonBytes(record.spec) > SUBAGENT_SPEC_BYTES ||
372
+ record.fork ||
373
+ !equalData(record.spec, followupSpec(prior.subagent, record.spec.task, prior.subagent.identity.id)) ||
374
+ !equalData(record.base, prior.subagent.base))
375
+ throw new TypeError("A follow-up must keep its helper's admitted definition.");
376
+ // Only the new task may be rewritten by host admission policy.
377
+ checkPrepared(record.requested, { ...record.requested, task: record.spec.task }, parent);
378
+ history = conversationOf(prior);
379
+ }
380
+ else {
381
+ checkPrepared(record.requested, record.spec, parent);
382
+ if (record.spec.fork) {
383
+ if (!record.fork)
384
+ throw new TypeError("Missing admitted fork history.");
385
+ history = forkHistory(parent, journal, record.fork.indices);
386
+ }
387
+ else if (record.fork)
388
+ throw new TypeError("A task-only helper cannot carry fork history.");
389
+ }
390
+ // Child creation repairs reused tool-call ids. Compare the same canonical input,
391
+ // not the predecessor's unchanged journal.
392
+ const start = runtime.freeze(readInput({ messages: [...history, { role: "user", content: record.spec.task }] }, "trusted"));
393
+ if (record.spec.tools.some((name) => !allowed(parent).includes(name)))
394
+ throw new TypeError("The helper's tools are no longer granted by its creator.");
395
+ const expectedNames = runtime.tools
396
+ .map((tool) => tool.name)
397
+ .filter((name) => record.spec.tools.includes(name));
398
+ if (runtime.configuration().output !== null)
399
+ expectedNames.push("submit_result");
400
+ const baseSettings = policy.self
401
+ ? parent.definition.modelSettings
402
+ : runtime.configuration().modelSettings;
403
+ const expectedSettings = {
404
+ ...readModelSettings(baseSettings),
405
+ ...models[record.spec.model ?? ""]?.settings,
406
+ };
407
+ const baseInstructions = policy.self
408
+ ? parent.definition.instructions
409
+ : runtime.configuration().instructions;
410
+ if (child.snapshot.agentId !== template().id ||
411
+ child.snapshot.version !== template().version ||
412
+ child.snapshot.session !== undefined ||
413
+ !equalData(child.snapshot.history, start.history) ||
414
+ child.snapshot.input !== start.input ||
415
+ !equalData(child.snapshot.limits, subagentLimits(runtime.limits, record.spec.limits)) ||
416
+ !equalData(record.base.enabledTools, expectedNames) ||
417
+ !equalData(record.base.modelSettings, expectedSettings) ||
418
+ (typeof baseInstructions === "string" &&
419
+ record.base.instructions !== baseInstructions) ||
420
+ !equalData(child.snapshot.definition, {
421
+ ...record.base,
422
+ instructions: subagentInstructions(record.base.instructions, record.spec.instructions),
423
+ }))
424
+ throw new TypeError("The saved helper no longer matches its admitted task, tools or definition.");
425
+ }
426
+ const admitted = records(parent);
427
+ const origins = admitted.filter((record) => !record.previousRunId);
428
+ if (admitted.length > policy.maxPerRun ||
429
+ new Set(origins.map((record) => record.spec.name)).size !== origins.length ||
430
+ new Set(origins.map((record) => record.identity.id)).size !== origins.length)
431
+ throw new TypeError("The saved helpers exceed this tool's per-run limit or reuse a name.");
432
+ }
433
+ function checkPrepared(requested, prepared, parent) {
434
+ if ((!prepare && !equalData(requested, prepared)) ||
435
+ jsonBytes(prepared) > SUBAGENT_SPEC_BYTES ||
436
+ prepared.name !== requested.name ||
437
+ prepared.model !== requested.model ||
438
+ prepared.fork !== requested.fork ||
439
+ prepared.continues !== requested.continues ||
440
+ (requested.continues !== undefined &&
441
+ !equalData({ ...prepared, task: requested.task }, requested)) ||
442
+ prepared.tools.some((name) => !requested.tools.includes(name) || !allowed(parent).includes(name)))
443
+ throw new TypeError("Admission policy may narrow tools and limits, not change identity or grant capabilities.");
444
+ subagentLimits(template()[AGENT_RUNTIME].limits, prepared.limits);
445
+ }
446
+ async function prepareDraft(requested, parent, context) {
447
+ try {
448
+ const prepared = prepare
449
+ ? await untilAbort(Promise.resolve(prepare(immutableCopy(requested), Object.freeze(context))), context.signal)
450
+ : requested;
451
+ context.signal.throwIfAborted();
452
+ if (isRecord(prepared) && isId(prepared.refuse)) {
453
+ if (jsonBytes(prepared.refuse) > SUBAGENT_SPEC_BYTES)
454
+ throw new TypeError("The admission refusal is too large.");
455
+ return { refuse: prepared.refuse };
456
+ }
457
+ const admitted = readDraft(prepared, true);
458
+ checkPrepared(requested, admitted, parent);
459
+ admitted.tools = allowed(parent).filter((name) => admitted.tools.includes(name));
460
+ return admitted;
461
+ }
462
+ catch {
463
+ context.signal.throwIfAborted();
464
+ fail("subagent_policy_failed", "The helper admission policy failed or tried to grant capabilities. Check the host policy before starting new work.");
465
+ }
466
+ }
467
+ return Object.freeze({
468
+ [MARK]: true,
469
+ kind: "delegation",
470
+ name,
471
+ needsApproval: policy.needsApproval,
472
+ get specialists() {
473
+ return [template()];
474
+ },
475
+ definition() {
476
+ const aliases = Object.keys(models);
477
+ const grants = grantable().map((tool) => tool.name);
478
+ return {
479
+ name,
480
+ description,
481
+ inputSchema: {
482
+ type: "object",
483
+ properties: {
484
+ agents: {
485
+ type: "array",
486
+ minItems: 1,
487
+ maxItems: policy.maxPerCall,
488
+ items: {
489
+ type: "object",
490
+ properties: {
491
+ name: {
492
+ type: "string",
493
+ description: "Private name: 1 to 64 letters, digits, _ or -.",
494
+ },
495
+ task: { type: "string" },
496
+ instructions: { type: "string" },
497
+ ...(policy.fork
498
+ ? {
499
+ fork: {
500
+ type: "boolean",
501
+ description: "Ask the host to share approved earlier messages.",
502
+ },
503
+ }
504
+ : {}),
505
+ ...(policy.followUp
506
+ ? {
507
+ continues: {
508
+ type: "string",
509
+ description: "The helperId returned by this tool. Pass only name, task and continues for a follow-up.",
510
+ },
511
+ }
512
+ : {}),
513
+ tools: {
514
+ type: "array",
515
+ items: { type: "string", ...(grants.length ? { enum: grants } : {}) },
516
+ ...(grants.length ? {} : { maxItems: 0 }),
517
+ uniqueItems: true,
518
+ },
519
+ ...(aliases.length
520
+ ? {
521
+ model: {
522
+ type: "string",
523
+ enum: aliases,
524
+ description: aliases
525
+ .map((alias) => `${alias}: ${models[alias]?.description}`)
526
+ .join("\n"),
527
+ },
528
+ }
529
+ : {}),
530
+ },
531
+ required: ["name", "task"],
532
+ additionalProperties: false,
533
+ },
534
+ },
535
+ },
536
+ required: ["agents"],
537
+ additionalProperties: false,
538
+ },
539
+ };
540
+ },
541
+ check,
542
+ async execute(raw, context) {
543
+ const internal = context[SUBAGENT_CONTEXT];
544
+ if (!internal)
545
+ throw new TypeError("Helper creation needs a journaled delegation context.");
546
+ const { parent, journal, scope, request, signal } = internal;
547
+ let items;
548
+ try {
549
+ items = drafts(raw, parent);
550
+ }
551
+ catch (error) {
552
+ if (journal.children.length)
553
+ fail("subagent_input_changed", "An admitted helper's definition cannot change. Reconcile the saved run before starting different work.");
554
+ return failure(error instanceof Error ? error.message : "Invalid helper definitions.");
555
+ }
556
+ check(parent, journal);
557
+ for (const child of journal.children)
558
+ if (!equalData(child.snapshot.kind === "agent" ? child.snapshot.subagent?.requested : undefined, items[Number(child.key.slice("helper-".length)) - 1]))
559
+ fail("subagent_input_changed", "An admitted helper's definition cannot change. Reconcile the saved run before starting different work.");
560
+ const ancestors = scope.path.reduce((nodes, step) => {
561
+ const parent = nodes.at(-1);
562
+ const node = parent &&
563
+ childJournals(parent)
564
+ .find((entry) => entry.operationId === step.operationId)
565
+ ?.children.find((child) => child.key === step.key)?.snapshot;
566
+ if (!node)
567
+ throw new TypeError("Missing helper ancestor in the execution tree.");
568
+ nodes.push(node);
569
+ return nodes;
570
+ }, [scope.tree.root]);
571
+ const created = ancestors.flatMap((node) => node.kind === "agent" && node.subagent ? [node.subagent] : []);
572
+ const level = created.length + 1;
573
+ if (level > Math.min(policy.maxLevels, ...created.map((record) => record.policy.maxLevels)))
574
+ return failure("Recursive helper creation is not allowed here. Complete the task with the tools you have.");
575
+ const existing = records(parent);
576
+ const remaining = Math.min(policy.maxPerRun - existing.length, scope.tree.childRoom(scope.depth + 1));
577
+ if (items.length - journal.children.length > remaining)
578
+ return failure(`There is room for ${Math.max(0, remaining)} more helpers. Request fewer helpers or do the work here.`);
579
+ const continuations = new Map();
580
+ try {
581
+ for (const item of items)
582
+ if (item.continues)
583
+ continuations.set(item.continues, previous(parent, journal, item));
584
+ }
585
+ catch (error) {
586
+ if (journal.children.length)
587
+ throw error;
588
+ return failure(error instanceof Error ? error.message : "Invalid helper follow-up.");
589
+ }
590
+ if (items.some((item, index) => !item.continues &&
591
+ !journal.children.some((child) => child.key === `helper-${index + 1}`) &&
592
+ existing.some((record) => record.spec.name === item.name)))
593
+ return failure("A helper with that name already exists in this run. Use a new name.");
594
+ const handles = [];
595
+ const results = [];
596
+ for (const [index, requested] of items.entries()) {
597
+ const key = `helper-${index + 1}`;
598
+ const saved = journal.children.find((child) => child.key === key);
599
+ const prior = requested.continues ? continuations.get(requested.continues) : undefined;
600
+ const admissionContext = {
601
+ call: immutableCopy(request),
602
+ depth: scope.depth + 1,
603
+ level,
604
+ grantable: Object.freeze(allowed(parent)),
605
+ signal,
606
+ };
607
+ if (saved && saved.snapshot.kind !== "agent")
608
+ throw new TypeError("A generated helper must be an agent.");
609
+ const savedHelper = saved?.snapshot.kind === "agent" ? saved.snapshot.subagent : undefined;
610
+ let admitted = savedHelper?.spec;
611
+ if (!admitted) {
612
+ const prepared = await prepareDraft(requested, parent, admissionContext);
613
+ if ("refuse" in prepared) {
614
+ results.push({ name: requested.name, status: "refused", error: prepared.refuse });
615
+ continue;
616
+ }
617
+ admitted = prior?.subagent
618
+ ? followupSpec(prior.subagent, prepared.task, prior.subagent.identity.id)
619
+ : prepared;
620
+ }
621
+ if (jsonBytes(admitted) > SUBAGENT_SPEC_BYTES)
622
+ fail("subagent_spec_limit", `The helper's saved definition and new task exceed ${SUBAGENT_SPEC_BYTES} UTF-8 JSON bytes. Send a shorter task.`);
623
+ let fork = savedHelper?.fork;
624
+ let history = prior ? conversationOf(prior) : [];
625
+ if (admitted.fork) {
626
+ if (!fork) {
627
+ if (!selectFork)
628
+ throw new TypeError("Missing host fork policy.");
629
+ try {
630
+ const selected = await untilAbort(Promise.resolve(selectFork(immutableCopy(conversationOnly(context.conversation)), Object.freeze(admissionContext))), signal);
631
+ history = forkHistory(parent, journal, selected);
632
+ fork = { indices: [...selected] };
633
+ }
634
+ catch {
635
+ signal.throwIfAborted();
636
+ fail("subagent_policy_failed", "The fork policy failed or exceeded its limits. Check the host's history filter before trying again.");
637
+ }
638
+ }
639
+ else
640
+ history = forkHistory(parent, journal, fork.indices);
641
+ }
642
+ // New history use is an authority boundary, not permission inferred from prose.
643
+ // Also recheck on replay before an unfinished child can continue.
644
+ if (admitted.fork || prior) {
645
+ await internal.recheck(holder(), parent);
646
+ if (prior)
647
+ await internal.recheck(template(), prior);
648
+ }
649
+ const identity = savedHelper?.identity ??
650
+ prior?.subagent?.identity ?? {
651
+ id: crypto.randomUUID(),
652
+ rootRunId: parent.tree.runId,
653
+ creatorRunId: parent.runId,
654
+ originRunId: childRunId(journal.operationId, key),
655
+ };
656
+ const creation = {
657
+ record: {
658
+ identity,
659
+ ...(prior ? { previousRunId: prior.runId } : {}),
660
+ ...(fork ? { fork } : {}),
661
+ tool: name,
662
+ requested,
663
+ spec: admitted,
664
+ policy,
665
+ template: template()[AGENT_RUNTIME].configuration(),
666
+ },
667
+ ...(prior?.subagent
668
+ ? { source: prior.subagent.base }
669
+ : policy.self
670
+ ? { source: parent.definition }
671
+ : {}),
672
+ };
673
+ const child = internal.child(key, template(), { messages: [...history, { role: "user", content: admitted.task }] }, creation);
674
+ handles.push({ index: results.length, child });
675
+ results.push({
676
+ name: requested.name,
677
+ helperId: identity.id,
678
+ runId: child.runId,
679
+ status: "failed",
680
+ error: "The helper has not finished.",
681
+ });
682
+ }
683
+ const settled = await context.join(handles.map(({ child }) => child));
684
+ for (const [index, outcome] of settled.entries()) {
685
+ const slot = handles[index]?.index;
686
+ if (slot === undefined)
687
+ throw new Error("Missing helper result position.");
688
+ const previous = results[slot];
689
+ if (!previous || previous.status === "refused")
690
+ throw new Error("Missing helper result.");
691
+ if (outcome.status === "completed") {
692
+ // Each template's runtime has already checked its own output contract.
693
+ if (outcome.snapshot.state.status !== "completed")
694
+ throw new Error("Invalid helper outcome.");
695
+ results[slot] = {
696
+ name: previous.name,
697
+ helperId: previous.helperId,
698
+ runId: outcome.runId,
699
+ status: "completed",
700
+ output: outcome.snapshot.state.candidate,
701
+ };
702
+ }
703
+ else {
704
+ const state = outcome.snapshot.state;
705
+ if (!isLocalStop(state)) {
706
+ if (state.status === "running" || state.status === "completed")
707
+ throw new Error("Invalid helper outcome.");
708
+ throw new Halt(state);
709
+ }
710
+ results[slot] = {
711
+ name: previous.name,
712
+ helperId: previous.helperId,
713
+ runId: outcome.runId,
714
+ status: "failed",
715
+ error: "The helper could not finish within its limits or returned a model or result failure. Continue with the other results.",
716
+ };
717
+ }
718
+ }
719
+ const content = summarize ? summarize(immutableCopy(results)) : JSON.stringify(results);
720
+ if (typeof content !== "string")
721
+ throw new TypeError("A helper summary must be text.");
722
+ return results.some((result) => result.status === "completed")
723
+ ? { ok: true, content, output: copyData(results) }
724
+ : {
725
+ ok: false,
726
+ kind: results.every((result) => result.status === "refused") ? "denied" : "failed",
727
+ content,
728
+ };
729
+ },
730
+ });
731
+ },
732
+ });
733
+ return descriptor;
734
+ }
735
+ /** @internal Bind per holder; a reusable self descriptor must not capture another agent. */
736
+ export function bindSubagentTool(tool, holder) {
737
+ return isSubagentTool(tool) ? tool.bind(holder) : tool;
738
+ }
739
+ /** @internal Called before any host resume callback, including for completed children. */
740
+ export function checkSubagentChildren(descriptor, parent, journal) {
741
+ if (MARK in descriptor && "check" in descriptor && typeof descriptor.check === "function")
742
+ descriptor.check(parent, journal);
743
+ else if (journal.children.some((child) => child.snapshot.kind === "agent" && child.snapshot.subagent))
744
+ throw new TypeError("A model-created helper must belong to its registered creation tool.");
745
+ }
746
+ //# sourceMappingURL=subagents.js.map