@myagentroam/agent 0.11.32 → 0.11.34

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 (856) hide show
  1. package/dist/cli/catalog-file.d.ts +78 -0
  2. package/dist/cli/catalog-file.js +102 -0
  3. package/dist/cli/codex-auth-file.d.ts +1 -1
  4. package/dist/cli/codex-auth-file.js +9 -10
  5. package/dist/cli/main.js +44 -54
  6. package/dist/error.d.ts +15 -0
  7. package/dist/error.js +74 -0
  8. package/dist/extensions/agents.d.ts +100 -0
  9. package/dist/extensions/agents.js +121 -0
  10. package/dist/extensions/capabilities.d.ts +4 -0
  11. package/dist/extensions/commands.d.ts +23 -0
  12. package/dist/extensions/commands.js +45 -0
  13. package/dist/extensions/compaction.d.ts +36 -0
  14. package/dist/extensions/contracts.d.ts +147 -0
  15. package/dist/extensions/data.d.ts +81 -0
  16. package/dist/extensions/data.js +78 -0
  17. package/dist/extensions/environment.d.ts +39 -0
  18. package/dist/extensions/environment.js +52 -0
  19. package/dist/extensions/files.d.ts +68 -0
  20. package/dist/extensions/files.js +26 -0
  21. package/dist/extensions/hooks.d.ts +32 -0
  22. package/dist/extensions/host-ports.d.ts +24 -0
  23. package/dist/extensions/manager.d.ts +42 -0
  24. package/dist/extensions/manager.js +457 -0
  25. package/dist/extensions/mcp.d.ts +116 -0
  26. package/dist/extensions/mcp.js +434 -0
  27. package/dist/extensions/model-request.d.ts +65 -0
  28. package/dist/extensions/model-request.js +197 -0
  29. package/dist/extensions/model-stream.d.ts +18 -0
  30. package/dist/extensions/model-stream.js +108 -0
  31. package/dist/extensions/models.d.ts +46 -0
  32. package/dist/extensions/models.js +7 -0
  33. package/dist/extensions/network.d.ts +40 -0
  34. package/dist/extensions/network.js +97 -0
  35. package/dist/extensions/operation.d.ts +32 -0
  36. package/dist/extensions/processes.d.ts +64 -0
  37. package/dist/extensions/processes.js +284 -0
  38. package/dist/extensions/prompt-composition.d.ts +38 -0
  39. package/dist/extensions/prompt-composition.js +100 -0
  40. package/dist/extensions/prompt-input.d.ts +30 -0
  41. package/dist/extensions/prompt-input.js +48 -0
  42. package/dist/extensions/prompts.d.ts +31 -0
  43. package/dist/extensions/prompts.js +88 -0
  44. package/dist/extensions/resources.d.ts +26 -0
  45. package/dist/extensions/resources.js +221 -0
  46. package/dist/extensions/services.d.ts +31 -0
  47. package/dist/extensions/services.js +61 -0
  48. package/dist/extensions/session-api.d.ts +6 -0
  49. package/dist/extensions/session-api.js +52 -0
  50. package/dist/extensions/session-input.d.ts +184 -0
  51. package/dist/extensions/session-input.js +422 -0
  52. package/dist/extensions/session-messages.d.ts +41 -0
  53. package/dist/extensions/session-messages.js +76 -0
  54. package/dist/extensions/session-tools.d.ts +32 -0
  55. package/dist/extensions/session-tools.js +208 -0
  56. package/dist/extensions/session.d.ts +60 -0
  57. package/dist/extensions/session.js +265 -0
  58. package/dist/extensions/settings.d.ts +76 -0
  59. package/dist/extensions/settings.js +115 -0
  60. package/dist/extensions/store.d.ts +10 -0
  61. package/dist/extensions/store.js +131 -0
  62. package/dist/extensions/tool-runtime.d.ts +16 -0
  63. package/dist/extensions/tools.d.ts +80 -0
  64. package/dist/extensions/tools.js +270 -0
  65. package/dist/extensions.d.ts +22 -0
  66. package/dist/host/contracts.d.ts +58 -0
  67. package/dist/host/contracts.js +18 -0
  68. package/dist/host/description.d.ts +19 -0
  69. package/dist/host/local-agent-host.d.ts +96 -0
  70. package/dist/host/local-agent-host.js +429 -0
  71. package/dist/host/local-exec-tool.d.ts +26 -0
  72. package/dist/host/local-exec-tool.js +686 -0
  73. package/dist/host/local-file-access.d.ts +30 -0
  74. package/dist/host/local-file-access.js +107 -0
  75. package/dist/host/local-network-access.d.ts +6 -0
  76. package/dist/host/local-network-access.js +101 -0
  77. package/dist/host/local-process-executor.d.ts +5 -0
  78. package/dist/host/local-process-executor.js +17 -0
  79. package/dist/host/local-session-environment.d.ts +18 -0
  80. package/dist/host/local-shell.d.ts +3 -0
  81. package/dist/host/local-tool-registry.d.ts +34 -0
  82. package/dist/host/local-tool-registry.js +134 -0
  83. package/dist/host/network.d.ts +5 -0
  84. package/dist/host/network.js +42 -0
  85. package/dist/host/process-control.d.ts +2 -0
  86. package/dist/host/process-control.js +26 -0
  87. package/dist/host/skill-contract.d.ts +6 -0
  88. package/dist/host.d.ts +17 -0
  89. package/dist/host.js +3 -0
  90. package/dist/index.d.ts +26 -51
  91. package/dist/index.js +9 -12
  92. package/dist/model/anthropic-messages.d.ts +10 -0
  93. package/dist/model/anthropic-messages.js +692 -0
  94. package/dist/model/anthropic-thinking.js +33 -0
  95. package/dist/model/configuration.d.ts +111 -0
  96. package/dist/model/configuration.js +201 -0
  97. package/dist/model/contracts.d.ts +229 -0
  98. package/dist/model/http.d.ts +13 -0
  99. package/dist/model/http.js +119 -0
  100. package/dist/model/image-contract.d.ts +10 -0
  101. package/dist/model/image.d.ts +9 -0
  102. package/dist/model/inline-media-budget.d.ts +7 -0
  103. package/dist/model/inline-media-budget.js +36 -0
  104. package/dist/model/input-images.d.ts +3 -0
  105. package/dist/model/input-images.js +16 -0
  106. package/dist/model/openai-responses.d.ts +59 -0
  107. package/dist/model/openai-responses.js +1586 -0
  108. package/dist/model/recovery.js +80 -0
  109. package/dist/model/request-configuration.d.ts +17 -0
  110. package/dist/model/request-configuration.js +47 -0
  111. package/dist/model/responses-event-projection.d.ts +24 -0
  112. package/dist/model/responses-event-projection.js +194 -0
  113. package/dist/model/responses-request.d.ts +5 -0
  114. package/dist/model/responses-request.js +363 -0
  115. package/dist/model/responses-session-cache.d.ts +33 -0
  116. package/dist/model/responses-session-cache.js +64 -0
  117. package/dist/model/runtime-credential.d.ts +1 -0
  118. package/dist/model/runtime-credential.js +1 -0
  119. package/dist/model/sse.js +281 -0
  120. package/dist/model/text-blocks.js +40 -0
  121. package/dist/model/tool-declarations.d.ts +4 -0
  122. package/dist/model/tool-definition-projection.d.ts +6 -0
  123. package/dist/model/tool-definition-projection.js +11 -0
  124. package/dist/model/tool-schema.d.ts +2 -0
  125. package/dist/model/tool-schema.js +17 -0
  126. package/dist/model/transport-test.d.ts +10 -0
  127. package/dist/model/transport-test.js +27 -0
  128. package/dist/model/usage-observer.d.ts +5 -0
  129. package/dist/model/usage.d.ts +40 -0
  130. package/dist/network/credential-runtime.d.ts +8 -0
  131. package/dist/network/credential-runtime.js +72 -0
  132. package/dist/network/credentials.d.ts +20 -0
  133. package/dist/network/credentials.js +18 -0
  134. package/dist/network/http.d.ts +20 -0
  135. package/dist/network/http.js +421 -0
  136. package/dist/network/product-user-agent.d.ts +5 -0
  137. package/dist/network/product-user-agent.js +22 -0
  138. package/dist/network/transport-error.d.ts +5 -0
  139. package/dist/network/transport-error.js +31 -0
  140. package/dist/process/contracts.d.ts +26 -0
  141. package/dist/prompts/index.d.ts +20 -0
  142. package/dist/prompts/index.js +49 -0
  143. package/dist/prompts/prompt-sections.d.ts +6 -0
  144. package/dist/prompts/prompt-sections.js +6 -0
  145. package/dist/prompts/read-context.js +152 -0
  146. package/dist/runtime/compaction/contracts.d.ts +23 -0
  147. package/dist/runtime/compaction/coordinator.js +88 -0
  148. package/dist/runtime/compaction/generate.d.ts +31 -0
  149. package/dist/runtime/compaction/generate.js +84 -0
  150. package/dist/runtime/compaction/history.d.ts +16 -0
  151. package/dist/runtime/compaction/operation.d.ts +30 -0
  152. package/dist/runtime/compaction/operation.js +131 -0
  153. package/dist/runtime/compaction/requests.d.ts +16 -0
  154. package/dist/runtime/compaction/requests.js +114 -0
  155. package/dist/runtime/compaction/retained-context.d.ts +6 -0
  156. package/dist/runtime/compaction/retained-context.js +48 -0
  157. package/dist/runtime/compaction/smart.d.ts +14 -0
  158. package/dist/runtime/compaction/smart.js +59 -0
  159. package/dist/runtime/context/contextual-blocks.d.ts +31 -0
  160. package/dist/runtime/context/contextual-blocks.js +158 -0
  161. package/dist/runtime/context/environment.d.ts +5 -0
  162. package/dist/runtime/context/gc-candidates-code.d.ts +6 -0
  163. package/dist/runtime/context/gc-candidates-code.js +102 -0
  164. package/dist/runtime/context/gc-candidates-exec.d.ts +6 -0
  165. package/dist/runtime/context/gc-candidates-exec.js +131 -0
  166. package/dist/runtime/context/gc-candidates-read-patch.d.ts +7 -0
  167. package/dist/runtime/context/gc-candidates-read-patch.js +118 -0
  168. package/dist/runtime/context/gc-candidates-subagent.d.ts +6 -0
  169. package/dist/runtime/context/gc-candidates-subagent.js +100 -0
  170. package/dist/runtime/context/gc-candidates-web.d.ts +6 -0
  171. package/dist/runtime/context/gc-candidates-web.js +58 -0
  172. package/dist/runtime/context/gc-candidates.d.ts +12 -0
  173. package/dist/runtime/context/gc-candidates.js +192 -0
  174. package/dist/runtime/context/gc-contracts.d.ts +57 -0
  175. package/dist/runtime/context/gc-economics.d.ts +48 -0
  176. package/dist/runtime/context/gc-economics.js +161 -0
  177. package/dist/runtime/context/gc-runtime.d.ts +43 -0
  178. package/dist/runtime/context/gc-tokens.d.ts +26 -0
  179. package/dist/runtime/context/gc-tokens.js +106 -0
  180. package/dist/runtime/context/gc.d.ts +7 -0
  181. package/dist/runtime/context/gc.js +552 -0
  182. package/dist/runtime/context/instructions.d.ts +37 -0
  183. package/dist/runtime/context/instructions.js +297 -0
  184. package/dist/runtime/context/normalize.d.ts +5 -0
  185. package/dist/runtime/context/projection.d.ts +23 -0
  186. package/dist/runtime/context/projection.js +284 -0
  187. package/dist/runtime/context/request-budget.d.ts +5 -0
  188. package/dist/runtime/context/request-budget.js +25 -0
  189. package/dist/runtime/context/restore.d.ts +27 -0
  190. package/dist/runtime/context/restore.js +186 -0
  191. package/dist/runtime/context/usage.d.ts +17 -0
  192. package/dist/runtime/context/usage.js +124 -0
  193. package/dist/runtime/context/world-state.d.ts +34 -0
  194. package/dist/runtime/context/world-state.js +232 -0
  195. package/dist/runtime/contracts.d.ts +29 -0
  196. package/dist/runtime/event-projection.d.ts +14 -0
  197. package/dist/runtime/event-projection.js +87 -0
  198. package/dist/runtime/events.d.ts +195 -0
  199. package/dist/runtime/execution-handle.d.ts +12 -0
  200. package/dist/runtime/execution-handle.js +1 -0
  201. package/dist/runtime/execution.d.ts +55 -0
  202. package/dist/runtime/execution.js +444 -0
  203. package/dist/runtime/model-progress.js +85 -0
  204. package/dist/runtime/resource-publication.d.ts +27 -0
  205. package/dist/runtime/resource-publication.js +60 -0
  206. package/dist/runtime/tool-round-contract.d.ts +19 -0
  207. package/dist/runtime/tool-round-contract.js +1 -0
  208. package/dist/runtime/wait.js +82 -0
  209. package/dist/sandbox/linux/bubblewrap-sandbox-executor.d.ts +1 -1
  210. package/dist/sandbox/linux/bubblewrap-sandbox-executor.js +8 -8
  211. package/dist/sdk/agent.d.ts +7 -0
  212. package/dist/sdk/agent.js +321 -0
  213. package/dist/sdk/execution-code-mode.d.ts +18 -0
  214. package/dist/sdk/execution-code-mode.js +51 -0
  215. package/dist/sdk/execution-compact-commit.d.ts +23 -0
  216. package/dist/sdk/execution-compact-commit.js +41 -0
  217. package/dist/sdk/execution-compact-extension.d.ts +12 -0
  218. package/dist/sdk/execution-compact-extension.js +46 -0
  219. package/dist/sdk/execution-compact-generation.d.ts +17 -0
  220. package/dist/sdk/execution-compact-generation.js +30 -0
  221. package/dist/sdk/execution-compaction-flight.d.ts +31 -0
  222. package/dist/sdk/execution-compaction-flight.js +50 -0
  223. package/dist/sdk/execution-compaction.d.ts +47 -0
  224. package/dist/sdk/execution-compaction.js +121 -0
  225. package/dist/sdk/execution-context-coordinator.d.ts +56 -0
  226. package/dist/sdk/execution-context-coordinator.js +102 -0
  227. package/dist/sdk/execution-input.d.ts +58 -0
  228. package/dist/sdk/execution-input.js +266 -0
  229. package/dist/sdk/execution-model-context.d.ts +52 -0
  230. package/dist/sdk/execution-model-context.js +156 -0
  231. package/dist/sdk/execution-model-lifecycle.d.ts +39 -0
  232. package/dist/sdk/execution-model-lifecycle.js +73 -0
  233. package/dist/sdk/execution-model-request.d.ts +40 -0
  234. package/dist/sdk/execution-model-request.js +45 -0
  235. package/dist/sdk/execution-round-preparation.d.ts +11 -0
  236. package/dist/sdk/execution-round-preparation.js +18 -0
  237. package/dist/sdk/execution-round-request.d.ts +30 -0
  238. package/dist/sdk/execution-round-request.js +31 -0
  239. package/dist/sdk/execution-tool-catalog.d.ts +46 -0
  240. package/dist/sdk/execution-tool-catalog.js +103 -0
  241. package/dist/sdk/execution-tool-scope.d.ts +67 -0
  242. package/dist/sdk/execution-tool-scope.js +147 -0
  243. package/dist/sdk/extension-agent-controller.d.ts +3 -0
  244. package/dist/sdk/extension-agent-controller.js +69 -0
  245. package/dist/sdk/extension-agents.d.ts +9 -0
  246. package/dist/sdk/extension-agents.js +58 -0
  247. package/dist/sdk/extension-models.d.ts +17 -0
  248. package/dist/sdk/extension-models.js +142 -0
  249. package/dist/sdk/extension-session-launch.d.ts +18 -0
  250. package/dist/sdk/extension-session-launch.js +73 -0
  251. package/dist/sdk/extension-session.d.ts +30 -0
  252. package/dist/sdk/extension-session.js +107 -0
  253. package/dist/sdk/extension-tool-runtime.d.ts +2 -0
  254. package/dist/sdk/extension-tool-runtime.js +14 -0
  255. package/dist/sdk/extension-tools.d.ts +16 -0
  256. package/dist/sdk/extension-tools.js +126 -0
  257. package/dist/sdk/model-input-projection.d.ts +4 -0
  258. package/dist/sdk/model-input-projection.js +27 -0
  259. package/dist/sdk/model-runtime.d.ts +21 -0
  260. package/dist/sdk/model-runtime.js +91 -0
  261. package/dist/sdk/native-steer.d.ts +20 -0
  262. package/dist/sdk/native-steer.js +84 -0
  263. package/dist/sdk/request-preparation.d.ts +9 -0
  264. package/dist/sdk/resource-input.d.ts +33 -0
  265. package/dist/sdk/resource-input.js +402 -0
  266. package/dist/sdk/session-catalog.d.ts +2 -0
  267. package/dist/sdk/session-catalog.js +12 -0
  268. package/dist/sdk/session-composition.d.ts +54 -0
  269. package/dist/sdk/session-composition.js +1 -0
  270. package/dist/sdk/session-execution-factory.d.ts +43 -0
  271. package/dist/sdk/session-execution-factory.js +937 -0
  272. package/dist/sdk/session-execution.d.ts +163 -0
  273. package/dist/sdk/session-execution.js +388 -0
  274. package/dist/sdk/session-extension-messages.d.ts +16 -0
  275. package/dist/sdk/session-extension-messages.js +64 -0
  276. package/dist/sdk/session-extension-prompt.d.ts +35 -0
  277. package/dist/sdk/session-extension-prompt.js +62 -0
  278. package/dist/sdk/session-maintenance.d.ts +25 -0
  279. package/dist/sdk/session-maintenance.js +205 -0
  280. package/dist/sdk/session-model-adapters.d.ts +28 -0
  281. package/dist/sdk/session-model-adapters.js +96 -0
  282. package/dist/sdk/session-open.d.ts +22 -0
  283. package/dist/sdk/session-open.js +44 -0
  284. package/dist/sdk/session-registry.d.ts +17 -0
  285. package/dist/sdk/session-registry.js +83 -0
  286. package/dist/sdk/session-runtime.d.ts +72 -0
  287. package/dist/sdk/session-runtime.js +205 -0
  288. package/dist/sdk/session.d.ts +3 -0
  289. package/dist/sdk/session.js +313 -0
  290. package/dist/sdk/subagent-backend.d.ts +3 -0
  291. package/dist/sdk/subagent-backend.js +49 -0
  292. package/dist/sdk/types.d.ts +80 -0
  293. package/dist/sdk/types.js +1 -0
  294. package/dist/session/catalog.d.ts +70 -0
  295. package/dist/session/catalog.js +194 -0
  296. package/dist/session/code-observation-contract.d.ts +40 -0
  297. package/dist/session/code-observation-contract.js +1 -0
  298. package/dist/session/code-observation-projection.d.ts +54 -0
  299. package/dist/session/code-observation-projection.js +165 -0
  300. package/dist/session/code-state.d.ts +27 -0
  301. package/dist/session/code-state.js +89 -0
  302. package/dist/session/context-gc-checkpoint.d.ts +26 -0
  303. package/dist/session/context-gc-checkpoint.js +935 -0
  304. package/dist/session/context-gc-contract.d.ts +141 -0
  305. package/dist/session/context-gc-contract.js +1 -0
  306. package/dist/session/context-gc-observations.d.ts +58 -0
  307. package/dist/session/context-gc-observations.js +187 -0
  308. package/dist/session/context-gc-replacements.d.ts +63 -0
  309. package/dist/session/context-gc-subagent.d.ts +54 -0
  310. package/dist/session/deferred-input.d.ts +5 -0
  311. package/dist/session/deferred-input.js +74 -0
  312. package/dist/session/extension-checkpoint.d.ts +8 -0
  313. package/dist/session/extension-checkpoint.js +30 -0
  314. package/dist/session/history-input-limits.d.ts +4 -0
  315. package/dist/session/history-input-limits.js +4 -0
  316. package/dist/session/inline-media-contract.d.ts +16 -0
  317. package/dist/session/inline-media-contract.js +1 -0
  318. package/dist/session/inline-media.d.ts +26 -0
  319. package/dist/session/inline-media.js +138 -0
  320. package/dist/session/model-request.d.ts +14 -0
  321. package/dist/session/model-request.js +1 -0
  322. package/dist/session/record-contract.d.ts +19 -0
  323. package/dist/session/record-contract.js +1 -0
  324. package/dist/session/record-projection.d.ts +6 -0
  325. package/dist/session/record-projection.js +80 -0
  326. package/dist/session/resource-contract.d.ts +9 -0
  327. package/dist/session/resource-contract.js +1 -0
  328. package/dist/session/rollback.d.ts +13 -0
  329. package/dist/session/rollback.js +46 -0
  330. package/dist/session/store/contracts.d.ts +160 -0
  331. package/dist/session/store/contracts.js +1 -0
  332. package/dist/session/store/current-state.d.ts +17 -0
  333. package/dist/session/store/current-state.js +53 -0
  334. package/dist/session/store/execution-state.d.ts +13 -0
  335. package/dist/session/store/execution-state.js +103 -0
  336. package/dist/session/store/index.d.ts +4 -0
  337. package/dist/session/store/index.js +2 -0
  338. package/dist/session/store/jsonl/directory-index.d.ts +26 -0
  339. package/dist/session/store/jsonl/directory-index.js +283 -0
  340. package/dist/session/store/jsonl/fs-durability.d.ts +3 -0
  341. package/dist/session/store/jsonl/fs-durability.js +17 -0
  342. package/dist/session/store/jsonl/history-replacement.d.ts +48 -0
  343. package/dist/session/store/jsonl/history-replacement.js +147 -0
  344. package/dist/session/store/jsonl/history.d.ts +25 -0
  345. package/dist/session/store/jsonl/history.js +181 -0
  346. package/dist/session/store/jsonl/images.d.ts +19 -0
  347. package/dist/session/store/jsonl/images.js +122 -0
  348. package/dist/session/store/jsonl/index-transaction.d.ts +13 -0
  349. package/dist/session/store/jsonl/index-transaction.js +87 -0
  350. package/dist/session/store/jsonl/jsonl-admission.d.ts +10 -0
  351. package/dist/session/store/jsonl/jsonl-admission.js +205 -0
  352. package/dist/session/store/jsonl/jsonl-codec.d.ts +11 -0
  353. package/dist/session/store/jsonl/jsonl-codec.js +138 -0
  354. package/dist/session/store/jsonl/jsonl-migration.d.ts +12 -0
  355. package/dist/session/store/jsonl/jsonl-migration.js +105 -0
  356. package/dist/session/store/jsonl/jsonl-store.d.ts +171 -0
  357. package/dist/session/store/jsonl/jsonl-store.js +2482 -0
  358. package/dist/session/store/jsonl/open-recovery.d.ts +13 -0
  359. package/dist/session/store/jsonl/open-recovery.js +131 -0
  360. package/dist/session/store/jsonl/read-pins.d.ts +4 -0
  361. package/dist/session/store/jsonl/read-pins.js +131 -0
  362. package/dist/session/store/jsonl/record-append.d.ts +16 -0
  363. package/dist/session/store/jsonl/record-append.js +49 -0
  364. package/dist/session/store/jsonl/records.d.ts +30 -0
  365. package/dist/session/store/jsonl/records.js +313 -0
  366. package/dist/session/store/jsonl/resources.d.ts +19 -0
  367. package/dist/session/store/jsonl/resources.js +209 -0
  368. package/dist/session/store/jsonl/store-pool.d.ts +12 -0
  369. package/dist/session/store/jsonl/store-pool.js +55 -0
  370. package/dist/session/store/jsonl/transaction-recovery.d.ts +48 -0
  371. package/dist/session/store/jsonl/transaction-recovery.js +374 -0
  372. package/dist/session/store/jsonl/tree-maintenance.d.ts +12 -0
  373. package/dist/session/store/jsonl/tree-maintenance.js +59 -0
  374. package/dist/session/store/types.d.ts +69 -0
  375. package/dist/session/store/types.js +1 -0
  376. package/dist/session/summary.d.ts +18 -0
  377. package/dist/session/summary.js +1 -0
  378. package/dist/session/todo.d.ts +11 -0
  379. package/dist/session/todo.js +30 -0
  380. package/dist/session/tool-result-resources.d.ts +27 -0
  381. package/dist/session/tool-result-resources.js +255 -0
  382. package/dist/session/types.js +1 -0
  383. package/dist/session/user-history.d.ts +17 -0
  384. package/dist/session/user-history.js +1 -0
  385. package/dist/session-store.d.ts +2 -0
  386. package/dist/session-store.js +1 -0
  387. package/dist/shared/auto-title.d.ts +3 -3
  388. package/dist/shared/auto-title.js +6 -6
  389. package/dist/shared/model-text.d.ts +8 -8
  390. package/dist/shared/model-text.js +8 -7
  391. package/dist/storage/file-lock.js +83 -0
  392. package/dist/subagent/contracts.d.ts +107 -0
  393. package/dist/subagent/contracts.js +1 -0
  394. package/dist/subagent/limits.d.ts +17 -0
  395. package/dist/subagent/limits.js +17 -0
  396. package/dist/subagent/model-update.js +81 -0
  397. package/dist/subagent/session-controller.d.ts +148 -0
  398. package/dist/subagent/session-controller.js +1761 -0
  399. package/dist/subagent/wait-targets.d.ts +10 -0
  400. package/dist/subagent/wait-targets.js +26 -0
  401. package/dist/subagent/wait.d.ts +26 -0
  402. package/dist/subagent/wait.js +73 -0
  403. package/dist/tools/agent/agent-cancel.d.ts +7 -0
  404. package/dist/tools/agent/agent-cancel.js +29 -0
  405. package/dist/tools/agent/agent-message.d.ts +7 -0
  406. package/dist/tools/agent/agent-message.js +57 -0
  407. package/dist/tools/agent/agent-start.d.ts +12 -0
  408. package/dist/tools/agent/agent-start.js +106 -0
  409. package/dist/tools/agent/agent-wait.d.ts +7 -0
  410. package/dist/tools/agent/agent-wait.js +91 -0
  411. package/dist/tools/agent/question.d.ts +7 -0
  412. package/dist/tools/agent/question.js +125 -0
  413. package/dist/tools/agent/skill.d.ts +11 -0
  414. package/dist/tools/agent/skill.js +38 -0
  415. package/dist/tools/agent/sleep.d.ts +9 -0
  416. package/dist/tools/agent/sleep.js +54 -0
  417. package/dist/tools/agent/smart-compact.d.ts +9 -0
  418. package/dist/tools/agent/smart-compact.js +23 -0
  419. package/dist/tools/agent/todo-read.d.ts +14 -0
  420. package/dist/tools/agent/todo-write.d.ts +14 -0
  421. package/dist/tools/agent/todo-write.js +66 -0
  422. package/dist/tools/agent/todo.d.ts +25 -0
  423. package/dist/tools/agent/todo.js +32 -0
  424. package/dist/tools/callers.d.ts +7 -0
  425. package/dist/tools/callers.js +39 -0
  426. package/dist/tools/code-mode/cells.d.ts +29 -0
  427. package/dist/tools/code-mode/cells.js +338 -0
  428. package/dist/tools/code-mode/dispatch.d.ts +20 -0
  429. package/dist/tools/code-mode/dispatch.js +80 -0
  430. package/dist/tools/code-mode/engine.d.ts +60 -0
  431. package/dist/tools/code-mode/engine.js +1 -0
  432. package/dist/tools/code-mode/index.d.ts +31 -0
  433. package/dist/tools/code-mode/index.js +751 -0
  434. package/dist/tools/code-mode/observations.d.ts +8 -0
  435. package/dist/tools/code-mode/observations.js +64 -0
  436. package/dist/tools/code-mode/worker.d.ts +1 -0
  437. package/dist/tools/contracts.d.ts +193 -0
  438. package/dist/tools/contracts.js +1 -0
  439. package/dist/tools/definition-projection.d.ts +1 -0
  440. package/dist/tools/definition-projection.js +1 -0
  441. package/dist/tools/execution-limits.d.ts +69 -0
  442. package/dist/tools/execution-limits.js +58 -0
  443. package/dist/tools/execution.d.ts +30 -0
  444. package/dist/tools/execution.js +191 -0
  445. package/dist/tools/local/apply-patch-parser.js +177 -0
  446. package/dist/tools/local/apply-patch.d.ts +19 -0
  447. package/dist/tools/local/apply-patch.js +489 -0
  448. package/dist/tools/local/exec.d.ts +28 -0
  449. package/dist/tools/local/exec.js +194 -0
  450. package/dist/tools/local/image-processing.js +146 -0
  451. package/dist/tools/local/read.d.ts +43 -0
  452. package/dist/tools/local/read.js +470 -0
  453. package/dist/tools/local/view-image.d.ts +15 -0
  454. package/dist/tools/local/view-image.js +317 -0
  455. package/dist/tools/mcp/catalog.js +220 -0
  456. package/dist/tools/mcp/history.d.ts +4 -0
  457. package/dist/tools/mcp/tool-search.d.ts +45 -0
  458. package/dist/tools/mcp/tool-search.js +294 -0
  459. package/dist/tools/output-projection.d.ts +18 -0
  460. package/dist/tools/output-projection.js +341 -0
  461. package/dist/tools/permission-contract.d.ts +25 -0
  462. package/dist/tools/permission-contract.js +1 -0
  463. package/dist/tools/permissions.d.ts +61 -0
  464. package/dist/tools/permissions.js +237 -0
  465. package/dist/tools/registry.d.ts +7 -0
  466. package/dist/tools/result-extension-contract.d.ts +37 -0
  467. package/dist/tools/result-extension-contract.js +32 -0
  468. package/dist/tools/result-extensions.d.ts +12 -0
  469. package/dist/tools/result-extensions.js +104 -0
  470. package/dist/tools/runtime-context.d.ts +89 -0
  471. package/dist/tools/runtime-context.js +1 -0
  472. package/dist/tools/runtime-resource-handles.js +28 -0
  473. package/dist/tools/runtime.js +77 -0
  474. package/dist/tools/scheduler.d.ts +12 -0
  475. package/dist/tools/shared/path-resolver.js +133 -0
  476. package/dist/tools/wait.d.ts +1 -0
  477. package/dist/tools/wait.js +1 -0
  478. package/package.json +15 -3
  479. package/dist/agent-core/error.d.ts +0 -15
  480. package/dist/agent-core/error.js +0 -74
  481. package/dist/agent-core/extensions/agents.d.ts +0 -79
  482. package/dist/agent-core/extensions/agents.js +0 -186
  483. package/dist/agent-core/extensions/compaction.d.ts +0 -48
  484. package/dist/agent-core/extensions/contracts.d.ts +0 -265
  485. package/dist/agent-core/extensions/data.d.ts +0 -84
  486. package/dist/agent-core/extensions/data.js +0 -83
  487. package/dist/agent-core/extensions/environment.d.ts +0 -27
  488. package/dist/agent-core/extensions/environment.js +0 -52
  489. package/dist/agent-core/extensions/files.d.ts +0 -64
  490. package/dist/agent-core/extensions/files.js +0 -26
  491. package/dist/agent-core/extensions/hooks.d.ts +0 -32
  492. package/dist/agent-core/extensions/manager.d.ts +0 -39
  493. package/dist/agent-core/extensions/manager.js +0 -458
  494. package/dist/agent-core/extensions/mcp.d.ts +0 -99
  495. package/dist/agent-core/extensions/mcp.js +0 -433
  496. package/dist/agent-core/extensions/model-request.d.ts +0 -56
  497. package/dist/agent-core/extensions/model-request.js +0 -197
  498. package/dist/agent-core/extensions/model-stream.d.ts +0 -9
  499. package/dist/agent-core/extensions/model-stream.js +0 -108
  500. package/dist/agent-core/extensions/models.d.ts +0 -43
  501. package/dist/agent-core/extensions/network.d.ts +0 -32
  502. package/dist/agent-core/extensions/network.js +0 -97
  503. package/dist/agent-core/extensions/operation.d.ts +0 -30
  504. package/dist/agent-core/extensions/processes.d.ts +0 -52
  505. package/dist/agent-core/extensions/processes.js +0 -284
  506. package/dist/agent-core/extensions/prompt-composition.d.ts +0 -24
  507. package/dist/agent-core/extensions/prompt-composition.js +0 -106
  508. package/dist/agent-core/extensions/prompt-input.d.ts +0 -23
  509. package/dist/agent-core/extensions/prompt-input.js +0 -48
  510. package/dist/agent-core/extensions/resources.d.ts +0 -27
  511. package/dist/agent-core/extensions/resources.js +0 -221
  512. package/dist/agent-core/extensions/services.d.ts +0 -31
  513. package/dist/agent-core/extensions/services.js +0 -61
  514. package/dist/agent-core/extensions/session-input.d.ts +0 -163
  515. package/dist/agent-core/extensions/session-input.js +0 -411
  516. package/dist/agent-core/extensions/session-messages.d.ts +0 -41
  517. package/dist/agent-core/extensions/session-messages.js +0 -76
  518. package/dist/agent-core/extensions/session.d.ts +0 -69
  519. package/dist/agent-core/extensions/session.js +0 -607
  520. package/dist/agent-core/extensions/settings.d.ts +0 -59
  521. package/dist/agent-core/extensions/settings.js +0 -115
  522. package/dist/agent-core/extensions/store.d.ts +0 -10
  523. package/dist/agent-core/extensions/store.js +0 -131
  524. package/dist/agent-core/extensions/tools.d.ts +0 -61
  525. package/dist/agent-core/extensions/tools.js +0 -269
  526. package/dist/agent-core/host/contracts.d.ts +0 -100
  527. package/dist/agent-core/host/contracts.js +0 -18
  528. package/dist/agent-core/host/local-agent-host.d.ts +0 -96
  529. package/dist/agent-core/host/local-agent-host.js +0 -425
  530. package/dist/agent-core/host/local-file-access.d.ts +0 -30
  531. package/dist/agent-core/host/local-file-access.js +0 -107
  532. package/dist/agent-core/host/local-network-access.d.ts +0 -6
  533. package/dist/agent-core/host/local-network-access.js +0 -101
  534. package/dist/agent-core/host/local-process-executor.d.ts +0 -29
  535. package/dist/agent-core/host/local-process-executor.js +0 -41
  536. package/dist/agent-core/host/local-session-environment.d.ts +0 -18
  537. package/dist/agent-core/host/local-shell.d.ts +0 -3
  538. package/dist/agent-core/host/network.d.ts +0 -4
  539. package/dist/agent-core/host/network.js +0 -6
  540. package/dist/agent-core/model/anthropic-messages.d.ts +0 -10
  541. package/dist/agent-core/model/anthropic-messages.js +0 -707
  542. package/dist/agent-core/model/anthropic-thinking.js +0 -33
  543. package/dist/agent-core/model/catalog-file.d.ts +0 -80
  544. package/dist/agent-core/model/catalog-file.js +0 -103
  545. package/dist/agent-core/model/configuration.d.ts +0 -127
  546. package/dist/agent-core/model/configuration.js +0 -168
  547. package/dist/agent-core/model/contracts.d.ts +0 -229
  548. package/dist/agent-core/model/http.d.ts +0 -27
  549. package/dist/agent-core/model/http.js +0 -534
  550. package/dist/agent-core/model/image.d.ts +0 -17
  551. package/dist/agent-core/model/openai-responses.d.ts +0 -77
  552. package/dist/agent-core/model/openai-responses.js +0 -2123
  553. package/dist/agent-core/model/product-user-agent.d.ts +0 -5
  554. package/dist/agent-core/model/product-user-agent.js +0 -22
  555. package/dist/agent-core/model/recovery.js +0 -80
  556. package/dist/agent-core/model/request-configuration.d.ts +0 -17
  557. package/dist/agent-core/model/request-configuration.js +0 -47
  558. package/dist/agent-core/model/runtime-credential.d.ts +0 -8
  559. package/dist/agent-core/model/runtime-credential.js +0 -72
  560. package/dist/agent-core/model/sse.js +0 -281
  561. package/dist/agent-core/model/text-blocks.js +0 -40
  562. package/dist/agent-core/model/tool-declarations.d.ts +0 -4
  563. package/dist/agent-core/model/transport-test.d.ts +0 -3
  564. package/dist/agent-core/model/transport-test.js +0 -23
  565. package/dist/agent-core/model/usage-observer.d.ts +0 -31
  566. package/dist/agent-core/prompts/index.d.ts +0 -20
  567. package/dist/agent-core/prompts/index.js +0 -49
  568. package/dist/agent-core/runtime/compaction/coordinator.js +0 -88
  569. package/dist/agent-core/runtime/compaction/generate.d.ts +0 -28
  570. package/dist/agent-core/runtime/compaction/generate.js +0 -84
  571. package/dist/agent-core/runtime/compaction/history.d.ts +0 -16
  572. package/dist/agent-core/runtime/compaction/operation.d.ts +0 -29
  573. package/dist/agent-core/runtime/compaction/operation.js +0 -131
  574. package/dist/agent-core/runtime/compaction/requests.d.ts +0 -16
  575. package/dist/agent-core/runtime/compaction/requests.js +0 -114
  576. package/dist/agent-core/runtime/compaction/retained-context.d.ts +0 -6
  577. package/dist/agent-core/runtime/compaction/retained-context.js +0 -47
  578. package/dist/agent-core/runtime/compaction/smart.d.ts +0 -14
  579. package/dist/agent-core/runtime/compaction/smart.js +0 -59
  580. package/dist/agent-core/runtime/context/contextual-blocks.d.ts +0 -30
  581. package/dist/agent-core/runtime/context/contextual-blocks.js +0 -146
  582. package/dist/agent-core/runtime/context/environment.d.ts +0 -5
  583. package/dist/agent-core/runtime/context/gc-runtime.d.ts +0 -38
  584. package/dist/agent-core/runtime/context/gc-tokens.d.ts +0 -25
  585. package/dist/agent-core/runtime/context/gc-tokens.js +0 -103
  586. package/dist/agent-core/runtime/context/gc.d.ts +0 -75
  587. package/dist/agent-core/runtime/context/gc.js +0 -1386
  588. package/dist/agent-core/runtime/context/instructions.d.ts +0 -37
  589. package/dist/agent-core/runtime/context/instructions.js +0 -297
  590. package/dist/agent-core/runtime/context/normalize.d.ts +0 -5
  591. package/dist/agent-core/runtime/context/projection.d.ts +0 -23
  592. package/dist/agent-core/runtime/context/projection.js +0 -284
  593. package/dist/agent-core/runtime/context/request-budget.d.ts +0 -4
  594. package/dist/agent-core/runtime/context/request-budget.js +0 -25
  595. package/dist/agent-core/runtime/context/restore.d.ts +0 -25
  596. package/dist/agent-core/runtime/context/restore.js +0 -186
  597. package/dist/agent-core/runtime/context/usage.d.ts +0 -17
  598. package/dist/agent-core/runtime/context/usage.js +0 -124
  599. package/dist/agent-core/runtime/context/world-state.d.ts +0 -33
  600. package/dist/agent-core/runtime/context/world-state.js +0 -232
  601. package/dist/agent-core/runtime/contracts.d.ts +0 -41
  602. package/dist/agent-core/runtime/event-projection.d.ts +0 -14
  603. package/dist/agent-core/runtime/event-projection.js +0 -87
  604. package/dist/agent-core/runtime/events.d.ts +0 -197
  605. package/dist/agent-core/runtime/execution-handle.d.ts +0 -12
  606. package/dist/agent-core/runtime/execution.d.ts +0 -50
  607. package/dist/agent-core/runtime/execution.js +0 -445
  608. package/dist/agent-core/runtime/model-progress.js +0 -85
  609. package/dist/agent-core/runtime/resource-publication.d.ts +0 -8
  610. package/dist/agent-core/runtime/resource-publication.js +0 -60
  611. package/dist/agent-core/sdk/agent.d.ts +0 -11
  612. package/dist/agent-core/sdk/agent.js +0 -474
  613. package/dist/agent-core/sdk/extension-agents.d.ts +0 -9
  614. package/dist/agent-core/sdk/extension-agents.js +0 -58
  615. package/dist/agent-core/sdk/extension-models.d.ts +0 -13
  616. package/dist/agent-core/sdk/extension-models.js +0 -137
  617. package/dist/agent-core/sdk/extension-session.d.ts +0 -30
  618. package/dist/agent-core/sdk/extension-session.js +0 -105
  619. package/dist/agent-core/sdk/extension-tools.d.ts +0 -16
  620. package/dist/agent-core/sdk/extension-tools.js +0 -126
  621. package/dist/agent-core/sdk/model-runtime.d.ts +0 -18
  622. package/dist/agent-core/sdk/model-runtime.js +0 -93
  623. package/dist/agent-core/sdk/native-steer.d.ts +0 -20
  624. package/dist/agent-core/sdk/native-steer.js +0 -84
  625. package/dist/agent-core/sdk/request-preparation.d.ts +0 -7
  626. package/dist/agent-core/sdk/resource-input.d.ts +0 -32
  627. package/dist/agent-core/sdk/resource-input.js +0 -403
  628. package/dist/agent-core/sdk/session.d.ts +0 -94
  629. package/dist/agent-core/sdk/session.js +0 -2377
  630. package/dist/agent-core/sdk/subagent-backend.d.ts +0 -3
  631. package/dist/agent-core/sdk/subagent-backend.js +0 -49
  632. package/dist/agent-core/sdk/types.d.ts +0 -81
  633. package/dist/agent-core/session/catalog.d.ts +0 -99
  634. package/dist/agent-core/session/catalog.js +0 -200
  635. package/dist/agent-core/session/context-gc-checkpoint.d.ts +0 -165
  636. package/dist/agent-core/session/context-gc-checkpoint.js +0 -935
  637. package/dist/agent-core/session/context-gc-observations.d.ts +0 -60
  638. package/dist/agent-core/session/context-gc-observations.js +0 -187
  639. package/dist/agent-core/session/context-gc-replacements.d.ts +0 -62
  640. package/dist/agent-core/session/context-gc-subagent.d.ts +0 -53
  641. package/dist/agent-core/session/deferred-input.d.ts +0 -5
  642. package/dist/agent-core/session/deferred-input.js +0 -74
  643. package/dist/agent-core/session/inline-media.d.ts +0 -45
  644. package/dist/agent-core/session/inline-media.js +0 -163
  645. package/dist/agent-core/session/rollback.d.ts +0 -13
  646. package/dist/agent-core/session/rollback.js +0 -46
  647. package/dist/agent-core/session/store/contracts.d.ts +0 -158
  648. package/dist/agent-core/session/store/current-state.d.ts +0 -17
  649. package/dist/agent-core/session/store/current-state.js +0 -53
  650. package/dist/agent-core/session/store/directory-index.d.ts +0 -18
  651. package/dist/agent-core/session/store/directory-index.js +0 -169
  652. package/dist/agent-core/session/store/execution-state.d.ts +0 -18
  653. package/dist/agent-core/session/store/execution-state.js +0 -175
  654. package/dist/agent-core/session/store/history.d.ts +0 -25
  655. package/dist/agent-core/session/store/history.js +0 -181
  656. package/dist/agent-core/session/store/images.d.ts +0 -19
  657. package/dist/agent-core/session/store/images.js +0 -110
  658. package/dist/agent-core/session/store/index.d.ts +0 -4
  659. package/dist/agent-core/session/store/index.js +0 -2
  660. package/dist/agent-core/session/store/jsonl-store.d.ts +0 -171
  661. package/dist/agent-core/session/store/jsonl-store.js +0 -2078
  662. package/dist/agent-core/session/store/records.d.ts +0 -23
  663. package/dist/agent-core/session/store/records.js +0 -261
  664. package/dist/agent-core/session/store/resources.d.ts +0 -26
  665. package/dist/agent-core/session/store/resources.js +0 -197
  666. package/dist/agent-core/session/store/types.d.ts +0 -82
  667. package/dist/agent-core/session/tool-result-resources.d.ts +0 -26
  668. package/dist/agent-core/session/tool-result-resources.js +0 -256
  669. package/dist/agent-core/session/transaction-recovery.d.ts +0 -16
  670. package/dist/agent-core/session/transaction-recovery.js +0 -135
  671. package/dist/agent-core/storage/file-lock.js +0 -83
  672. package/dist/agent-core/subagent/contracts.d.ts +0 -117
  673. package/dist/agent-core/subagent/model-update.js +0 -81
  674. package/dist/agent-core/subagent/scheduler.d.ts +0 -135
  675. package/dist/agent-core/subagent/scheduler.js +0 -369
  676. package/dist/agent-core/subagent/session-controller.d.ts +0 -138
  677. package/dist/agent-core/subagent/session-controller.js +0 -1594
  678. package/dist/agent-core/subagent/wait.d.ts +0 -14
  679. package/dist/agent-core/subagent/wait.js +0 -32
  680. package/dist/agent-core/tools/agent/agent-cancel.d.ts +0 -7
  681. package/dist/agent-core/tools/agent/agent-cancel.js +0 -29
  682. package/dist/agent-core/tools/agent/agent-message.d.ts +0 -7
  683. package/dist/agent-core/tools/agent/agent-message.js +0 -57
  684. package/dist/agent-core/tools/agent/agent-start.d.ts +0 -12
  685. package/dist/agent-core/tools/agent/agent-start.js +0 -106
  686. package/dist/agent-core/tools/agent/agent-wait.d.ts +0 -7
  687. package/dist/agent-core/tools/agent/agent-wait.js +0 -91
  688. package/dist/agent-core/tools/agent/question.d.ts +0 -7
  689. package/dist/agent-core/tools/agent/question.js +0 -125
  690. package/dist/agent-core/tools/agent/skill.d.ts +0 -11
  691. package/dist/agent-core/tools/agent/skill.js +0 -38
  692. package/dist/agent-core/tools/agent/sleep.d.ts +0 -12
  693. package/dist/agent-core/tools/agent/sleep.js +0 -54
  694. package/dist/agent-core/tools/agent/smart-compact.d.ts +0 -9
  695. package/dist/agent-core/tools/agent/smart-compact.js +0 -23
  696. package/dist/agent-core/tools/agent/todo-read.d.ts +0 -14
  697. package/dist/agent-core/tools/agent/todo-write.d.ts +0 -14
  698. package/dist/agent-core/tools/agent/todo-write.js +0 -66
  699. package/dist/agent-core/tools/agent/todo.d.ts +0 -26
  700. package/dist/agent-core/tools/agent/todo.js +0 -60
  701. package/dist/agent-core/tools/callers.d.ts +0 -6
  702. package/dist/agent-core/tools/callers.js +0 -39
  703. package/dist/agent-core/tools/code-mode/cells.d.ts +0 -29
  704. package/dist/agent-core/tools/code-mode/cells.js +0 -337
  705. package/dist/agent-core/tools/code-mode/dispatch.d.ts +0 -20
  706. package/dist/agent-core/tools/code-mode/dispatch.js +0 -80
  707. package/dist/agent-core/tools/code-mode/engine.d.ts +0 -60
  708. package/dist/agent-core/tools/code-mode/index.d.ts +0 -29
  709. package/dist/agent-core/tools/code-mode/index.js +0 -749
  710. package/dist/agent-core/tools/code-mode/observations.d.ts +0 -98
  711. package/dist/agent-core/tools/code-mode/observations.js +0 -228
  712. package/dist/agent-core/tools/code-mode/state.d.ts +0 -9
  713. package/dist/agent-core/tools/code-mode/state.js +0 -82
  714. package/dist/agent-core/tools/contracts.d.ts +0 -211
  715. package/dist/agent-core/tools/definition-projection.d.ts +0 -7
  716. package/dist/agent-core/tools/definition-projection.js +0 -26
  717. package/dist/agent-core/tools/execution-limits.d.ts +0 -69
  718. package/dist/agent-core/tools/execution-limits.js +0 -69
  719. package/dist/agent-core/tools/execution.d.ts +0 -46
  720. package/dist/agent-core/tools/execution.js +0 -191
  721. package/dist/agent-core/tools/local/apply-patch-parser.js +0 -177
  722. package/dist/agent-core/tools/local/apply-patch.d.ts +0 -19
  723. package/dist/agent-core/tools/local/apply-patch.js +0 -489
  724. package/dist/agent-core/tools/local/exec.d.ts +0 -53
  725. package/dist/agent-core/tools/local/exec.js +0 -877
  726. package/dist/agent-core/tools/local/image-processing.js +0 -146
  727. package/dist/agent-core/tools/local/read-context.js +0 -152
  728. package/dist/agent-core/tools/local/read.d.ts +0 -43
  729. package/dist/agent-core/tools/local/read.js +0 -470
  730. package/dist/agent-core/tools/local/registry.d.ts +0 -34
  731. package/dist/agent-core/tools/local/registry.js +0 -132
  732. package/dist/agent-core/tools/local/view-image.d.ts +0 -15
  733. package/dist/agent-core/tools/local/view-image.js +0 -317
  734. package/dist/agent-core/tools/local/workspace-tools.d.ts +0 -12
  735. package/dist/agent-core/tools/local/workspace-tools.js +0 -28
  736. package/dist/agent-core/tools/mcp/catalog.js +0 -220
  737. package/dist/agent-core/tools/mcp/history.d.ts +0 -4
  738. package/dist/agent-core/tools/mcp/tool-search.d.ts +0 -45
  739. package/dist/agent-core/tools/mcp/tool-search.js +0 -294
  740. package/dist/agent-core/tools/output-projection.d.ts +0 -18
  741. package/dist/agent-core/tools/output-projection.js +0 -341
  742. package/dist/agent-core/tools/permissions.d.ts +0 -85
  743. package/dist/agent-core/tools/permissions.js +0 -237
  744. package/dist/agent-core/tools/registry.d.ts +0 -7
  745. package/dist/agent-core/tools/result-extensions.d.ts +0 -46
  746. package/dist/agent-core/tools/result-extensions.js +0 -134
  747. package/dist/agent-core/tools/runtime-context.d.ts +0 -74
  748. package/dist/agent-core/tools/runtime-resource-handles.js +0 -28
  749. package/dist/agent-core/tools/runtime.js +0 -77
  750. package/dist/agent-core/tools/scheduler.d.ts +0 -12
  751. package/dist/agent-core/tools/shared/path-resolver.js +0 -133
  752. package/dist/agent-core/tools/wait.js +0 -82
  753. /package/dist/{agent-core/extensions/models.js → extensions/capabilities.js} +0 -0
  754. /package/dist/{agent-core/extensions → extensions}/compaction.js +0 -0
  755. /package/dist/{agent-core/model → extensions}/contracts.js +0 -0
  756. /package/dist/{agent-core/extensions → extensions}/hooks.js +0 -0
  757. /package/dist/{agent-core/runtime/context/contracts.js → extensions/host-ports.js} +0 -0
  758. /package/dist/{agent-core/extensions → extensions}/operation.js +0 -0
  759. /package/dist/{agent-core/runtime/contracts.js → extensions/tool-runtime.js} +0 -0
  760. /package/dist/{agent-core/extensions/contracts.js → extensions.js} +0 -0
  761. /package/dist/{agent-core/runtime/events.js → host/description.js} +0 -0
  762. /package/dist/{agent-core/host → host}/local-session-environment.js +0 -0
  763. /package/dist/{agent-core/host → host}/local-shell.js +0 -0
  764. /package/dist/{agent-core/runtime/execution-handle.js → host/skill-contract.js} +0 -0
  765. /package/dist/{agent-core/model → model}/anthropic-thinking.d.ts +0 -0
  766. /package/dist/{agent-core/model → model}/attempt-diagnostics.d.ts +0 -0
  767. /package/dist/{agent-core/model → model}/attempt-diagnostics.js +0 -0
  768. /package/dist/{agent-core/session/store → model}/contracts.js +0 -0
  769. /package/dist/{agent-core/sdk/types.js → model/image-contract.js} +0 -0
  770. /package/dist/{agent-core/model → model}/image.js +0 -0
  771. /package/dist/{agent-core/model → model}/native-context.d.ts +0 -0
  772. /package/dist/{agent-core/model → model}/native-context.js +0 -0
  773. /package/dist/{agent-core/model → model}/recovery.d.ts +0 -0
  774. /package/dist/{agent-core/model → model}/sse.d.ts +0 -0
  775. /package/dist/{agent-core/model → model}/text-blocks.d.ts +0 -0
  776. /package/dist/{agent-core/model → model}/tool-declarations.js +0 -0
  777. /package/dist/{agent-core/model → model}/tool-input.d.ts +0 -0
  778. /package/dist/{agent-core/model → model}/tool-input.js +0 -0
  779. /package/dist/{agent-core/model → model}/usage-observer.js +0 -0
  780. /package/dist/{agent-core/session/store/types.js → model/usage.js} +0 -0
  781. /package/dist/{agent-core/subagent → process}/contracts.js +0 -0
  782. /package/dist/{agent-core/prompts → prompts}/compact.d.ts +0 -0
  783. /package/dist/{agent-core/prompts → prompts}/compact.js +0 -0
  784. /package/dist/{agent-core/prompts → prompts}/core.d.ts +0 -0
  785. /package/dist/{agent-core/prompts → prompts}/core.js +0 -0
  786. /package/dist/{agent-core/prompts → prompts}/markup.d.ts +0 -0
  787. /package/dist/{agent-core/prompts → prompts}/markup.js +0 -0
  788. /package/dist/{agent-core/prompts → prompts}/modes.d.ts +0 -0
  789. /package/dist/{agent-core/prompts → prompts}/modes.js +0 -0
  790. /package/dist/{agent-core/prompts → prompts}/output.d.ts +0 -0
  791. /package/dist/{agent-core/prompts → prompts}/output.js +0 -0
  792. /package/dist/{agent-core/prompts → prompts}/permissions.d.ts +0 -0
  793. /package/dist/{agent-core/prompts → prompts}/permissions.js +0 -0
  794. /package/dist/{agent-core/tools/local → prompts}/read-context.d.ts +0 -0
  795. /package/dist/{agent-core/prompts → prompts}/resources.d.ts +0 -0
  796. /package/dist/{agent-core/prompts → prompts}/resources.js +0 -0
  797. /package/dist/{agent-core/prompts → prompts}/subagent.d.ts +0 -0
  798. /package/dist/{agent-core/prompts → prompts}/subagent.js +0 -0
  799. /package/dist/{agent-core/prompts → prompts}/workflow.d.ts +0 -0
  800. /package/dist/{agent-core/prompts → prompts}/workflow.js +0 -0
  801. /package/dist/{agent-core/runtime → runtime}/async-queue.d.ts +0 -0
  802. /package/dist/{agent-core/runtime → runtime}/async-queue.js +0 -0
  803. /package/dist/{agent-core/tools → runtime/compaction}/contracts.js +0 -0
  804. /package/dist/{agent-core/runtime → runtime}/compaction/coordinator.d.ts +0 -0
  805. /package/dist/{agent-core/runtime → runtime}/compaction/history.js +0 -0
  806. /package/dist/{agent-core/runtime → runtime}/context/contracts.d.ts +0 -0
  807. /package/dist/{agent-core/session/types.js → runtime/context/contracts.js} +0 -0
  808. /package/dist/{agent-core/runtime → runtime}/context/environment.js +0 -0
  809. /package/dist/{agent-core/tools/code-mode/engine.js → runtime/context/gc-contracts.js} +0 -0
  810. /package/dist/{agent-core/runtime → runtime}/context/gc-runtime.js +0 -0
  811. /package/dist/{agent-core/runtime → runtime}/context/normalize.js +0 -0
  812. /package/dist/{agent-core/tools/code-mode/worker.d.ts → runtime/contracts.js} +0 -0
  813. /package/dist/{agent-core/tools/runtime-context.js → runtime/events.js} +0 -0
  814. /package/dist/{agent-core/runtime → runtime}/execution-policy.d.ts +0 -0
  815. /package/dist/{agent-core/runtime → runtime}/execution-policy.js +0 -0
  816. /package/dist/{agent-core/runtime → runtime}/model-generation-timing.d.ts +0 -0
  817. /package/dist/{agent-core/runtime → runtime}/model-generation-timing.js +0 -0
  818. /package/dist/{agent-core/runtime → runtime}/model-progress.d.ts +0 -0
  819. /package/dist/{agent-core/runtime → runtime}/plan-output.d.ts +0 -0
  820. /package/dist/{agent-core/runtime → runtime}/plan-output.js +0 -0
  821. /package/dist/{agent-core/tools/public-metadata.d.ts → runtime/public-tool-metadata.d.ts} +0 -0
  822. /package/dist/{agent-core/tools/public-metadata.js → runtime/public-tool-metadata.js} +0 -0
  823. /package/dist/{agent-core/runtime → runtime}/token-budget.d.ts +0 -0
  824. /package/dist/{agent-core/runtime → runtime}/token-budget.js +0 -0
  825. /package/dist/{agent-core/tools → runtime}/wait.d.ts +0 -0
  826. /package/dist/{agent-core/sdk → sdk}/request-preparation.js +0 -0
  827. /package/dist/{agent-core/session → session}/context-gc-markup.d.ts +0 -0
  828. /package/dist/{agent-core/session → session}/context-gc-markup.js +0 -0
  829. /package/dist/{agent-core/session → session}/context-gc-replacements.js +0 -0
  830. /package/dist/{agent-core/session → session}/context-gc-subagent.js +0 -0
  831. /package/dist/{agent-core/session → session}/types.d.ts +0 -0
  832. /package/dist/{agent-core/storage → storage}/file-lock.d.ts +0 -0
  833. /package/dist/{agent-core/subagent → subagent}/model-update.d.ts +0 -0
  834. /package/dist/{agent-core/tools → tools}/agent/todo-read.js +0 -0
  835. /package/dist/{agent-core/tools → tools}/code-mode/quickjs-engine.d.ts +0 -0
  836. /package/dist/{agent-core/tools → tools}/code-mode/quickjs-engine.js +0 -0
  837. /package/dist/{agent-core/tools → tools}/code-mode/text-output.d.ts +0 -0
  838. /package/dist/{agent-core/tools → tools}/code-mode/text-output.js +0 -0
  839. /package/dist/{agent-core/tools → tools}/code-mode/worker.js +0 -0
  840. /package/dist/{agent-core/tools → tools}/file-change-diff.d.ts +0 -0
  841. /package/dist/{agent-core/tools → tools}/file-change-diff.js +0 -0
  842. /package/dist/{agent-core/tools → tools}/input-diagnostics/source-preview.d.ts +0 -0
  843. /package/dist/{agent-core/tools → tools}/input-diagnostics/source-preview.js +0 -0
  844. /package/dist/{agent-core/tools → tools}/input.d.ts +0 -0
  845. /package/dist/{agent-core/tools → tools}/input.js +0 -0
  846. /package/dist/{agent-core/tools → tools}/local/apply-patch-parser.d.ts +0 -0
  847. /package/dist/{agent-core/tools → tools}/local/image-processing.d.ts +0 -0
  848. /package/dist/{agent-core/tools → tools}/mcp/catalog.d.ts +0 -0
  849. /package/dist/{agent-core/tools → tools}/mcp/history.js +0 -0
  850. /package/dist/{agent-core/tools → tools}/registry.js +0 -0
  851. /package/dist/{agent-core/tools → tools}/runtime-resource-handles.d.ts +0 -0
  852. /package/dist/{agent-core/tools → tools}/runtime.d.ts +0 -0
  853. /package/dist/{agent-core/tools → tools}/scheduler.js +0 -0
  854. /package/dist/{agent-core/tools → tools}/shared/patch-result.d.ts +0 -0
  855. /package/dist/{agent-core/tools → tools}/shared/patch-result.js +0 -0
  856. /package/dist/{agent-core/tools → tools}/shared/path-resolver.d.ts +0 -0
@@ -0,0 +1,1761 @@
1
+ import { waitMetadata } from '../runtime/wait.js';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { AgentError, describeAgentError } from '../error.js';
5
+ import { SUBAGENT_LIMITS } from './limits.js';
6
+ import { parseAgentWaitTargets, SubagentWaitCoordinator, waitForAgentGroup } from './wait.js';
7
+ const RECENT_TERMINAL_RESOURCE_LIMIT = 16;
8
+ /** Owns the mutable state and transitions of one child task. */
9
+ class SubagentTask {
10
+ state;
11
+ get detailsEvicted() {
12
+ return this.state.detailsEvicted;
13
+ }
14
+ get restorable() {
15
+ return this.state.restorable;
16
+ }
17
+ get permissionStop() {
18
+ return this.state.permissionStop;
19
+ }
20
+ get agentId() {
21
+ return this.state.agentId;
22
+ }
23
+ get description() {
24
+ return this.state.description;
25
+ }
26
+ get role() {
27
+ return this.state.role;
28
+ }
29
+ get ownerInstanceId() {
30
+ return this.state.ownerInstanceId;
31
+ }
32
+ get extensionId() {
33
+ return this.state.extensionId;
34
+ }
35
+ get status() {
36
+ return this.state.status;
37
+ }
38
+ get modelId() {
39
+ return this.state.modelId;
40
+ }
41
+ get modelName() {
42
+ return this.state.modelName;
43
+ }
44
+ get reasoningEffort() {
45
+ return this.state.reasoningEffort;
46
+ }
47
+ get latestMessage() {
48
+ return this.state.latestMessage;
49
+ }
50
+ get latestActivity() {
51
+ return this.state.latestActivity;
52
+ }
53
+ get messageRevision() {
54
+ return this.state.messageRevision;
55
+ }
56
+ get observedMessageRevision() {
57
+ return this.state.observedMessageRevision;
58
+ }
59
+ get latestMessageActivityRevision() {
60
+ return this.state.latestMessageActivityRevision;
61
+ }
62
+ get summary() {
63
+ return this.state.summary;
64
+ }
65
+ get changedFiles() {
66
+ return this.state.changedFiles;
67
+ }
68
+ get verification() {
69
+ return this.state.verification;
70
+ }
71
+ get evidence() {
72
+ return this.state.evidence;
73
+ }
74
+ get errorCode() {
75
+ return this.state.errorCode;
76
+ }
77
+ get errorMessage() {
78
+ return this.state.errorMessage;
79
+ }
80
+ get terminalPending() {
81
+ return this.state.terminalPending;
82
+ }
83
+ get observedTerminalRevision() {
84
+ return this.state.observedTerminalRevision;
85
+ }
86
+ get terminalRevision() {
87
+ return this.state.terminalRevision;
88
+ }
89
+ get resourceRevision() {
90
+ return this.state.resourceRevision;
91
+ }
92
+ get turn() {
93
+ return this.state.turn;
94
+ }
95
+ get controlTail() {
96
+ return this.state.controlTail;
97
+ }
98
+ get receipt() {
99
+ return this.state.receipt;
100
+ }
101
+ constructor(state) {
102
+ this.state = state;
103
+ }
104
+ acknowledgeMessage(revision) {
105
+ this.state.observedMessageRevision = Math.max(this.state.observedMessageRevision, revision);
106
+ }
107
+ acknowledgeTerminal(revision) {
108
+ this.state.observedTerminalRevision = Math.max(this.state.observedTerminalRevision, revision);
109
+ }
110
+ selectModel(model) {
111
+ this.state.modelId = model.id;
112
+ this.state.modelName = model.name;
113
+ if (model.reasoningEffort !== undefined)
114
+ this.state.reasoningEffort = model.reasoningEffort;
115
+ }
116
+ setReceipt(receipt) {
117
+ this.state.receipt = receipt;
118
+ }
119
+ updateDelivery(receipt, status) {
120
+ if (status !== 'applied' && receipt.deliveryStatus !== 'accepted')
121
+ return false;
122
+ receipt.deliveryStatus = status;
123
+ return true;
124
+ }
125
+ requestCancel(expected) {
126
+ const turn = this.state.turn;
127
+ if (turn !== expected)
128
+ return;
129
+ if (turn.handle)
130
+ turn.handle.cancel();
131
+ else
132
+ turn.cancelRequested = true;
133
+ }
134
+ attachHandle(expected, handle) {
135
+ const turn = this.state.turn;
136
+ if (turn !== expected)
137
+ return;
138
+ turn.handle = handle;
139
+ }
140
+ cancelPending(expected) {
141
+ const turn = this.state.turn;
142
+ if (turn === expected && turn.cancelRequested)
143
+ turn.handle.cancel();
144
+ }
145
+ takePendingMessages(expected) {
146
+ const turn = this.state.turn;
147
+ return turn === expected ? turn.pendingMessages.splice(0) : [];
148
+ }
149
+ settleHandleReady(expected) {
150
+ if (this.state.turn === expected)
151
+ this.state.turn.resolveHandleReady();
152
+ }
153
+ settleCompletion(expected) {
154
+ if (this.state.turn === expected)
155
+ this.state.turn.resolve();
156
+ }
157
+ appendMessage(message) {
158
+ this.state.turn.pendingMessages.push(message);
159
+ }
160
+ control(operation) {
161
+ const result = (this.state.controlTail ?? Promise.resolve()).then(operation);
162
+ const tail = result.then(() => undefined, () => undefined);
163
+ this.state.controlTail = tail;
164
+ void tail.then(() => {
165
+ if (this.state.controlTail === tail)
166
+ delete this.state.controlTail;
167
+ });
168
+ return result;
169
+ }
170
+ cancelQueued(publish) {
171
+ this.state.status = 'cancelled';
172
+ if (publish)
173
+ this.state.terminalPending = true;
174
+ }
175
+ queueTurn(input, onComplete) {
176
+ let resolve;
177
+ let resolveHandleReady;
178
+ const completion = new Promise((done) => (resolve = done));
179
+ const handleReady = new Promise((done) => (resolveHandleReady = done));
180
+ const turn = {
181
+ ...input,
182
+ handleReady,
183
+ completion,
184
+ resolve: () => {
185
+ onComplete();
186
+ resolve();
187
+ },
188
+ resolveHandleReady
189
+ };
190
+ this.state.status = 'queued';
191
+ this.state.restorable = false;
192
+ delete this.state.summary;
193
+ delete this.state.permissionStop;
194
+ delete this.state.errorCode;
195
+ delete this.state.errorMessage;
196
+ this.state.changedFiles = [];
197
+ this.state.verification = [];
198
+ this.state.evidence = [];
199
+ this.state.terminalPending = false;
200
+ this.state.turn = turn;
201
+ return turn;
202
+ }
203
+ markRunning() {
204
+ this.state.status = 'running';
205
+ }
206
+ clearTurn(expected) {
207
+ if (expected === undefined || this.state.turn === expected)
208
+ delete this.state.turn;
209
+ }
210
+ observeEvent(event, revision) {
211
+ if (!observeAgentEvent(this.state, event))
212
+ return false;
213
+ this.state.messageRevision++;
214
+ this.state.latestMessageActivityRevision = revision;
215
+ return true;
216
+ }
217
+ complete(result, terminal, persisted, previousActivity, previousRevision) {
218
+ if (result.status === 'completed') {
219
+ this.state.status = 'completed';
220
+ this.state.summary = result.finalAnswer;
221
+ if (result.permissionStop)
222
+ this.state.permissionStop = result.permissionStop;
223
+ else
224
+ delete this.state.permissionStop;
225
+ }
226
+ else if (result.status === 'cancelled')
227
+ this.state.status = 'cancelled';
228
+ else {
229
+ this.state.status = 'failed';
230
+ this.state.errorCode = result.errorCode ?? 'MAR_AGENT_SUBAGENT_FAILED';
231
+ this.state.errorMessage = result.errorMessage ?? 'Subagent execution failed.';
232
+ }
233
+ this.state.restorable =
234
+ persisted &&
235
+ terminal === this.state.status &&
236
+ (previousActivity === undefined || this.state.latestActivity !== previousActivity) &&
237
+ (this.state.latestMessage === undefined || this.state.messageRevision > previousRevision) &&
238
+ (this.state.status !== 'completed' ||
239
+ (this.state.latestMessage?.phase === 'final_answer' &&
240
+ this.state.summary === this.state.latestMessage.text));
241
+ this.state.terminalPending = true;
242
+ }
243
+ fail(error) {
244
+ const diagnostic = describeAgentError(error, 'MAR_AGENT_SUBAGENT_FAILED');
245
+ this.state.status = 'failed';
246
+ this.state.restorable = false;
247
+ this.state.errorCode = diagnostic.code;
248
+ this.state.errorMessage = diagnostic.message;
249
+ this.state.terminalPending = true;
250
+ }
251
+ touch(revision, terminal = false) {
252
+ this.state.resourceRevision = revision;
253
+ if (terminal)
254
+ this.state.terminalRevision = revision;
255
+ }
256
+ terminalPublished(revision) {
257
+ if (this.state.terminalRevision === revision)
258
+ this.state.terminalPending = false;
259
+ }
260
+ evictDetails() {
261
+ for (const key of DETAIL_FIELDS)
262
+ delete this.state[key];
263
+ this.state.changedFiles = [];
264
+ this.state.verification = [];
265
+ this.state.evidence = [];
266
+ this.state.detailsEvicted = true;
267
+ }
268
+ restoreDetails(restored) {
269
+ for (const key of DETAIL_FIELDS) {
270
+ if (key in restored)
271
+ Object.assign(this.state, { [key]: restored[key] });
272
+ else
273
+ delete this.state[key];
274
+ }
275
+ delete this.state.detailsEvicted;
276
+ }
277
+ copyWaitState() {
278
+ return {
279
+ ...this.state,
280
+ changedFiles: [...this.state.changedFiles],
281
+ verification: [...this.state.verification],
282
+ evidence: this.state.evidence.map((item) => ({ ...item }))
283
+ };
284
+ }
285
+ }
286
+ const DETAIL_FIELDS = [
287
+ 'latestMessage',
288
+ 'latestActivity',
289
+ 'summary',
290
+ 'changedFiles',
291
+ 'verification',
292
+ 'evidence',
293
+ 'permissionStop',
294
+ 'errorMessage'
295
+ ];
296
+ export class SubagentSessionController {
297
+ parentSessionId;
298
+ rootSessionId;
299
+ backend;
300
+ limits;
301
+ #agents = new Map();
302
+ // Discovery order is independent of the order in which history is requested.
303
+ #discovered = new Map();
304
+ #loading = new Map();
305
+ #readers = new Map();
306
+ #allReaders = 0;
307
+ #queue = [];
308
+ #waiters = new SubagentWaitCoordinator();
309
+ modelMessages = {
310
+ pending: () => [...this.#agents.values()].some((state) => state.messageRevision > state.observedMessageRevision),
311
+ subscribe: (listener) => {
312
+ const notify = (activity) => {
313
+ if (activity.kind === 'message')
314
+ listener();
315
+ };
316
+ return this.#waiters.subscribeActivity(notify);
317
+ }
318
+ };
319
+ #nativeObservations = new Map();
320
+ #activityRevision = 0;
321
+ #resourceRevision = 0;
322
+ #running = 0;
323
+ #disposed = false;
324
+ #creationBudget = { count: 0 };
325
+ #retainedExecution = new AsyncLocalStorage();
326
+ #execution;
327
+ #pendingDeliveries = new Set();
328
+ constructor(parentSessionId, rootSessionId, backend, limits = { maxTasks: 16, maxConcurrent: 16 }) {
329
+ this.parentSessionId = parentSessionId;
330
+ this.rootSessionId = rootSessionId;
331
+ this.backend = backend;
332
+ this.limits = limits;
333
+ }
334
+ static async open(input) {
335
+ const controller = new SubagentSessionController(input.parentSessionId, input.rootSessionId, input.backend, input.limits);
336
+ const sessions = await input.backend.listChildren(input.parentSessionId);
337
+ // Map insertion order is creation order; values independently rank activity.
338
+ for (const session of sessions)
339
+ controller.#discovered.set(session.id, 0);
340
+ for (const session of [...sessions].sort((a, b) => a.lastActivityAt.localeCompare(b.lastActivityAt))) {
341
+ controller.#discovered.set(session.id, ++controller.#resourceRevision);
342
+ }
343
+ return controller;
344
+ }
345
+ async beginParentExecution(execution) {
346
+ if (this.#disposed)
347
+ throw new AgentError('MAR_AGENT_SUBAGENT_LIMIT', 'Subagent controller is disposed.');
348
+ this.#execution = execution;
349
+ this.#creationBudget = { count: 0 };
350
+ for (const state of this.#agents.values())
351
+ await this.#publishTerminal(state);
352
+ this.#releaseOldDetails();
353
+ }
354
+ /** A retained cell must not borrow a later model Execution's identity or task budget. */
355
+ captureExecution(executionId) {
356
+ const enter = this.captureParentFrame(executionId);
357
+ return {
358
+ run: (input, options) => enter(() => this.run(input, options)),
359
+ message: (id, message, options) => enter(() => this.message(id, message, options)),
360
+ output: (id, options) => this.output(id, options),
361
+ outputAny: (options) => this.outputAny(options),
362
+ outputMany: (ids, options) => this.outputMany(ids, options),
363
+ cancel: (id) => this.cancel(id),
364
+ listSessionResources: () => this.listSessionResources(),
365
+ dispose: () => this.dispose()
366
+ };
367
+ }
368
+ /** SDK physical tool ingress shares the same captured parent as its model controls. */
369
+ captureParentFrame(executionId) {
370
+ const execution = executionId === undefined ? this.#requireExecution() : this.#execution;
371
+ if (!execution || (executionId !== undefined && execution.executionId !== executionId))
372
+ throw new AgentError('MAR_AGENT_SUBAGENT_FAILED', 'Parent Execution source is unavailable.');
373
+ const context = (executionId === undefined
374
+ ? this.#retainedExecution.getStore()
375
+ : undefined) ?? {
376
+ execution,
377
+ budget: this.#creationBudget
378
+ };
379
+ return (run) => this.#retainedExecution.run(context, run);
380
+ }
381
+ withOperation(operation, run) {
382
+ operation.signal.throwIfAborted();
383
+ if (!operation.operationId.trim())
384
+ throw new AgentError('MAR_AGENT_SUBAGENT_FAILED', 'Parent operation identity is invalid.');
385
+ return this.#retainedExecution.run({ execution: operation, budget: { count: 0 }, native: true }, run);
386
+ }
387
+ async inspect(agentId) {
388
+ return this.#using([agentId], async () => {
389
+ return this.#snapshot(await this.#find(agentId), { full: true });
390
+ });
391
+ }
392
+ inspectAll() {
393
+ if (this.#disposed)
394
+ throw new AgentError('MAR_AGENT_DISPOSED', 'Subagent controller is disposed.');
395
+ return this.#orderedStates().map((state) => this.#snapshot(state, { full: true }));
396
+ }
397
+ async list(signal) {
398
+ return this.#using(undefined, async () => {
399
+ await this.prepareAll(signal);
400
+ return this.inspectAll();
401
+ });
402
+ }
403
+ /** Full listing is explicit; ordinary opens and executions never require it. */
404
+ async prepareAll(signal) {
405
+ for (const id of this.#discovered.keys()) {
406
+ signal?.throwIfAborted();
407
+ await this.#restoreDiscovered(id);
408
+ }
409
+ signal?.throwIfAborted();
410
+ }
411
+ async prepareSessionResources(signal) {
412
+ const candidates = [...this.#discovered]
413
+ .filter(([id]) => {
414
+ const state = this.#agents.get(id);
415
+ return !state || isTerminalState(state);
416
+ })
417
+ .sort(([a, ar], [b, br]) => (this.#agents.get(b)?.resourceRevision ?? br) -
418
+ (this.#agents.get(a)?.resourceRevision ?? ar));
419
+ let prepared = 0;
420
+ for (const [id] of candidates) {
421
+ signal?.throwIfAborted();
422
+ const state = await this.#restoreDiscovered(id);
423
+ if (state && isTerminalState(state) && ++prepared === RECENT_TERMINAL_RESOURCE_LIMIT)
424
+ break;
425
+ }
426
+ signal?.throwIfAborted();
427
+ this.#releaseOldDetails();
428
+ }
429
+ async #restoreDiscovered(agentId) {
430
+ try {
431
+ return await this.#find(agentId);
432
+ }
433
+ catch (error) {
434
+ if (!(error instanceof AgentError) || error.code !== 'MAR_AGENT_SUBAGENT_NOT_FOUND')
435
+ throw error;
436
+ this.#discovered.delete(agentId);
437
+ return undefined;
438
+ }
439
+ }
440
+ #orderedStates() {
441
+ return [...this.#discovered.keys()].flatMap((id) => {
442
+ const state = this.#agents.get(id);
443
+ return state ? [state] : [];
444
+ });
445
+ }
446
+ collectModelUpdates() {
447
+ return [...this.#agents.values()]
448
+ .filter((state) => state.messageRevision > state.observedMessageRevision ||
449
+ (isTerminalState(state) &&
450
+ state.terminalRevision !== undefined &&
451
+ state.terminalRevision > state.observedTerminalRevision))
452
+ .sort((left, right) => left.resourceRevision - right.resourceRevision)
453
+ .slice(0, SUBAGENT_LIMITS.agentWaitMaxAgents)
454
+ .map((state) => {
455
+ const messageRevision = state.messageRevision;
456
+ const terminalRevision = isTerminalState(state) ? state.terminalRevision : undefined;
457
+ const includeTerminalDetails = terminalRevision !== undefined && terminalRevision > state.observedTerminalRevision;
458
+ const snapshot = this.#snapshot(state, {
459
+ includeLatestMessage: messageRevision > state.observedMessageRevision,
460
+ includeTerminalDetails,
461
+ full: false
462
+ });
463
+ return {
464
+ snapshot,
465
+ truncated: snapshot.latestMessage?.truncated === true ||
466
+ (includeTerminalDetails &&
467
+ (snapshot.summary !== state.summary ||
468
+ (snapshot.changedFiles?.length ?? 0) < state.changedFiles.length)),
469
+ acknowledge: () => {
470
+ state.acknowledgeMessage(messageRevision);
471
+ if (includeTerminalDetails)
472
+ state.acknowledgeTerminal(terminalRevision);
473
+ }
474
+ };
475
+ });
476
+ }
477
+ async cancelOwned(ownerInstanceId) {
478
+ for (const pending of this.#pendingDeliveries)
479
+ if (pending.ownerInstanceId === ownerInstanceId)
480
+ pending.delivery.settled?.('cancelled');
481
+ const results = await Promise.allSettled([...this.#agents.values()]
482
+ .filter((state) => state.turn?.ownerInstanceId === ownerInstanceId)
483
+ .map((state) => this.#control(state, async () => {
484
+ if (state.turn?.ownerInstanceId === ownerInstanceId)
485
+ await this.#cancelState(state);
486
+ })));
487
+ const failure = results.find((result) => result.status === 'rejected');
488
+ this.#nativeObservations.delete(ownerInstanceId);
489
+ if (failure?.status === 'rejected')
490
+ throw failure.reason;
491
+ }
492
+ endParentExecution(executionId) {
493
+ if (this.#execution?.executionId === executionId)
494
+ this.#execution = undefined;
495
+ }
496
+ parentExecution(executionId) {
497
+ const execution = this.#retainedExecution.getStore()?.execution ?? this.#execution;
498
+ return execution?.executionId === executionId ? { ...execution, executionId } : undefined;
499
+ }
500
+ async run(input, options = {}) {
501
+ options.signal?.throwIfAborted();
502
+ options.turnSignal?.throwIfAborted();
503
+ if (options.waitFor !== undefined &&
504
+ options.waitFor !== 'start' &&
505
+ options.waitFor !== 'completion')
506
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Task start wait is invalid.');
507
+ const execution = this.#requireExecution();
508
+ const native = this.#retainedExecution.getStore()?.native === true;
509
+ validateTaskInput(input, native);
510
+ if (!native &&
511
+ (this.#retainedExecution.getStore()?.budget ?? this.#creationBudget).count >=
512
+ this.limits.maxTasks)
513
+ throw new AgentError('MAR_AGENT_SUBAGENT_LIMIT', 'Subagent task limit was reached.');
514
+ const source = {
515
+ type: 'subagent',
516
+ parentSessionId: this.parentSessionId,
517
+ rootSessionId: this.rootSessionId,
518
+ ...(execution.executionId === undefined ? {} : { parentExecutionId: execution.executionId }),
519
+ ...(native && 'operationId' in execution
520
+ ? {
521
+ parentOperationId: execution.operationId,
522
+ ...(execution.ownerInstanceId === undefined
523
+ ? {}
524
+ : { ownerInstanceId: execution.ownerInstanceId }),
525
+ ...(execution.extensionId === undefined ? {} : { extensionId: execution.extensionId })
526
+ }
527
+ : {}),
528
+ role: input.role,
529
+ description: input.description.trim()
530
+ };
531
+ const created = await this.backend.createSession({
532
+ title: input.description.trim(),
533
+ source
534
+ });
535
+ try {
536
+ if (this.#disposed)
537
+ throw new AgentError('MAR_AGENT_DISPOSED', 'Subagent controller is disposed.');
538
+ this.#requireExecution();
539
+ options.signal?.throwIfAborted();
540
+ options.turnSignal?.throwIfAborted();
541
+ }
542
+ catch (error) {
543
+ await this.#deleteUnstartedSession(created.id, error);
544
+ }
545
+ return this.#using([created.id], async () => {
546
+ const state = new SubagentTask({
547
+ agentId: created.id,
548
+ description: source.description,
549
+ role: input.role,
550
+ ...(source.ownerInstanceId === undefined
551
+ ? {}
552
+ : { ownerInstanceId: source.ownerInstanceId }),
553
+ ...(source.extensionId === undefined ? {} : { extensionId: source.extensionId }),
554
+ status: 'queued',
555
+ messageRevision: 0,
556
+ observedMessageRevision: 0,
557
+ latestMessageActivityRevision: 0,
558
+ changedFiles: [],
559
+ verification: [],
560
+ evidence: [],
561
+ terminalPending: false,
562
+ observedTerminalRevision: -1,
563
+ resourceRevision: ++this.#resourceRevision
564
+ });
565
+ if (!native)
566
+ (this.#retainedExecution.getStore()?.budget ?? this.#creationBudget).count++;
567
+ this.#agents.set(state.agentId, state);
568
+ this.#discovered.set(state.agentId, state.resourceRevision);
569
+ const knownModel = execution.models.get(input.modelId ?? execution.modelId);
570
+ if (knownModel) {
571
+ state.selectModel(knownModel);
572
+ }
573
+ try {
574
+ const selected = resolveModel(execution, input);
575
+ state.selectModel(selected);
576
+ }
577
+ catch (error) {
578
+ this.#setFailure(state, error);
579
+ }
580
+ try {
581
+ await options.onCreated?.(this.#receiptSnapshot(state));
582
+ if (this.#disposed)
583
+ throw new AgentError('MAR_AGENT_DISPOSED', 'Subagent controller is disposed.');
584
+ this.#requireExecution();
585
+ options.signal?.throwIfAborted();
586
+ }
587
+ catch (error) {
588
+ await this.#deleteUnstartedSession(state.agentId, error);
589
+ }
590
+ if (state.status === 'failed') {
591
+ await this.#publishTerminal(state);
592
+ this.#observeTerminal(state);
593
+ return this.#snapshot(state);
594
+ }
595
+ this.#queueTurn(state, input.prompt, execution, [], undefined, undefined, options.signal, options.turnSignal);
596
+ if (options.waitFor === 'start' || (options.waitFor === undefined && input.background))
597
+ return this.#receiptSnapshot(state);
598
+ await waitForPromise(state.turn.completion, options.signal);
599
+ const includeLatestMessage = this.#hasUnreadMessage(state);
600
+ const includeTerminalDetails = this.#observeTerminal(state);
601
+ this.#observeLatestMessage(state);
602
+ return this.#snapshot(state, { includeLatestMessage, includeTerminalDetails });
603
+ });
604
+ }
605
+ async output(agentId, options = {}) {
606
+ return this.#using([agentId], async () => {
607
+ options.signal?.throwIfAborted();
608
+ const state = await this.#find(agentId);
609
+ options.signal?.throwIfAborted();
610
+ validateOutputOptions(options, this.#retainedExecution.getStore()?.native === true);
611
+ if (options.untilSettled) {
612
+ if (state.turn)
613
+ await waitForPromise(state.turn.completion, options.signal);
614
+ options.signal?.throwIfAborted();
615
+ const includeLatestMessage = this.#hasUnreadMessage(state);
616
+ const includeTerminalDetails = this.#observeTerminal(state);
617
+ this.#observeLatestMessage(state);
618
+ return {
619
+ ...this.#snapshot(state, { includeLatestMessage, includeTerminalDetails }),
620
+ waitOutcome: 'completion'
621
+ };
622
+ }
623
+ if (options.waitMs === undefined || options.waitMs === 0)
624
+ return {
625
+ ...this.#snapshot(state, {
626
+ includeLatestMessage: false,
627
+ includeTerminalDetails: false
628
+ }),
629
+ waitOutcome: 'snapshot'
630
+ };
631
+ if (isTerminalState(state)) {
632
+ const includeLatestMessage = this.#hasUnreadMessage(state);
633
+ const includeTerminalDetails = this.#observeTerminal(state);
634
+ this.#observeLatestMessage(state);
635
+ return {
636
+ ...this.#snapshot(state, { includeLatestMessage, includeTerminalDetails }),
637
+ waitOutcome: 'completion'
638
+ };
639
+ }
640
+ const waitFor = options.waitFor ?? 'completion';
641
+ if (waitFor === 'message' && this.#hasUnreadMessage(state)) {
642
+ this.#observeLatestMessage(state);
643
+ return { ...this.#snapshot(state), waitOutcome: 'message' };
644
+ }
645
+ const waitMs = this.#retainedExecution.getStore()?.native
646
+ ? options.waitMs
647
+ : Math.max(options.waitMs, SUBAGENT_LIMITS.agentWaitWaitFloorMs);
648
+ if (waitFor === 'completion') {
649
+ const completed = await this.#waitForCompletion(state, waitMs, options.signal, options.waitInterrupt);
650
+ options.signal?.throwIfAborted();
651
+ const includeLatestMessage = this.#hasUnreadMessage(state);
652
+ const includeTerminalDetails = completed ? this.#observeTerminal(state) : false;
653
+ if (includeLatestMessage)
654
+ this.#observeLatestMessage(state);
655
+ return {
656
+ ...this.#snapshot(state, { includeLatestMessage, includeTerminalDetails }),
657
+ ...waitMetadata(completed ? 'completion' : options.waitInterrupt?.pending() ? 'interrupted' : 'timeout')
658
+ };
659
+ }
660
+ const activity = await this.#waitForMessageOrCompletion([state], waitMs, options.signal, options.waitInterrupt);
661
+ options.signal?.throwIfAborted();
662
+ const includeLatestMessage = activity?.kind === 'message' ||
663
+ (activity?.kind === 'completion' && this.#hasUnreadMessage(activity.state));
664
+ const includeTerminalDetails = activity?.kind === 'completion' ? this.#observeTerminal(activity.state) : false;
665
+ if (activity)
666
+ this.#observeLatestMessage(activity.state);
667
+ return {
668
+ ...this.#snapshot(activity?.state ?? state, {
669
+ includeLatestMessage,
670
+ includeTerminalDetails
671
+ }),
672
+ ...waitMetadata(activity?.kind ?? (options.waitInterrupt?.pending() ? 'interrupted' : 'timeout'))
673
+ };
674
+ });
675
+ }
676
+ async outputAny(options = {}) {
677
+ return this.#using(undefined, async () => {
678
+ options.signal?.throwIfAborted();
679
+ if (options.untilSettled)
680
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'An unbounded wait requires an agent id.');
681
+ validateOutputOptions(options, this.#retainedExecution.getStore()?.native === true);
682
+ const hasLive = [...this.#agents.values()].some((state) => !isTerminalState(state));
683
+ if (!hasLive) {
684
+ for (const id of [...this.#discovered.keys()].reverse()) {
685
+ options.signal?.throwIfAborted();
686
+ if (await this.#restoreDiscovered(id))
687
+ break;
688
+ }
689
+ }
690
+ options.signal?.throwIfAborted();
691
+ const states = this.#orderedStates();
692
+ if (states.length === 0)
693
+ throw new AgentError('MAR_AGENT_SUBAGENT_NOT_FOUND', 'Subagent was not found.');
694
+ const live = states.filter((state) => state.status === 'queued' || state.status === 'running');
695
+ if (options.waitMs === undefined || options.waitMs === 0)
696
+ return {
697
+ ...this.#snapshot(live.at(-1) ?? states.at(-1), {
698
+ includeLatestMessage: false,
699
+ includeTerminalDetails: false
700
+ }),
701
+ waitOutcome: 'snapshot'
702
+ };
703
+ if (live.length === 0) {
704
+ const state = states.at(-1);
705
+ const includeLatestMessage = this.#hasUnreadMessage(state);
706
+ const includeTerminalDetails = this.#observeTerminal(state);
707
+ this.#observeLatestMessage(state);
708
+ return {
709
+ ...this.#snapshot(state, { includeLatestMessage, includeTerminalDetails }),
710
+ waitOutcome: 'completion'
711
+ };
712
+ }
713
+ const waitFor = options.waitFor ?? 'completion';
714
+ if (waitFor === 'message') {
715
+ const pending = this.#oldestUnreadMessage(live);
716
+ if (pending) {
717
+ this.#observeLatestMessage(pending);
718
+ return { ...this.#snapshot(pending), waitOutcome: 'message' };
719
+ }
720
+ }
721
+ const waitMs = this.#retainedExecution.getStore()?.native
722
+ ? options.waitMs
723
+ : Math.max(options.waitMs, SUBAGENT_LIMITS.agentWaitWaitFloorMs);
724
+ if (waitFor === 'message') {
725
+ const activity = await this.#waitForMessageOrCompletion(live, waitMs, options.signal, options.waitInterrupt);
726
+ options.signal?.throwIfAborted();
727
+ const includeLatestMessage = activity?.kind === 'message' ||
728
+ (activity?.kind === 'completion' && this.#hasUnreadMessage(activity.state));
729
+ const includeTerminalDetails = activity?.kind === 'completion' ? this.#observeTerminal(activity.state) : false;
730
+ if (activity)
731
+ this.#observeLatestMessage(activity.state);
732
+ return {
733
+ ...this.#snapshot(activity?.state ?? live.at(-1), {
734
+ includeLatestMessage,
735
+ includeTerminalDetails
736
+ }),
737
+ ...waitMetadata(activity?.kind ?? (options.waitInterrupt?.pending() ? 'interrupted' : 'timeout'))
738
+ };
739
+ }
740
+ const completed = await this.#waitForAnyCompletion(live, waitMs, options.signal, options.waitInterrupt);
741
+ options.signal?.throwIfAborted();
742
+ const state = completed ?? this.#oldestUnreadMessage(live) ?? live.at(-1);
743
+ const includeLatestMessage = this.#hasUnreadMessage(state);
744
+ const includeTerminalDetails = completed ? this.#observeTerminal(state) : false;
745
+ if (includeLatestMessage)
746
+ this.#observeLatestMessage(state);
747
+ return {
748
+ ...this.#snapshot(state, {
749
+ includeLatestMessage,
750
+ includeTerminalDetails
751
+ }),
752
+ ...waitMetadata(completed ? 'completion' : options.waitInterrupt?.pending() ? 'interrupted' : 'timeout')
753
+ };
754
+ });
755
+ }
756
+ async outputMany(agentIds, options = {}) {
757
+ options.signal?.throwIfAborted();
758
+ const { agentIds: ids, mode = 'any' } = parseAgentWaitTargets({ agentIds, mode: options.mode }, this.#retainedExecution.getStore()?.native ? Infinity : SUBAGENT_LIMITS.agentWaitMaxAgents);
759
+ validateOutputOptions(options, this.#retainedExecution.getStore()?.native === true);
760
+ if (!ids || 'untilSettled' in options)
761
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Group waits require a bounded deadline.');
762
+ return this.#using(ids, async () => {
763
+ const states = await Promise.all(ids.map((id) => this.#find(id)));
764
+ options.signal?.throwIfAborted();
765
+ const waitFor = options.waitFor ?? 'completion';
766
+ const targets = states.map((state) => ({
767
+ state,
768
+ turn: state.turn,
769
+ view: copyWaitState(state),
770
+ observation: this.#nativeObservation(state)
771
+ }));
772
+ const refresh = () => {
773
+ for (const target of targets) {
774
+ if (!isTerminalState(target.view) &&
775
+ (target.state.turn === target.turn ||
776
+ (target.state.turn === undefined && isTerminalState(target.state))))
777
+ target.view = copyWaitState(target.state);
778
+ }
779
+ };
780
+ const unread = (target) => target.view.messageRevision >
781
+ (target.observation?.messageRevision ?? target.state.observedMessageRevision);
782
+ const ready = (target) => isTerminalState(target.view) || (waitFor === 'message' && unread(target));
783
+ const { snapshot, satisfied } = await waitForAgentGroup({
784
+ targets,
785
+ mode,
786
+ refresh,
787
+ ready,
788
+ waitMs: options.waitMs === undefined ||
789
+ options.waitMs === 0 ||
790
+ this.#retainedExecution.getStore()?.native
791
+ ? options.waitMs
792
+ : Math.max(options.waitMs, SUBAGENT_LIMITS.agentWaitWaitFloorMs),
793
+ signal: options.signal,
794
+ interrupt: options.waitInterrupt,
795
+ subscribe: (notify) => {
796
+ const listener = () => notify();
797
+ return this.#waiters.subscribeActivity(listener);
798
+ }
799
+ });
800
+ const pendingAgentIds = targets
801
+ .filter((target) => !ready(target))
802
+ .map((target) => target.state.agentId);
803
+ const agents = targets.map((target) => {
804
+ const { state, view, observation } = target;
805
+ const terminal = isTerminalState(view);
806
+ const outcome = snapshot
807
+ ? 'snapshot'
808
+ : terminal
809
+ ? 'completion'
810
+ : ready(target)
811
+ ? 'message'
812
+ : satisfied
813
+ ? 'snapshot'
814
+ : options.waitInterrupt?.pending()
815
+ ? 'interrupted'
816
+ : 'timeout';
817
+ const includeLatestMessage = outcome !== 'snapshot' && unread(target);
818
+ const includeTerminalDetails = outcome === 'completion' &&
819
+ (observation
820
+ ? observation.terminalRevision < view.resourceRevision
821
+ : state.observedTerminalRevision < view.resourceRevision);
822
+ const result = {
823
+ ...this.#snapshot(view, { includeLatestMessage, includeTerminalDetails }),
824
+ ...(target.turn === undefined ? {} : { turnId: target.turn.turnId }),
825
+ ...waitMetadata(outcome)
826
+ };
827
+ if (includeLatestMessage) {
828
+ if (observation)
829
+ observation.messageRevision = Math.max(observation.messageRevision, view.messageRevision);
830
+ else
831
+ state.acknowledgeMessage(view.messageRevision);
832
+ }
833
+ if (includeTerminalDetails) {
834
+ if (observation)
835
+ observation.terminalRevision = Math.max(observation.terminalRevision, view.resourceRevision);
836
+ else
837
+ state.acknowledgeTerminal(view.resourceRevision);
838
+ }
839
+ return result;
840
+ });
841
+ return {
842
+ mode,
843
+ waitFor,
844
+ agents,
845
+ pendingAgentIds,
846
+ ...waitMetadata(snapshot
847
+ ? 'snapshot'
848
+ : !satisfied
849
+ ? options.waitInterrupt?.pending()
850
+ ? 'interrupted'
851
+ : 'timeout'
852
+ : agents.some((agent) => agent.waitOutcome === 'message')
853
+ ? 'message'
854
+ : 'completion')
855
+ };
856
+ });
857
+ }
858
+ async message(agentId, message, options = {}) {
859
+ return this.#using([agentId], async () => {
860
+ const execution = this.#requireExecution();
861
+ if (typeof message !== 'string' ||
862
+ message.trim().length === 0 ||
863
+ (this.#retainedExecution.getStore()?.native !== true &&
864
+ Buffer.byteLength(message) > SUBAGENT_LIMITS.subagentMessageMaxBytes) ||
865
+ (options.delivery !== undefined &&
866
+ options.delivery !== 'append' &&
867
+ options.delivery !== 'replace'))
868
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Agent message input is invalid.');
869
+ const state = await this.#find(agentId);
870
+ return this.#control(state, async () => {
871
+ this.#requireExecution();
872
+ options.signal?.throwIfAborted();
873
+ // Resolve before cancelling so an unavailable model does not stop valid work.
874
+ const selected = resolveExistingModel(execution, state);
875
+ if (options.delivery === 'replace')
876
+ await this.#cancelState(state);
877
+ this.#requireExecution();
878
+ options.signal?.throwIfAborted();
879
+ const turnId = state.turn?.turnId ?? randomUUID();
880
+ const receipt = { messageId: randomUUID(), turnId, deliveryStatus: 'accepted' };
881
+ const mutableReceipt = receipt;
882
+ const delivery = this.#createDelivery(state, execution, mutableReceipt, options.signal);
883
+ try {
884
+ if (state.status === 'running' && state.turn) {
885
+ const turn = state.turn;
886
+ const sendSignal = delivery.signal && options.signal
887
+ ? AbortSignal.any([delivery.signal, options.signal])
888
+ : (delivery.signal ?? options.signal);
889
+ if (!turn.handle)
890
+ await waitForPromise(turn.handleReady, sendSignal);
891
+ this.#requireExecution();
892
+ options.signal?.throwIfAborted();
893
+ delivery.signal?.throwIfAborted();
894
+ if (state.status === 'running' &&
895
+ state.turn === turn &&
896
+ turn.handle?.enqueueMessage(message, delivery)) {
897
+ delivery.accepted();
898
+ state.setReceipt(mutableReceipt);
899
+ return this.#messageReceiptSnapshot(state);
900
+ }
901
+ await waitForPromise(turn.completion, sendSignal);
902
+ }
903
+ else if (state.status === 'queued' && state.turn) {
904
+ delivery.accepted();
905
+ state.appendMessage({ text: message, delivery });
906
+ state.setReceipt(mutableReceipt);
907
+ return this.#messageReceiptSnapshot(state);
908
+ }
909
+ this.#requireExecution();
910
+ options.signal?.throwIfAborted();
911
+ delivery.signal?.throwIfAborted();
912
+ state.selectModel(selected);
913
+ // A closing turn may have rejected append; reserve a fresh identity for its successor.
914
+ mutableReceipt.turnId = randomUUID();
915
+ delivery.accepted();
916
+ state.setReceipt(mutableReceipt);
917
+ this.#queueTurn(state, message, execution, [], mutableReceipt.turnId, delivery, options.signal);
918
+ return this.#messageReceiptSnapshot(state);
919
+ }
920
+ catch (error) {
921
+ delivery.settled?.(options.signal?.aborted || ('signal' in execution && execution.signal.aborted)
922
+ ? 'cancelled'
923
+ : 'failed');
924
+ throw error;
925
+ }
926
+ });
927
+ });
928
+ }
929
+ async cancel(agentId) {
930
+ return this.#using([agentId], async () => {
931
+ const state = await this.#find(agentId);
932
+ await this.#control(state, () => this.#cancelState(state));
933
+ const includeLatestMessage = this.#hasUnreadMessage(state);
934
+ const includeTerminalDetails = this.#observeTerminal(state);
935
+ this.#observeLatestMessage(state);
936
+ return this.#snapshot(state, { includeLatestMessage, includeTerminalDetails });
937
+ });
938
+ }
939
+ #control(state, operation) {
940
+ return state.control(operation);
941
+ }
942
+ async #cancelState(state) {
943
+ if (state.status === 'queued' && state.turn) {
944
+ const turn = state.turn;
945
+ const index = this.#queue.indexOf(state);
946
+ if (index >= 0)
947
+ this.#queue.splice(index, 1);
948
+ state.cancelQueued(true);
949
+ this.#touchResource(state, true);
950
+ this.#closeReceipt(state);
951
+ await this.#publishTerminal(state);
952
+ state.settleHandleReady(turn);
953
+ state.settleCompletion(turn);
954
+ this.#notifyCompletion(state);
955
+ state.clearTurn(turn);
956
+ this.#drain();
957
+ }
958
+ else if (state.status === 'running' && state.turn) {
959
+ const turn = state.turn;
960
+ const needsHandle = !turn.handle;
961
+ state.requestCancel(turn);
962
+ if (needsHandle) {
963
+ await turn.handleReady;
964
+ }
965
+ await turn.completion;
966
+ }
967
+ }
968
+ listSessionResources() {
969
+ const states = [...this.#agents.values()];
970
+ const active = states
971
+ .filter((state) => state.status === 'queued' || state.status === 'running')
972
+ .sort((left, right) => right.resourceRevision - left.resourceRevision);
973
+ const terminal = states
974
+ .filter((state) => state.status !== 'queued' && state.status !== 'running')
975
+ .sort((left, right) => right.resourceRevision - left.resourceRevision)
976
+ .slice(0, RECENT_TERMINAL_RESOURCE_LIMIT);
977
+ return [...active, ...terminal].map((state) => ({
978
+ agentId: state.agentId,
979
+ status: state.status,
980
+ description: state.description
981
+ }));
982
+ }
983
+ async dispose() {
984
+ if (this.#disposed)
985
+ return;
986
+ this.#disposed = true;
987
+ for (const pending of this.#pendingDeliveries)
988
+ pending.delivery.settled?.('cancelled');
989
+ for (const state of this.#queue.splice(0)) {
990
+ const turn = state.turn;
991
+ state.cancelQueued(false);
992
+ this.#closeReceipt(state);
993
+ if (turn) {
994
+ state.settleHandleReady(turn);
995
+ state.settleCompletion(turn);
996
+ }
997
+ this.#notifyCompletion(state);
998
+ if (turn)
999
+ state.clearTurn(turn);
1000
+ }
1001
+ for (const state of this.#agents.values()) {
1002
+ if (state.status !== 'running' || !state.turn)
1003
+ continue;
1004
+ state.requestCancel(state.turn);
1005
+ }
1006
+ await Promise.allSettled([...this.#agents.values()].flatMap((state) => state.turn === undefined ? [] : [state.turn.completion]));
1007
+ this.#execution = undefined;
1008
+ this.#nativeObservations.clear();
1009
+ }
1010
+ #queueTurn(state, prompt, execution, pendingMessages, turnId = randomUUID(), delivery, signal, turnSignal) {
1011
+ const native = this.#retainedExecution.getStore()?.native === true && 'operationId' in execution
1012
+ ? execution
1013
+ : undefined;
1014
+ const sourceSignal = turnSignal ??
1015
+ (native === undefined
1016
+ ? undefined
1017
+ : signal === undefined
1018
+ ? native.signal
1019
+ : AbortSignal.any([native.signal, signal]));
1020
+ this.#touchResource(state);
1021
+ let turn;
1022
+ const abort = () => {
1023
+ void this.#control(state, async () => {
1024
+ if (state.turn === turn)
1025
+ await this.#cancelState(state);
1026
+ }).catch(() => undefined);
1027
+ };
1028
+ turn = state.queueTurn({
1029
+ turnId,
1030
+ ...(native?.ownerInstanceId === undefined
1031
+ ? {}
1032
+ : { ownerInstanceId: native.ownerInstanceId }),
1033
+ ...(native?.origin === undefined
1034
+ ? {}
1035
+ : { origin: Object.freeze({ ...native.origin, signal: sourceSignal }) }),
1036
+ ...(delivery === undefined ? {} : { delivery }),
1037
+ prompt,
1038
+ start: execution.startTurn,
1039
+ pendingMessages
1040
+ }, () => sourceSignal?.removeEventListener('abort', abort));
1041
+ sourceSignal?.addEventListener('abort', abort, { once: true });
1042
+ this.#queue.push(state);
1043
+ this.#drain();
1044
+ if (sourceSignal?.aborted)
1045
+ abort();
1046
+ }
1047
+ #drain() {
1048
+ while (!this.#disposed && this.#running < this.limits.maxConcurrent && this.#queue.length > 0) {
1049
+ const state = this.#queue.shift();
1050
+ const turn = state.turn;
1051
+ if (!turn || state.status !== 'queued')
1052
+ continue;
1053
+ state.markRunning();
1054
+ this.#touchResource(state);
1055
+ this.#running++;
1056
+ void this.#startAndConsumeTurn(state, turn);
1057
+ }
1058
+ }
1059
+ async #startAndConsumeTurn(state, turn) {
1060
+ try {
1061
+ const handle = await turn.start({
1062
+ turnId: turn.turnId,
1063
+ ...(turn.delivery === undefined ? {} : { delivery: turn.delivery }),
1064
+ ...(turn.origin === undefined ? {} : { origin: turn.origin }),
1065
+ sessionId: state.agentId,
1066
+ prompt: turn.prompt,
1067
+ modelId: state.modelId,
1068
+ reasoningEffort: state.reasoningEffort,
1069
+ role: state.role,
1070
+ initialMailbox: state.takePendingMessages(turn)
1071
+ });
1072
+ state.attachHandle(turn, handle);
1073
+ }
1074
+ catch (error) {
1075
+ state.settleHandleReady(turn);
1076
+ await this.#failTurn(state, turn, error);
1077
+ return;
1078
+ }
1079
+ state.cancelPending(turn);
1080
+ state.settleHandleReady(turn);
1081
+ await this.#consumeTurn(state, turn);
1082
+ }
1083
+ async #consumeTurn(state, turn) {
1084
+ const previousActivity = state.latestActivity;
1085
+ const previousMessageRevision = state.messageRevision;
1086
+ let terminal;
1087
+ try {
1088
+ const consume = (async () => {
1089
+ for await (const event of turn.handle) {
1090
+ if (event.type === 'execution.completed')
1091
+ terminal = 'completed';
1092
+ else if (event.type === 'execution.failed')
1093
+ terminal = 'failed';
1094
+ else if (event.type === 'execution.cancelled')
1095
+ terminal = 'cancelled';
1096
+ if (!state.observeEvent(event, this.#activityRevision + 1))
1097
+ continue;
1098
+ this.#activityRevision++;
1099
+ this.#touchResource(state);
1100
+ this.#notifyActivity({ state, kind: 'message' });
1101
+ }
1102
+ })();
1103
+ const [resultOutcome, consumeOutcome] = await Promise.allSettled([
1104
+ Promise.resolve().then(() => turn.handle.result()),
1105
+ consume
1106
+ ]);
1107
+ if (resultOutcome.status === 'rejected')
1108
+ throw resultOutcome.reason;
1109
+ if (consumeOutcome.status === 'rejected')
1110
+ throw consumeOutcome.reason;
1111
+ const result = resultOutcome.value;
1112
+ state.complete(result, terminal, turn.handle.persistedEvents === true, previousActivity, previousMessageRevision);
1113
+ this.#touchResource(state, true);
1114
+ this.#closeReceipt(state);
1115
+ await this.#publishTerminal(state);
1116
+ }
1117
+ catch (error) {
1118
+ this.#setFailure(state, error);
1119
+ this.#closeReceipt(state);
1120
+ await this.#publishTerminal(state);
1121
+ }
1122
+ finally {
1123
+ this.#closeReceipt(state);
1124
+ this.#running--;
1125
+ state.settleCompletion(turn);
1126
+ this.#notifyCompletion(state);
1127
+ state.clearTurn(turn);
1128
+ this.#drain();
1129
+ }
1130
+ }
1131
+ async #failTurn(state, turn, error) {
1132
+ this.#setFailure(state, error);
1133
+ this.#closeReceipt(state);
1134
+ this.#running--;
1135
+ state.settleCompletion(turn);
1136
+ state.clearTurn(turn);
1137
+ this.#notifyCompletion(state);
1138
+ await this.#publishTerminal(state);
1139
+ this.#drain();
1140
+ }
1141
+ #setFailure(state, error) {
1142
+ state.fail(error);
1143
+ this.#touchResource(state, true);
1144
+ }
1145
+ #touchResource(state, terminal = false) {
1146
+ state.touch(++this.#resourceRevision, terminal);
1147
+ }
1148
+ #waitForAnyCompletion(candidates, waitMs, signal, interrupt) {
1149
+ return this.#waiters.waitCompletion((state) => candidates.includes(state), () => candidates.find(isTerminalState), waitMs, signal, interrupt);
1150
+ }
1151
+ #waitForCompletion(state, waitMs, signal, interrupt) {
1152
+ return this.#waiters.waitCompletion((completed) => completed === state, () => (isTerminalState(state) ? state : undefined), waitMs, signal, interrupt);
1153
+ }
1154
+ #notifyCompletion(state) {
1155
+ this.#waiters.notifyCompletion(state);
1156
+ this.#notifyActivity({ state, kind: 'completion' });
1157
+ }
1158
+ #waitForMessageOrCompletion(candidates, waitMs, signal, interrupt) {
1159
+ return this.#waiters.waitActivity((activity) => candidates.includes(activity.state), () => {
1160
+ const pending = this.#oldestUnreadMessage(candidates);
1161
+ if (pending)
1162
+ return { state: pending, kind: 'message' };
1163
+ const terminal = candidates.find(isTerminalState);
1164
+ return terminal ? { state: terminal, kind: 'completion' } : undefined;
1165
+ }, waitMs, signal, interrupt);
1166
+ }
1167
+ #notifyActivity(activity) {
1168
+ this.#waiters.notifyActivity(activity);
1169
+ }
1170
+ #hasUnreadMessage(state) {
1171
+ return (state.messageRevision >
1172
+ (this.#nativeObservation(state)?.messageRevision ?? state.observedMessageRevision));
1173
+ }
1174
+ #nativeObservation(state) {
1175
+ const context = this.#retainedExecution.getStore();
1176
+ if (!context?.native || !('operationId' in context.execution))
1177
+ return undefined;
1178
+ const owner = context.execution.ownerInstanceId ?? context.execution.operationId;
1179
+ let observations = this.#nativeObservations.get(owner);
1180
+ if (!observations)
1181
+ this.#nativeObservations.set(owner, (observations = new Map()));
1182
+ let observation = observations.get(state.agentId);
1183
+ if (!observation)
1184
+ observations.set(state.agentId, (observation = { messageRevision: 0, terminalRevision: 0 }));
1185
+ return observation;
1186
+ }
1187
+ #oldestUnreadMessage(states) {
1188
+ return states
1189
+ .filter((state) => this.#hasUnreadMessage(state))
1190
+ .sort((left, right) => left.latestMessageActivityRevision - right.latestMessageActivityRevision)
1191
+ .at(0);
1192
+ }
1193
+ #observeLatestMessage(state) {
1194
+ const native = this.#nativeObservation(state);
1195
+ if (native)
1196
+ native.messageRevision = state.messageRevision;
1197
+ else
1198
+ state.acknowledgeMessage(state.messageRevision);
1199
+ }
1200
+ #observeTerminal(state) {
1201
+ const native = this.#nativeObservation(state);
1202
+ if (native) {
1203
+ if (!isTerminalState(state) || native.terminalRevision === state.resourceRevision)
1204
+ return false;
1205
+ native.terminalRevision = state.resourceRevision;
1206
+ return true;
1207
+ }
1208
+ if (!isTerminalState(state) || state.observedTerminalRevision >= state.resourceRevision)
1209
+ return false;
1210
+ state.acknowledgeTerminal(state.resourceRevision);
1211
+ return true;
1212
+ }
1213
+ #createDelivery(state, execution, receipt, signal) {
1214
+ const native = this.#retainedExecution.getStore()?.native === true && 'operationId' in execution
1215
+ ? execution
1216
+ : undefined;
1217
+ const sourceSignal = native === undefined
1218
+ ? undefined
1219
+ : signal === undefined
1220
+ ? native.signal
1221
+ : AbortSignal.any([native.signal, signal]);
1222
+ const controller = new AbortController();
1223
+ const release = () => {
1224
+ sourceSignal?.removeEventListener('abort', abort);
1225
+ this.#pendingDeliveries.delete(pending);
1226
+ };
1227
+ const delivery = {
1228
+ accepted: () => {
1229
+ pending.admitted = true;
1230
+ },
1231
+ messageId: receipt.messageId,
1232
+ ...(native?.origin === undefined ? {} : { origin: native.origin }),
1233
+ ...(native === undefined ? {} : { signal: controller.signal }),
1234
+ applied: () => {
1235
+ // A durable commit remains applied even if cancellation races its completion callback.
1236
+ state.updateDelivery(receipt, 'applied');
1237
+ release();
1238
+ },
1239
+ settled: (status) => {
1240
+ if (!state.updateDelivery(receipt, status))
1241
+ return;
1242
+ controller.abort(new AgentError('MAR_AGENT_CANCELLED', 'Agent message was cancelled.'));
1243
+ release();
1244
+ }
1245
+ };
1246
+ const pending = {
1247
+ state,
1248
+ receipt,
1249
+ delivery,
1250
+ admitted: false,
1251
+ ...(native?.ownerInstanceId === undefined ? {} : { ownerInstanceId: native.ownerInstanceId })
1252
+ };
1253
+ const abort = () => delivery.settled?.('cancelled');
1254
+ this.#pendingDeliveries.add(pending);
1255
+ sourceSignal?.addEventListener('abort', abort, { once: true });
1256
+ if (sourceSignal?.aborted)
1257
+ abort();
1258
+ return delivery;
1259
+ }
1260
+ #closeReceipt(state) {
1261
+ for (const pending of this.#pendingDeliveries)
1262
+ if (pending.admitted &&
1263
+ pending.state === state &&
1264
+ pending.receipt.turnId === state.turn?.turnId)
1265
+ pending.delivery.settled?.(state.status === 'cancelled' ? 'cancelled' : 'failed');
1266
+ }
1267
+ async #deleteUnstartedSession(agentId, error) {
1268
+ this.#agents.delete(agentId);
1269
+ this.#discovered.delete(agentId);
1270
+ try {
1271
+ await this.backend.deleteSession(agentId);
1272
+ }
1273
+ catch (cleanupError) {
1274
+ const original = describeAgentError(error, 'MAR_AGENT_SUBAGENT_FAILED');
1275
+ const cleanup = describeAgentError(cleanupError, 'MAR_AGENT_SUBAGENT_FAILED');
1276
+ throw new AgentError(original.code, `${original.message} Cleanup also failed: ${cleanup.message}`, { cause: cleanupError });
1277
+ }
1278
+ throw error;
1279
+ }
1280
+ async #using(ids, operation) {
1281
+ if (ids === undefined)
1282
+ this.#allReaders++;
1283
+ else
1284
+ for (const id of ids)
1285
+ this.#readers.set(id, (this.#readers.get(id) ?? 0) + 1);
1286
+ try {
1287
+ return await operation();
1288
+ }
1289
+ finally {
1290
+ if (ids === undefined)
1291
+ this.#allReaders--;
1292
+ else
1293
+ for (const id of ids) {
1294
+ const count = this.#readers.get(id) - 1;
1295
+ if (count)
1296
+ this.#readers.set(id, count);
1297
+ else
1298
+ this.#readers.delete(id);
1299
+ }
1300
+ }
1301
+ }
1302
+ #releaseOldDetails() {
1303
+ if (this.#allReaders)
1304
+ return;
1305
+ const terminal = [...this.#agents.values()]
1306
+ .filter(isTerminalState)
1307
+ .sort((a, b) => b.resourceRevision - a.resourceRevision);
1308
+ for (const state of terminal.slice(RECENT_TERMINAL_RESOURCE_LIMIT)) {
1309
+ if (state.detailsEvicted ||
1310
+ !state.restorable ||
1311
+ state.turn ||
1312
+ state.controlTail ||
1313
+ this.#readers.has(state.agentId) ||
1314
+ this.#loading.has(state.agentId) ||
1315
+ state.terminalPending ||
1316
+ state.messageRevision > state.observedMessageRevision ||
1317
+ (state.terminalRevision !== undefined &&
1318
+ state.terminalRevision > state.observedTerminalRevision) ||
1319
+ [...this.#pendingDeliveries].some((pending) => pending.state === state))
1320
+ continue;
1321
+ // Keep identity and cursors for old acknowledgements; only the disk-backed body unloads.
1322
+ state.evictDetails();
1323
+ }
1324
+ }
1325
+ async #find(agentId) {
1326
+ if (this.#disposed)
1327
+ throw new AgentError('MAR_AGENT_DISPOSED', 'Subagent controller is disposed.');
1328
+ const known = this.#agents.get(agentId);
1329
+ if (known && !known.detailsEvicted)
1330
+ return known;
1331
+ const pending = this.#loading.get(agentId);
1332
+ if (pending)
1333
+ return pending;
1334
+ const load = (async () => {
1335
+ const persisted = await this.backend.loadChild(this.parentSessionId, agentId);
1336
+ if (this.#disposed)
1337
+ throw new AgentError('MAR_AGENT_DISPOSED', 'Subagent controller is disposed.');
1338
+ if (!persisted) {
1339
+ this.#agents.delete(agentId);
1340
+ this.#discovered.delete(agentId);
1341
+ throw new AgentError('MAR_AGENT_SUBAGENT_NOT_FOUND', 'Subagent was not found.');
1342
+ }
1343
+ const existing = this.#agents.get(agentId);
1344
+ if (existing && !existing.detailsEvicted)
1345
+ return existing;
1346
+ const restored = restoreAgentState(persisted);
1347
+ if (existing) {
1348
+ existing.restoreDetails(restored);
1349
+ return existing;
1350
+ }
1351
+ let revision = this.#discovered.get(agentId);
1352
+ if (revision === undefined) {
1353
+ revision = ++this.#resourceRevision;
1354
+ this.#discovered.set(agentId, revision);
1355
+ }
1356
+ restored.resourceRevision = revision;
1357
+ const task = new SubagentTask(restored);
1358
+ this.#agents.set(agentId, task);
1359
+ return task;
1360
+ })();
1361
+ this.#loading.set(agentId, load);
1362
+ try {
1363
+ return await load;
1364
+ }
1365
+ finally {
1366
+ if (this.#loading.get(agentId) === load)
1367
+ this.#loading.delete(agentId);
1368
+ }
1369
+ }
1370
+ #requireExecution() {
1371
+ if (this.#disposed)
1372
+ throw new AgentError('MAR_AGENT_DISPOSED', 'Subagent controller is disposed.');
1373
+ const execution = this.#retainedExecution.getStore()?.execution ?? this.#execution;
1374
+ if (!execution)
1375
+ throw new AgentError('MAR_AGENT_SUBAGENT_FAILED', 'Subagent control requires an active parent execution.');
1376
+ if ('signal' in execution)
1377
+ execution.signal.throwIfAborted();
1378
+ return execution;
1379
+ }
1380
+ #receiptSnapshot(state) {
1381
+ return this.#snapshot(state, {
1382
+ includeLatestMessage: false,
1383
+ includeLatestActivity: false,
1384
+ includeTerminalDetails: false
1385
+ });
1386
+ }
1387
+ #messageReceiptSnapshot(state) {
1388
+ // A follow-up starts a new observation boundary; messages from the preceding state
1389
+ // must not be returned later as fresh progress for the newly requested work.
1390
+ this.#observeLatestMessage(state);
1391
+ return this.#receiptSnapshot(state);
1392
+ }
1393
+ #snapshot(state, options = {}) {
1394
+ const terminal = state.status === 'completed' ||
1395
+ state.status === 'failed' ||
1396
+ state.status === 'cancelled' ||
1397
+ state.status === 'interrupted';
1398
+ const includeLatestMessage = options.includeLatestMessage ?? true;
1399
+ const includeLatestActivity = options.includeLatestActivity ?? true;
1400
+ const includeTerminalDetails = options.includeTerminalDetails ?? true;
1401
+ const full = options.full ?? this.#retainedExecution.getStore()?.native === true;
1402
+ const latestMessage = !includeLatestMessage || state.latestMessage === undefined
1403
+ ? undefined
1404
+ : full
1405
+ ? { ...state.latestMessage }
1406
+ : projectLatestMessage(state.latestMessage, terminal);
1407
+ const summary = !includeTerminalDetails || state.summary === undefined
1408
+ ? undefined
1409
+ : full
1410
+ ? state.summary
1411
+ : truncateUtf8(state.summary, SUBAGENT_LIMITS.subagentSummaryMaxBytes);
1412
+ const omitDuplicateMessage = !full &&
1413
+ terminal &&
1414
+ latestMessage?.phase === 'final_answer' &&
1415
+ summary !== undefined &&
1416
+ summary === state.latestMessage?.text &&
1417
+ (state.receipt === undefined || state.receipt.turnId === latestMessage.turnId);
1418
+ return {
1419
+ agentId: state.agentId,
1420
+ description: state.description,
1421
+ status: state.status,
1422
+ ...(full && this.#retainedExecution.getStore()?.native === true
1423
+ ? {
1424
+ role: state.role,
1425
+ ...(state.extensionId === undefined ? {} : { extensionId: state.extensionId })
1426
+ }
1427
+ : {}),
1428
+ ...(includeTerminalDetails && state.permissionStop
1429
+ ? { permissionStop: state.permissionStop }
1430
+ : {}),
1431
+ ...state.receipt,
1432
+ ...(omitDuplicateMessage ? { turnId: latestMessage.turnId } : {}),
1433
+ ...(state.modelId === undefined ? {} : { modelId: state.modelId }),
1434
+ ...(state.modelName === undefined ? {} : { modelName: state.modelName }),
1435
+ ...(state.reasoningEffort === undefined ? {} : { reasoningEffort: state.reasoningEffort }),
1436
+ ...(latestMessage === undefined || omitDuplicateMessage ? {} : { latestMessage }),
1437
+ ...(!includeLatestActivity || state.latestActivity === undefined
1438
+ ? {}
1439
+ : { latestActivity: { ...state.latestActivity } }),
1440
+ ...(summary === undefined ? {} : { summary }),
1441
+ ...(!includeTerminalDetails || !terminal || state.changedFiles.length === 0
1442
+ ? {}
1443
+ : {
1444
+ changedFiles: full
1445
+ ? [...state.changedFiles]
1446
+ : state.changedFiles.slice(0, SUBAGENT_LIMITS.subagentChangedFilesMaxItems)
1447
+ }),
1448
+ ...(!full || !includeTerminalDetails || !terminal || state.verification.length === 0
1449
+ ? {}
1450
+ : { verification: [...state.verification] }),
1451
+ ...(!full || !includeTerminalDetails || !terminal || state.evidence.length === 0
1452
+ ? {}
1453
+ : { evidence: state.evidence.map((item) => ({ ...item })) }),
1454
+ ...(state.errorCode === undefined ? {} : { errorCode: state.errorCode }),
1455
+ ...(state.errorMessage === undefined ? {} : { errorMessage: state.errorMessage })
1456
+ };
1457
+ }
1458
+ async #publishTerminal(state) {
1459
+ if (!state.terminalPending || !this.#execution)
1460
+ return;
1461
+ const revision = state.terminalRevision;
1462
+ try {
1463
+ await this.#execution.emitTerminal(this.#snapshot(state, { full: false }));
1464
+ state.terminalPublished(revision);
1465
+ }
1466
+ catch {
1467
+ // Keep the terminal transition pending for a later active parent Execution.
1468
+ }
1469
+ }
1470
+ }
1471
+ function projectLatestMessage(message, terminal) {
1472
+ const text = truncateCharacters(message.text, !terminal && message.phase === 'commentary'
1473
+ ? SUBAGENT_LIMITS.subagentRunningLatestMessageMaxCharacters
1474
+ : 10_000);
1475
+ return {
1476
+ ...message,
1477
+ text,
1478
+ truncated: message.truncated === true || text !== message.text
1479
+ };
1480
+ }
1481
+ function validateTaskInput(input, native = false) {
1482
+ if (!input ||
1483
+ typeof input !== 'object' ||
1484
+ typeof input.description !== 'string' ||
1485
+ typeof input.prompt !== 'string' ||
1486
+ (input.role !== 'general-purpose' && input.role !== 'explore') ||
1487
+ (input.reasoningEffort !== undefined && !isReasoningEffort(input.reasoningEffort)) ||
1488
+ input.parentSubagentId ||
1489
+ !input.description.trim() ||
1490
+ (!native && input.description.length > SUBAGENT_LIMITS.subagentDescriptionMaxCharacters) ||
1491
+ !input.prompt.trim() ||
1492
+ (!native && Buffer.byteLength(input.prompt) > SUBAGENT_LIMITS.subagentPromptMaxBytes))
1493
+ throw new AgentError(input?.parentSubagentId
1494
+ ? 'MAR_AGENT_SUBAGENT_RECURSION_DISABLED'
1495
+ : 'MAR_AGENT_TOOL_INPUT_INVALID', input?.parentSubagentId ? 'Subagents cannot create subagents.' : 'Subagent task is invalid.');
1496
+ }
1497
+ function resolveModel(execution, input) {
1498
+ const modelId = input.modelId ?? execution.modelId;
1499
+ const model = execution.models.get(modelId);
1500
+ if (!model || model.conversationModel === false)
1501
+ throw new AgentError('MAR_AGENT_SUBAGENT_MODEL_UNAVAILABLE', 'Selected model is unavailable for subagents.');
1502
+ if (input.reasoningEffort !== undefined &&
1503
+ !model.reasoningEfforts.includes(input.reasoningEffort))
1504
+ throw new AgentError('MAR_AGENT_SUBAGENT_REASONING_EFFORT_UNAVAILABLE', 'Selected reasoning effort is unavailable for the subagent model.', {
1505
+ details: {
1506
+ modelId,
1507
+ reasoningEffort: input.reasoningEffort,
1508
+ supportedReasoningEfforts: model.reasoningEfforts
1509
+ }
1510
+ });
1511
+ const reasoningEffort = input.reasoningEffort ??
1512
+ (model.reasoningEfforts.includes(execution.reasoningEffort)
1513
+ ? execution.reasoningEffort
1514
+ : model.defaultReasoningEffort);
1515
+ return { ...model, reasoningEffort };
1516
+ }
1517
+ function resolveExistingModel(execution, state) {
1518
+ const model = execution.models.get(state.modelId ?? execution.modelId);
1519
+ if (!model)
1520
+ throw new AgentError('MAR_AGENT_SUBAGENT_MODEL_UNAVAILABLE', 'The subagent model is no longer available.');
1521
+ return {
1522
+ ...model,
1523
+ reasoningEffort: state.reasoningEffort && model.reasoningEfforts.includes(state.reasoningEffort)
1524
+ ? state.reasoningEffort
1525
+ : model.defaultReasoningEffort
1526
+ };
1527
+ }
1528
+ function restoreAgentState(session) {
1529
+ const delivered = session.records.findLast((record) => (record.type === 'turn.user' || record.type === 'extension.input') &&
1530
+ isRecord(record.payload) &&
1531
+ typeof record.payload.messageId === 'string' &&
1532
+ typeof record.turnId === 'string');
1533
+ const latestExecutionStart = session.records.findLastIndex((record) => eventType(record) === 'execution.started');
1534
+ const currentRecords = latestExecutionStart < 0 ? session.records : session.records.slice(latestExecutionStart);
1535
+ const header = session.records.findLast((record) => record.type === 'execution.header' && isRecord(record.payload))?.payload;
1536
+ const terminal = currentRecords.findLast((record) => ['execution.completed', 'execution.failed', 'execution.cancelled'].includes(eventType(record) ?? ''));
1537
+ const terminalType = eventType(terminal);
1538
+ const state = {
1539
+ restorable: true,
1540
+ agentId: session.id,
1541
+ description: session.source.description,
1542
+ role: session.source.role,
1543
+ ...(session.source.ownerInstanceId === undefined
1544
+ ? {}
1545
+ : { ownerInstanceId: session.source.ownerInstanceId }),
1546
+ ...(session.source.extensionId === undefined
1547
+ ? {}
1548
+ : { extensionId: session.source.extensionId }),
1549
+ status: terminalType === 'execution.completed'
1550
+ ? 'completed'
1551
+ : terminalType === 'execution.failed'
1552
+ ? 'failed'
1553
+ : terminalType === 'execution.cancelled'
1554
+ ? 'cancelled'
1555
+ : 'interrupted',
1556
+ ...(delivered && isRecord(delivered.payload)
1557
+ ? {
1558
+ receipt: {
1559
+ messageId: delivered.payload.messageId,
1560
+ turnId: delivered.turnId,
1561
+ deliveryStatus: 'applied'
1562
+ }
1563
+ }
1564
+ : {}),
1565
+ ...(typeof header?.modelId === 'string' ? { modelId: header.modelId } : {}),
1566
+ ...(typeof header?.modelName === 'string' ? { modelName: header.modelName } : {}),
1567
+ ...(isReasoningEffort(header?.reasoningEffort)
1568
+ ? { reasoningEffort: header.reasoningEffort }
1569
+ : {}),
1570
+ messageRevision: 0,
1571
+ observedMessageRevision: 0,
1572
+ latestMessageActivityRevision: 0,
1573
+ changedFiles: [],
1574
+ verification: [],
1575
+ evidence: [],
1576
+ terminalPending: false,
1577
+ observedTerminalRevision: -1,
1578
+ resourceRevision: 0
1579
+ };
1580
+ if (terminalType === 'execution.completed' && terminal) {
1581
+ const event = terminal.payload;
1582
+ if (event.permissionStop)
1583
+ state.permissionStop = event.permissionStop;
1584
+ }
1585
+ for (const record of currentRecords) {
1586
+ if (!isRecord(record.payload) ||
1587
+ !['message.completed', 'tool.started', 'tool.completed', 'tool.failed'].includes(eventType(record) ?? ''))
1588
+ continue;
1589
+ const event = record.payload;
1590
+ if (observeAgentEvent(state, event))
1591
+ state.messageRevision++;
1592
+ }
1593
+ state.observedMessageRevision = state.messageRevision;
1594
+ if (state.status === 'completed' && state.latestMessage?.phase === 'final_answer')
1595
+ state.summary = state.latestMessage.text;
1596
+ if (state.status === 'failed' && terminal && isRecord(terminal.payload)) {
1597
+ if (typeof terminal.payload.code === 'string')
1598
+ state.errorCode = terminal.payload.code;
1599
+ if (typeof terminal.payload.message === 'string')
1600
+ state.errorMessage = terminal.payload.message;
1601
+ }
1602
+ return state;
1603
+ }
1604
+ function observeAgentEvent(state, event) {
1605
+ if (event.type === 'message.completed') {
1606
+ state.latestMessage = latestMessageFromEvent(event);
1607
+ state.latestActivity = {
1608
+ kind: 'message',
1609
+ timestamp: event.timestamp,
1610
+ phase: event.phase
1611
+ };
1612
+ return true;
1613
+ }
1614
+ if (event.type === 'tool.started') {
1615
+ state.latestActivity = {
1616
+ kind: 'tool',
1617
+ timestamp: event.timestamp,
1618
+ toolName: event.toolName,
1619
+ status: 'started'
1620
+ };
1621
+ return false;
1622
+ }
1623
+ if (event.type === 'tool.failed') {
1624
+ state.latestActivity = {
1625
+ kind: 'tool',
1626
+ timestamp: event.timestamp,
1627
+ toolName: event.toolName,
1628
+ status: 'failed'
1629
+ };
1630
+ return false;
1631
+ }
1632
+ if (event.type !== 'tool.completed')
1633
+ return false;
1634
+ state.latestActivity = {
1635
+ kind: 'tool',
1636
+ timestamp: event.timestamp,
1637
+ toolName: event.toolName,
1638
+ status: 'completed'
1639
+ };
1640
+ if (event.toolName === 'apply_patch' && isRecord(event.data)) {
1641
+ const data = event.data;
1642
+ const files = Array.isArray(data.files) ? data.files : [];
1643
+ for (const file of files) {
1644
+ if (!isRecord(file))
1645
+ continue;
1646
+ for (const path of [file.path, file.targetPath])
1647
+ if (typeof path === 'string' && path.length > 0 && !state.changedFiles.includes(path))
1648
+ state.changedFiles.push(path);
1649
+ }
1650
+ }
1651
+ else if (event.toolName === 'read' && isRecord(event.data)) {
1652
+ const data = event.data;
1653
+ const results = Array.isArray(data.results) ? data.results : [];
1654
+ for (const result of results) {
1655
+ if (!isRecord(result) || typeof result.path !== 'string' || result.error !== undefined)
1656
+ continue;
1657
+ const evidence = {
1658
+ path: result.path,
1659
+ ...(isPositiveInteger(result.startLine) ? { startLine: result.startLine } : {}),
1660
+ ...(isPositiveInteger(result.endLine) ? { endLine: result.endLine } : {})
1661
+ };
1662
+ if (!state.evidence.some((item) => JSON.stringify(item) === JSON.stringify(evidence)))
1663
+ state.evidence.push(evidence);
1664
+ }
1665
+ }
1666
+ else if (event.toolName === 'exec')
1667
+ state.verification.push(event.summary);
1668
+ return false;
1669
+ }
1670
+ function eventType(record) {
1671
+ return record && isRecord(record.payload) && typeof record.payload.type === 'string'
1672
+ ? record.payload.type
1673
+ : undefined;
1674
+ }
1675
+ function latestMessageFromEvent(event) {
1676
+ const text = event.text;
1677
+ return {
1678
+ itemId: event.itemId,
1679
+ turnId: event.turnId ?? '',
1680
+ phase: event.phase,
1681
+ text,
1682
+ timestamp: event.timestamp,
1683
+ truncated: text !== event.text
1684
+ };
1685
+ }
1686
+ function isReasoningEffort(value) {
1687
+ return (value === 'low' ||
1688
+ value === 'medium' ||
1689
+ value === 'high' ||
1690
+ value === 'xhigh' ||
1691
+ value === 'max' ||
1692
+ value === 'ultra');
1693
+ }
1694
+ function isRecord(value) {
1695
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
1696
+ }
1697
+ function isPositiveInteger(value) {
1698
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1;
1699
+ }
1700
+ function truncateUtf8(value, maximumBytes) {
1701
+ const bytes = Buffer.from(value);
1702
+ if (bytes.length <= maximumBytes)
1703
+ return value;
1704
+ let end = maximumBytes;
1705
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
1706
+ end--;
1707
+ return bytes.subarray(0, end).toString('utf8');
1708
+ }
1709
+ function truncateCharacters(value, maximumCharacters) {
1710
+ const characters = [...value];
1711
+ return characters.length <= maximumCharacters
1712
+ ? value
1713
+ : characters.slice(0, maximumCharacters).join('');
1714
+ }
1715
+ function validateOutputOptions(options, native = false) {
1716
+ if ((options.untilSettled !== undefined && options.untilSettled !== true) ||
1717
+ (options.untilSettled === true && options.waitFor === 'message') ||
1718
+ (options.waitFor !== undefined &&
1719
+ options.waitFor !== 'completion' &&
1720
+ options.waitFor !== 'message') ||
1721
+ (options.waitMs !== undefined &&
1722
+ (!Number.isSafeInteger(options.waitMs) ||
1723
+ options.waitMs < SUBAGENT_LIMITS.agentWaitMinWaitMs ||
1724
+ (!native && options.waitMs > SUBAGENT_LIMITS.agentWaitMaxWaitMs))))
1725
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Task wait is invalid.');
1726
+ }
1727
+ function isTerminalState(state) {
1728
+ return (state.status === 'completed' ||
1729
+ state.status === 'failed' ||
1730
+ state.status === 'cancelled' ||
1731
+ state.status === 'interrupted');
1732
+ }
1733
+ function waitForPromise(promise, signal) {
1734
+ signal?.throwIfAborted();
1735
+ if (signal === undefined)
1736
+ return promise;
1737
+ return new Promise((resolve, reject) => {
1738
+ let settled = false;
1739
+ const finish = (result) => {
1740
+ if (settled)
1741
+ return;
1742
+ settled = true;
1743
+ signal.removeEventListener('abort', abort);
1744
+ if ('error' in result)
1745
+ reject(result.error);
1746
+ else
1747
+ resolve(result.value);
1748
+ };
1749
+ const abort = () => finish({
1750
+ error: signal.reason ?? new AgentError('MAR_AGENT_EXECUTION_CANCELLED', 'Execution cancelled.')
1751
+ });
1752
+ signal.addEventListener('abort', abort, { once: true });
1753
+ promise.then((value) => finish({ value }), (error) => finish({ error }));
1754
+ if (signal.aborted)
1755
+ abort();
1756
+ });
1757
+ }
1758
+ /** Retain the waited Turn's evidence when the live Session moves on to another Turn. */
1759
+ function copyWaitState(state) {
1760
+ return state.copyWaitState();
1761
+ }