effect-agent 0.1.0-beta.85 → 0.1.0-beta.87

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 (751) hide show
  1. package/dist/Agent-CN0EWRsR.d.mts +226 -0
  2. package/dist/Agent-RklVROrm.mjs +83 -0
  3. package/dist/Agent-RklVROrm.mjs.map +1 -0
  4. package/dist/AgentError-CggcAQ7V.d.mts +101 -0
  5. package/dist/AgentPolicy-CetmQrf3.d.mts +96 -0
  6. package/dist/AgentRuntime-BLyETCPo.mjs +4562 -0
  7. package/dist/AgentRuntime-BLyETCPo.mjs.map +1 -0
  8. package/dist/AgentRuntime-uxR_a4VM.d.mts +346 -0
  9. package/dist/AgentUpdates-DMJ-_xow.d.mts +53 -0
  10. package/dist/ContextCompactor-Dxu5zhOL.d.mts +161 -0
  11. package/dist/ContextWindow-DRQ5Mbm2.d.mts +58 -0
  12. package/dist/DurableAgentRuntime-uggeJpv3.mjs +6368 -0
  13. package/dist/DurableAgentRuntime-uggeJpv3.mjs.map +1 -0
  14. package/dist/DurableFailpoint-Oinuuedm.d.mts +41 -0
  15. package/dist/DurableStep-Cry_iol4.d.mts +103 -0
  16. package/dist/Ephemeral.d.mts +22 -0
  17. package/dist/Ephemeral.mjs +22 -0
  18. package/dist/Ephemeral.mjs.map +1 -0
  19. package/dist/EventSource-OqS_P9ug.d.mts +51 -0
  20. package/dist/Identifiers-CN2s30fF.d.mts +40 -0
  21. package/dist/MemoryNamespace-BbRW5p71.d.mts +36 -0
  22. package/dist/MemoryReference-B8Q3UJoJ.d.mts +79 -0
  23. package/dist/Messaging-CkcIdt4I.d.mts +490 -0
  24. package/dist/MessagingHost-CRk0kXzT.d.mts +246 -0
  25. package/dist/MessagingHost-CWi_PP3g.mjs +137 -0
  26. package/dist/MessagingHost-CWi_PP3g.mjs.map +1 -0
  27. package/dist/OperationAuthorizer-TzcQtpX5.d.mts +61 -0
  28. package/dist/Output-D6SkedVx.d.mts +25 -0
  29. package/dist/PageCapture-Df8Xwskw.d.mts +583 -0
  30. package/dist/PageScreenshot-BpgZKAxl.d.mts +48 -0
  31. package/dist/PreparedInputAdmission-C4HbjHgl.d.mts +38 -0
  32. package/dist/Receipt-BAHyigAF.d.mts +33 -0
  33. package/dist/Records-BAGkekt8.d.mts +3570 -0
  34. package/dist/RunEvent-DIrzkjLr.d.mts +460 -0
  35. package/dist/RunEventSink-D5aVhISG.d.mts +108 -0
  36. package/dist/RunJournal-Cgg1kNvc.mjs +825 -0
  37. package/dist/RunJournal-Cgg1kNvc.mjs.map +1 -0
  38. package/dist/RunOptions-g1aigcKI.d.mts +915 -0
  39. package/dist/RunPolicyUsage-ClZxyR46.d.mts +21 -0
  40. package/dist/Sandbox-CEsDWBLq.d.mts +173 -0
  41. package/dist/Schedule-H3SEYX9g.d.mts +842 -0
  42. package/dist/Scheduling-C9aIP8zT.mjs +691 -0
  43. package/dist/Scheduling-C9aIP8zT.mjs.map +1 -0
  44. package/dist/Subagent-Cy_hU1tv.mjs +1469 -0
  45. package/dist/Subagent-Cy_hU1tv.mjs.map +1 -0
  46. package/dist/Subagent-DyfzHNdv.d.mts +826 -0
  47. package/dist/SubagentContract-DdT7Cqe6.d.mts +116 -0
  48. package/dist/SubagentHost-CJUBQlcc.d.mts +140 -0
  49. package/dist/Subscription-BEP8oQO5.d.mts +921 -0
  50. package/dist/SubscriptionInput-vAAOBrK7.d.mts +41 -0
  51. package/dist/Thread-DOBQ0QUY.d.mts +96 -0
  52. package/dist/ThreadHistory-tS1KwxHR.d.mts +60 -0
  53. package/dist/ToolBroker-DWs4tZra.d.mts +133 -0
  54. package/dist/ToolExposure-9uF_Yo0T.mjs +10 -0
  55. package/dist/ToolExposure-9uF_Yo0T.mjs.map +1 -0
  56. package/dist/ToolExposure-C93U1sPu.mjs +30 -0
  57. package/dist/ToolExposure-C93U1sPu.mjs.map +1 -0
  58. package/dist/ToolExposure-UCN12eCd.d.mts +39 -0
  59. package/dist/ToolExposure-r2eOWk4F.d.mts +46 -0
  60. package/dist/ToolExposure.d.mts +6 -5
  61. package/dist/ToolExposure.mjs +17 -9
  62. package/dist/ToolExposure.mjs.map +1 -1
  63. package/dist/ToolReconciler-DQVaJfpE.d.mts +76 -0
  64. package/dist/ToolResult-DmmgoChv.d.mts +61 -0
  65. package/dist/Usage-Dx0aknfk.d.mts +121 -0
  66. package/dist/WakeScheduler-EjUF-GhC.d.mts +56 -0
  67. package/dist/Worker-CaPYykpe.d.mts +228 -0
  68. package/dist/agent-registration-CWDMOAZA.mjs +172 -0
  69. package/dist/agent-registration-CWDMOAZA.mjs.map +1 -0
  70. package/dist/capabilities/Approval.d.mts +114 -0
  71. package/dist/capabilities/Approval.mjs +226 -0
  72. package/dist/capabilities/Approval.mjs.map +1 -0
  73. package/dist/capabilities/Budget.d.mts +112 -0
  74. package/dist/capabilities/Budget.mjs +346 -0
  75. package/dist/capabilities/Budget.mjs.map +1 -0
  76. package/dist/capabilities/CodeMode.d.mts +157 -0
  77. package/dist/capabilities/CodeMode.mjs +522 -0
  78. package/dist/capabilities/CodeMode.mjs.map +1 -0
  79. package/dist/capabilities/Commands.d.mts +55 -0
  80. package/dist/capabilities/Commands.mjs +57 -0
  81. package/dist/capabilities/Commands.mjs.map +1 -0
  82. package/dist/capabilities/ContextTools.d.mts +321 -0
  83. package/dist/capabilities/ContextTools.mjs +126 -0
  84. package/dist/capabilities/ContextTools.mjs.map +1 -0
  85. package/dist/capabilities/Mcp.d.mts +108 -0
  86. package/dist/capabilities/Mcp.mjs +260 -0
  87. package/dist/capabilities/Mcp.mjs.map +1 -0
  88. package/dist/capabilities/McpClient.d.mts +115 -0
  89. package/dist/capabilities/McpClient.mjs +506 -0
  90. package/dist/capabilities/McpClient.mjs.map +1 -0
  91. package/dist/capabilities/MemoryNotes.d.mts +424 -0
  92. package/dist/capabilities/MemoryNotes.mjs +128 -0
  93. package/dist/capabilities/MemoryNotes.mjs.map +1 -0
  94. package/dist/capabilities/Messaging.d.mts +3 -0
  95. package/dist/capabilities/Messaging.mjs +151 -0
  96. package/dist/capabilities/Messaging.mjs.map +1 -0
  97. package/dist/capabilities/ModelContext.d.mts +89 -0
  98. package/dist/capabilities/ModelContext.mjs +168 -0
  99. package/dist/capabilities/ModelContext.mjs.map +1 -0
  100. package/dist/capabilities/Redaction.d.mts +37 -0
  101. package/dist/capabilities/Redaction.mjs +104 -0
  102. package/dist/capabilities/Redaction.mjs.map +1 -0
  103. package/dist/capabilities/Remembering.d.mts +434 -0
  104. package/dist/capabilities/Remembering.mjs +290 -0
  105. package/dist/capabilities/Remembering.mjs.map +1 -0
  106. package/dist/capabilities/RunHooks.d.mts +82 -0
  107. package/dist/capabilities/RunHooks.mjs +144 -0
  108. package/dist/capabilities/RunHooks.mjs.map +1 -0
  109. package/dist/capabilities/SemanticMemory.d.mts +431 -0
  110. package/dist/capabilities/SemanticMemory.mjs +315 -0
  111. package/dist/capabilities/SemanticMemory.mjs.map +1 -0
  112. package/dist/capabilities/Subagent.d.mts +4 -0
  113. package/dist/capabilities/Subagent.mjs +5 -0
  114. package/dist/capabilities/SubagentReservations.d.mts +186 -0
  115. package/dist/capabilities/SubagentReservations.mjs +479 -0
  116. package/dist/capabilities/SubagentReservations.mjs.map +1 -0
  117. package/dist/capabilities/ToolDiscovery.d.mts +109 -0
  118. package/dist/capabilities/ToolDiscovery.mjs +211 -0
  119. package/dist/capabilities/ToolDiscovery.mjs.map +1 -0
  120. package/dist/capabilities/WebCapture.d.mts +163 -0
  121. package/dist/capabilities/WebCapture.mjs +335 -0
  122. package/dist/capabilities/WebCapture.mjs.map +1 -0
  123. package/dist/capabilities/WebSearch.d.mts +71 -0
  124. package/dist/capabilities/WebSearch.mjs +112 -0
  125. package/dist/capabilities/WebSearch.mjs.map +1 -0
  126. package/dist/compaction-C2OTceKw.mjs +505 -0
  127. package/dist/compaction-C2OTceKw.mjs.map +1 -0
  128. package/dist/core/Agent.d.mts +2 -0
  129. package/dist/core/Agent.mjs +2 -0
  130. package/dist/core/AgentError.d.mts +2 -0
  131. package/dist/core/AgentError.mjs +117 -0
  132. package/dist/core/AgentError.mjs.map +1 -0
  133. package/dist/core/AgentPolicy.d.mts +2 -0
  134. package/dist/core/AgentPolicy.mjs +94 -0
  135. package/dist/core/AgentPolicy.mjs.map +1 -0
  136. package/dist/core/AgentUpdates.d.mts +2 -0
  137. package/dist/core/AgentUpdates.mjs +63 -0
  138. package/dist/core/AgentUpdates.mjs.map +1 -0
  139. package/dist/core/IdGenerator.d.mts +26 -0
  140. package/dist/core/IdGenerator.mjs +27 -0
  141. package/dist/core/IdGenerator.mjs.map +1 -0
  142. package/dist/core/Identifiers.d.mts +2 -0
  143. package/dist/core/Identifiers.mjs +43 -0
  144. package/dist/core/Identifiers.mjs.map +1 -0
  145. package/dist/core/Memory.d.mts +57 -0
  146. package/dist/core/Memory.mjs +203 -0
  147. package/dist/core/Memory.mjs.map +1 -0
  148. package/dist/core/MemoryNamespace.d.mts +2 -0
  149. package/dist/core/MemoryNamespace.mjs +116 -0
  150. package/dist/core/MemoryNamespace.mjs.map +1 -0
  151. package/dist/core/MemoryReference.d.mts +2 -0
  152. package/dist/core/MemoryReference.mjs +109 -0
  153. package/dist/core/MemoryReference.mjs.map +1 -0
  154. package/dist/core/MemoryRevalidation.d.mts +65 -0
  155. package/dist/core/MemoryRevalidation.mjs +126 -0
  156. package/dist/core/MemoryRevalidation.mjs.map +1 -0
  157. package/dist/core/MemoryStore.d.mts +186 -0
  158. package/dist/core/MemoryStore.mjs +243 -0
  159. package/dist/core/MemoryStore.mjs.map +1 -0
  160. package/dist/core/Receipt.d.mts +2 -0
  161. package/dist/core/Receipt.mjs +36 -0
  162. package/dist/core/Receipt.mjs.map +1 -0
  163. package/dist/core/RememberingStore.d.mts +1562 -0
  164. package/dist/core/RememberingStore.mjs +190 -0
  165. package/dist/core/RememberingStore.mjs.map +1 -0
  166. package/dist/core/RunEvent.d.mts +2 -0
  167. package/dist/core/RunEvent.mjs +337 -0
  168. package/dist/core/RunEvent.mjs.map +1 -0
  169. package/dist/core/RunPolicyUsage.d.mts +2 -0
  170. package/dist/core/RunPolicyUsage.mjs +21 -0
  171. package/dist/core/RunPolicyUsage.mjs.map +1 -0
  172. package/dist/core/SemanticMemoryIndex.d.mts +826 -0
  173. package/dist/core/SemanticMemoryIndex.mjs +185 -0
  174. package/dist/core/SemanticMemoryIndex.mjs.map +1 -0
  175. package/dist/core/SemanticMemoryRevalidation.d.mts +45 -0
  176. package/dist/core/SemanticMemoryRevalidation.mjs +191 -0
  177. package/dist/core/SemanticMemoryRevalidation.mjs.map +1 -0
  178. package/dist/core/SubagentContract.d.mts +2 -0
  179. package/dist/core/SubagentContract.mjs +148 -0
  180. package/dist/core/SubagentContract.mjs.map +1 -0
  181. package/dist/core/Thread.d.mts +2 -0
  182. package/dist/core/Thread.mjs +250 -0
  183. package/dist/core/Thread.mjs.map +1 -0
  184. package/dist/core/ToolResult.d.mts +2 -0
  185. package/dist/core/ToolResult.mjs +140 -0
  186. package/dist/core/ToolResult.mjs.map +1 -0
  187. package/dist/core/Usage.d.mts +2 -0
  188. package/dist/core/Usage.mjs +319 -0
  189. package/dist/core/Usage.mjs.map +1 -0
  190. package/dist/core/Worker.d.mts +3 -0
  191. package/dist/core/Worker.mjs +147 -0
  192. package/dist/core/Worker.mjs.map +1 -0
  193. package/dist/durable/ActivityStore.d.mts +116 -0
  194. package/dist/durable/ActivityStore.mjs +131 -0
  195. package/dist/durable/ActivityStore.mjs.map +1 -0
  196. package/dist/durable/Admin.d.mts +2 -0
  197. package/dist/durable/Admin.mjs +328 -0
  198. package/dist/durable/Admin.mjs.map +1 -0
  199. package/dist/durable/AgentRegistration.d.mts +2 -0
  200. package/dist/durable/AgentRegistration.mjs +14 -0
  201. package/dist/durable/AgentRegistration.mjs.map +1 -0
  202. package/dist/durable/Certification.d.mts +111 -0
  203. package/dist/durable/Certification.mjs +159 -0
  204. package/dist/durable/Certification.mjs.map +1 -0
  205. package/dist/durable/CommittedActivity.d.mts +62 -0
  206. package/dist/durable/CommittedActivity.mjs +159 -0
  207. package/dist/durable/CommittedActivity.mjs.map +1 -0
  208. package/dist/durable/Digest.d.mts +2 -0
  209. package/dist/durable/Digest.mjs +50 -0
  210. package/dist/durable/Digest.mjs.map +1 -0
  211. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  212. package/dist/durable/DurableAgentRuntime.mjs +3 -0
  213. package/dist/durable/DurableFailpoint.d.mts +2 -0
  214. package/dist/durable/DurableFailpoint.mjs +94 -0
  215. package/dist/durable/DurableFailpoint.mjs.map +1 -0
  216. package/dist/durable/DurableFailpointTestControl.d.mts +15 -0
  217. package/dist/durable/DurableFailpointTestControl.mjs +19 -0
  218. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  219. package/dist/durable/EventSource.d.mts +2 -0
  220. package/dist/durable/EventSource.mjs +65 -0
  221. package/dist/durable/EventSource.mjs.map +1 -0
  222. package/dist/durable/GitHubWorkflowSource.d.mts +144 -0
  223. package/dist/durable/GitHubWorkflowSource.mjs +209 -0
  224. package/dist/durable/GitHubWorkflowSource.mjs.map +1 -0
  225. package/dist/durable/MessageDelivery.d.mts +492 -0
  226. package/dist/durable/MessageDelivery.mjs +495 -0
  227. package/dist/durable/MessageDelivery.mjs.map +1 -0
  228. package/dist/durable/MessageDeliveryStoreConformance.d.mts +358 -0
  229. package/dist/durable/MessageDeliveryStoreConformance.mjs +243 -0
  230. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  231. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  232. package/dist/durable/OperationAuthorizer.mjs +70 -0
  233. package/dist/durable/OperationAuthorizer.mjs.map +1 -0
  234. package/dist/durable/PersistentHistory.d.mts +16 -0
  235. package/dist/durable/PersistentHistory.mjs +125 -0
  236. package/dist/durable/PersistentHistory.mjs.map +1 -0
  237. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  238. package/dist/durable/PreparedInputAdmission.mjs +34 -0
  239. package/dist/durable/PreparedInputAdmission.mjs.map +1 -0
  240. package/dist/durable/Records.d.mts +2 -0
  241. package/dist/durable/Records.mjs +795 -0
  242. package/dist/durable/Records.mjs.map +1 -0
  243. package/dist/durable/Recovery.d.mts +2 -0
  244. package/dist/durable/Recovery.mjs +739 -0
  245. package/dist/durable/Recovery.mjs.map +1 -0
  246. package/dist/durable/RunJournal.d.mts +2 -0
  247. package/dist/durable/RunJournal.mjs +2 -0
  248. package/dist/durable/Schedule.d.mts +2 -0
  249. package/dist/durable/Schedule.mjs +382 -0
  250. package/dist/durable/Schedule.mjs.map +1 -0
  251. package/dist/durable/ScheduleStoreConformance.d.mts +18 -0
  252. package/dist/durable/ScheduleStoreConformance.mjs +420 -0
  253. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  254. package/dist/durable/ScheduleTransition.d.mts +24 -0
  255. package/dist/durable/ScheduleTransition.mjs +180 -0
  256. package/dist/durable/ScheduleTransition.mjs.map +1 -0
  257. package/dist/durable/Scheduling.d.mts +54 -0
  258. package/dist/durable/Scheduling.mjs +2 -0
  259. package/dist/durable/SqlMemoryStore.d.mts +30 -0
  260. package/dist/durable/SqlMemoryStore.mjs +435 -0
  261. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  262. package/dist/durable/SqlMessageDeliveryStore.d.mts +40 -0
  263. package/dist/durable/SqlMessageDeliveryStore.mjs +167 -0
  264. package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -0
  265. package/dist/durable/SqlStorageV2Upgrade.d.mts +22 -0
  266. package/dist/durable/SqlStorageV2Upgrade.mjs +459 -0
  267. package/dist/durable/SqlStorageV2Upgrade.mjs.map +1 -0
  268. package/dist/durable/SqlSubscriptionStore.d.mts +63 -0
  269. package/dist/durable/SqlSubscriptionStore.mjs +751 -0
  270. package/dist/durable/SqlSubscriptionStore.mjs.map +1 -0
  271. package/dist/durable/SubmissionLedger.d.mts +3 -0
  272. package/dist/durable/SubmissionLedger.mjs +914 -0
  273. package/dist/durable/SubmissionLedger.mjs.map +1 -0
  274. package/dist/durable/SubmissionLedgerConformance.d.mts +30 -0
  275. package/dist/durable/SubmissionLedgerConformance.mjs +1986 -0
  276. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  277. package/dist/durable/SubmissionStatus.d.mts +2 -0
  278. package/dist/durable/SubmissionStatus.mjs +18 -0
  279. package/dist/durable/SubmissionStatus.mjs.map +1 -0
  280. package/dist/durable/Subscription.d.mts +2 -0
  281. package/dist/durable/Subscription.mjs +360 -0
  282. package/dist/durable/Subscription.mjs.map +1 -0
  283. package/dist/durable/SubscriptionInput.d.mts +2 -0
  284. package/dist/durable/SubscriptionInput.mjs +52 -0
  285. package/dist/durable/SubscriptionInput.mjs.map +1 -0
  286. package/dist/durable/SubscriptionStoreConformance.d.mts +17 -0
  287. package/dist/durable/SubscriptionStoreConformance.mjs +625 -0
  288. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  289. package/dist/durable/SubscriptionTools.d.mts +273 -0
  290. package/dist/durable/SubscriptionTools.mjs +190 -0
  291. package/dist/durable/SubscriptionTools.mjs.map +1 -0
  292. package/dist/durable/SubscriptionTransition.d.mts +21 -0
  293. package/dist/durable/SubscriptionTransition.mjs +148 -0
  294. package/dist/durable/SubscriptionTransition.mjs.map +1 -0
  295. package/dist/durable/Subscriptions.d.mts +73 -0
  296. package/dist/durable/Subscriptions.mjs +627 -0
  297. package/dist/durable/Subscriptions.mjs.map +1 -0
  298. package/dist/durable/ThreadContextHistory.d.mts +32 -0
  299. package/dist/durable/ThreadContextHistory.mjs +152 -0
  300. package/dist/durable/ThreadContextHistory.mjs.map +1 -0
  301. package/dist/durable/ThreadContextHistoryProjection.d.mts +60 -0
  302. package/dist/durable/ThreadContextHistoryProjection.mjs +149 -0
  303. package/dist/durable/ThreadContextHistoryProjection.mjs.map +1 -0
  304. package/dist/durable/ThreadInvariants.d.mts +74 -0
  305. package/dist/durable/ThreadInvariants.mjs +200 -0
  306. package/dist/durable/ThreadInvariants.mjs.map +1 -0
  307. package/dist/durable/ThreadProjection.d.mts +78 -0
  308. package/dist/durable/ThreadProjection.mjs +158 -0
  309. package/dist/durable/ThreadProjection.mjs.map +1 -0
  310. package/dist/durable/ThreadProjectionMaintenance.d.mts +49 -0
  311. package/dist/durable/ThreadProjectionMaintenance.mjs +33 -0
  312. package/dist/durable/ThreadProjectionMaintenance.mjs.map +1 -0
  313. package/dist/durable/ThreadStore.d.mts +2 -0
  314. package/dist/durable/ThreadStore.mjs +147 -0
  315. package/dist/durable/ThreadStore.mjs.map +1 -0
  316. package/dist/durable/ThreadStoreConformance.d.mts +29 -0
  317. package/dist/durable/ThreadStoreConformance.mjs +248 -0
  318. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  319. package/dist/durable/ToolReconciler.d.mts +2 -0
  320. package/dist/durable/ToolReconciler.mjs +81 -0
  321. package/dist/durable/ToolReconciler.mjs.map +1 -0
  322. package/dist/durable/WakeScheduler.d.mts +2 -0
  323. package/dist/durable/WakeScheduler.mjs +85 -0
  324. package/dist/durable/WakeScheduler.mjs.map +1 -0
  325. package/dist/durable/WorkerHost.d.mts +129 -0
  326. package/dist/durable/WorkerHost.mjs +77 -0
  327. package/dist/durable/WorkerHost.mjs.map +1 -0
  328. package/dist/engine/AgentRuntime.d.mts +2 -0
  329. package/dist/engine/AgentRuntime.mjs +2 -0
  330. package/dist/engine/Compaction.d.mts +7 -0
  331. package/dist/engine/Compaction.mjs +16 -0
  332. package/dist/engine/Compaction.mjs.map +1 -0
  333. package/dist/engine/ContextCompactor.d.mts +2 -0
  334. package/dist/engine/ContextCompactor.mjs +119 -0
  335. package/dist/engine/ContextCompactor.mjs.map +1 -0
  336. package/dist/engine/ContextHistory.d.mts +65 -0
  337. package/dist/engine/ContextHistory.mjs +76 -0
  338. package/dist/engine/ContextHistory.mjs.map +1 -0
  339. package/dist/engine/ContextWindow.d.mts +2 -0
  340. package/dist/engine/ContextWindow.mjs +59 -0
  341. package/dist/engine/ContextWindow.mjs.map +1 -0
  342. package/dist/engine/DurableStep.d.mts +2 -0
  343. package/dist/engine/DurableStep.mjs +62 -0
  344. package/dist/engine/DurableStep.mjs.map +1 -0
  345. package/dist/engine/MessagingHost.d.mts +2 -0
  346. package/dist/engine/MessagingHost.mjs +2 -0
  347. package/dist/engine/Output.d.mts +2 -0
  348. package/dist/engine/Output.mjs +8 -0
  349. package/dist/engine/Output.mjs.map +1 -0
  350. package/dist/engine/RunEventSink.d.mts +2 -0
  351. package/dist/engine/RunEventSink.mjs +22 -0
  352. package/dist/engine/RunEventSink.mjs.map +1 -0
  353. package/dist/engine/RunOptions.d.mts +2 -0
  354. package/dist/engine/RunOptions.mjs +122 -0
  355. package/dist/engine/RunOptions.mjs.map +1 -0
  356. package/dist/engine/SubagentHost.d.mts +2 -0
  357. package/dist/engine/SubagentHost.mjs +72 -0
  358. package/dist/engine/SubagentHost.mjs.map +1 -0
  359. package/dist/engine/ThreadHistory.d.mts +2 -0
  360. package/dist/engine/ThreadHistory.mjs +67 -0
  361. package/dist/engine/ThreadHistory.mjs.map +1 -0
  362. package/dist/engine/ToolBroker.d.mts +2 -0
  363. package/dist/engine/ToolBroker.mjs +42 -0
  364. package/dist/engine/ToolBroker.mjs.map +1 -0
  365. package/dist/foreign-diagnostic-DBQ1XHKh.mjs +37 -0
  366. package/dist/foreign-diagnostic-DBQ1XHKh.mjs.map +1 -0
  367. package/dist/index.d.mts +88 -54
  368. package/dist/index.mjs +97 -54
  369. package/dist/output-contract-BC7tjlGw.mjs +84 -0
  370. package/dist/output-contract-BC7tjlGw.mjs.map +1 -0
  371. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  372. package/dist/sandbox/CodeExecutor.d.mts +194 -0
  373. package/dist/sandbox/CodeExecutor.mjs +278 -0
  374. package/dist/sandbox/CodeExecutor.mjs.map +1 -0
  375. package/dist/sandbox/InteractiveBrowser.d.mts +142 -0
  376. package/dist/sandbox/InteractiveBrowser.mjs +165 -0
  377. package/dist/sandbox/InteractiveBrowser.mjs.map +1 -0
  378. package/dist/sandbox/PageCapture.d.mts +2 -0
  379. package/dist/sandbox/PageCapture.mjs +450 -0
  380. package/dist/sandbox/PageCapture.mjs.map +1 -0
  381. package/dist/sandbox/PageCrawl.d.mts +88 -0
  382. package/dist/sandbox/PageCrawl.mjs +124 -0
  383. package/dist/sandbox/PageCrawl.mjs.map +1 -0
  384. package/dist/sandbox/PageScreenshot.d.mts +2 -0
  385. package/dist/sandbox/PageScreenshot.mjs +53 -0
  386. package/dist/sandbox/PageScreenshot.mjs.map +1 -0
  387. package/dist/sandbox/ProtectedBrowser.d.mts +252 -0
  388. package/dist/sandbox/ProtectedBrowser.mjs +270 -0
  389. package/dist/sandbox/ProtectedBrowser.mjs.map +1 -0
  390. package/dist/sandbox/Sandbox.d.mts +2 -0
  391. package/dist/sandbox/Sandbox.mjs +208 -0
  392. package/dist/sandbox/Sandbox.mjs.map +1 -0
  393. package/dist/utf8-BYfhEkcj.mjs +11 -0
  394. package/dist/utf8-BYfhEkcj.mjs.map +1 -0
  395. package/dist/utf8-DchGZRBd.mjs +23 -0
  396. package/dist/utf8-DchGZRBd.mjs.map +1 -0
  397. package/package.json +1 -1
  398. package/src/Ephemeral.ts +17 -0
  399. package/src/ToolExposure.ts +2 -2
  400. package/src/capabilities/Approval.ts +352 -0
  401. package/src/capabilities/Budget.ts +536 -0
  402. package/src/capabilities/CodeMode.ts +1090 -0
  403. package/src/capabilities/Commands.ts +86 -0
  404. package/src/capabilities/ContextTools.ts +184 -0
  405. package/src/capabilities/Mcp.ts +427 -0
  406. package/src/capabilities/McpClient.ts +967 -0
  407. package/src/capabilities/MemoryNotes.ts +174 -0
  408. package/src/capabilities/Messaging.ts +261 -0
  409. package/src/capabilities/ModelContext.ts +354 -0
  410. package/src/capabilities/Redaction.ts +157 -0
  411. package/src/capabilities/Remembering.ts +550 -0
  412. package/src/capabilities/RunHooks.ts +280 -0
  413. package/src/capabilities/SemanticMemory.ts +447 -0
  414. package/src/capabilities/Subagent.ts +2277 -0
  415. package/src/capabilities/SubagentReservations.ts +850 -0
  416. package/src/capabilities/ToolDiscovery.ts +339 -0
  417. package/src/capabilities/WebCapture.ts +722 -0
  418. package/src/capabilities/WebSearch.ts +184 -0
  419. package/src/capabilities/internal/subagent-background.ts +1106 -0
  420. package/src/capabilities/internal/subagent-contract.ts +142 -0
  421. package/src/capabilities/internal/subagent-policy.ts +235 -0
  422. package/src/capabilities/internal/subagent-reporting.ts +261 -0
  423. package/src/capabilities/internal/utf8.ts +10 -0
  424. package/src/core/Agent.ts +575 -0
  425. package/src/core/AgentError.ts +152 -0
  426. package/src/core/AgentPolicy.ts +153 -0
  427. package/src/core/AgentUpdates.ts +100 -0
  428. package/src/core/IdGenerator.ts +39 -0
  429. package/src/core/Identifiers.ts +48 -0
  430. package/src/core/Memory.ts +290 -0
  431. package/src/core/MemoryNamespace.ts +196 -0
  432. package/src/core/MemoryReference.ts +121 -0
  433. package/src/core/MemoryRevalidation.ts +185 -0
  434. package/src/core/MemoryStore.ts +368 -0
  435. package/src/core/Messaging.ts +90 -0
  436. package/src/core/Receipt.ts +42 -0
  437. package/src/core/RememberingStore.ts +300 -0
  438. package/src/core/RunEvent.ts +366 -0
  439. package/src/core/RunPolicyUsage.ts +17 -0
  440. package/src/core/SemanticMemoryIndex.ts +250 -0
  441. package/src/core/SemanticMemoryRevalidation.ts +254 -0
  442. package/src/core/SubagentContract.ts +196 -0
  443. package/src/core/Thread.ts +371 -0
  444. package/src/core/ToolExposure.ts +74 -0
  445. package/src/core/ToolResult.ts +170 -0
  446. package/src/core/Usage.ts +529 -0
  447. package/src/core/Worker.ts +173 -0
  448. package/src/core/internal/agent-updates.ts +32 -0
  449. package/src/core/internal/utf8.ts +23 -0
  450. package/src/durable/ActivityStore.ts +160 -0
  451. package/src/durable/Admin.ts +496 -0
  452. package/src/durable/AgentRegistration.ts +13 -0
  453. package/src/durable/Certification.ts +210 -0
  454. package/src/durable/CommittedActivity.ts +296 -0
  455. package/src/durable/Digest.ts +93 -0
  456. package/src/durable/DurableAgentRuntime.ts +10340 -0
  457. package/src/durable/DurableFailpoint.ts +103 -0
  458. package/src/durable/DurableFailpointTestControl.ts +39 -0
  459. package/src/durable/EventSource.ts +172 -0
  460. package/src/durable/GitHubWorkflowSource.ts +453 -0
  461. package/src/durable/MessageDelivery.ts +708 -0
  462. package/src/durable/MessageDeliveryStoreConformance.ts +363 -0
  463. package/src/durable/OperationAuthorizer.ts +85 -0
  464. package/src/durable/PersistentHistory.ts +260 -0
  465. package/src/durable/PreparedInputAdmission.ts +44 -0
  466. package/src/durable/Records.ts +1010 -0
  467. package/src/durable/Recovery.ts +1018 -0
  468. package/src/durable/RunJournal.ts +1479 -0
  469. package/src/durable/Schedule.ts +504 -0
  470. package/src/durable/ScheduleStoreConformance.ts +638 -0
  471. package/src/durable/ScheduleTransition.ts +265 -0
  472. package/src/durable/Scheduling.ts +1077 -0
  473. package/src/durable/SqlMemoryStore.ts +774 -0
  474. package/src/durable/SqlMessageDeliveryStore.ts +302 -0
  475. package/src/durable/SqlStorageV2Upgrade.ts +500 -0
  476. package/src/durable/SqlSubscriptionStore.ts +1440 -0
  477. package/src/durable/SubmissionLedger.ts +1201 -0
  478. package/src/durable/SubmissionLedgerConformance.ts +4579 -0
  479. package/src/durable/SubmissionStatus.ts +14 -0
  480. package/src/durable/Subscription.ts +544 -0
  481. package/src/durable/SubscriptionInput.ts +144 -0
  482. package/src/durable/SubscriptionStoreConformance.ts +945 -0
  483. package/src/durable/SubscriptionTools.ts +327 -0
  484. package/src/durable/SubscriptionTransition.ts +302 -0
  485. package/src/durable/Subscriptions.ts +1210 -0
  486. package/src/durable/ThreadContextHistory.ts +227 -0
  487. package/src/durable/ThreadContextHistoryProjection.ts +216 -0
  488. package/src/durable/ThreadInvariants.ts +442 -0
  489. package/src/durable/ThreadProjection.ts +269 -0
  490. package/src/durable/ThreadProjectionMaintenance.ts +67 -0
  491. package/src/durable/ThreadStore.ts +242 -0
  492. package/src/durable/ThreadStoreConformance.ts +710 -0
  493. package/src/durable/ToolReconciler.ts +105 -0
  494. package/src/durable/WakeScheduler.ts +134 -0
  495. package/src/durable/WorkerHost.ts +171 -0
  496. package/src/durable/internal/agent-registration.ts +525 -0
  497. package/src/durable/internal/agent-updates.ts +302 -0
  498. package/src/durable/internal/foreign-diagnostic.ts +47 -0
  499. package/src/durable/internal/journal-checkpoint.ts +104 -0
  500. package/src/durable/internal/journal-metadata.ts +107 -0
  501. package/src/durable/internal/messaging-host.ts +608 -0
  502. package/src/durable/internal/schedule-time.ts +303 -0
  503. package/src/durable/internal/storage-v2-layout.ts +163 -0
  504. package/src/durable/internal/storage-v2.ts +73 -0
  505. package/src/durable/internal/worker-host.ts +2467 -0
  506. package/src/durable/internal/worker-runtime.ts +9 -0
  507. package/src/engine/AgentRuntime.ts +37 -0
  508. package/src/engine/Compaction.ts +11 -0
  509. package/src/engine/ContextCompactor.ts +277 -0
  510. package/src/engine/ContextHistory.ts +73 -0
  511. package/src/engine/ContextWindow.ts +72 -0
  512. package/src/engine/DurableStep.ts +132 -0
  513. package/src/engine/MessagingHost.ts +110 -0
  514. package/src/engine/Output.ts +2 -0
  515. package/src/engine/RunEventSink.ts +132 -0
  516. package/src/engine/RunOptions.ts +1077 -0
  517. package/src/engine/SubagentHost.ts +181 -0
  518. package/src/engine/ThreadHistory.ts +120 -0
  519. package/src/engine/ToolBroker.ts +157 -0
  520. package/src/engine/ToolExposure.ts +48 -0
  521. package/src/engine/internal/agent-runtime.ts +10117 -0
  522. package/src/engine/internal/bounded-value.ts +315 -0
  523. package/src/engine/internal/compaction.ts +678 -0
  524. package/src/engine/internal/error-diagnostic.ts +39 -0
  525. package/src/engine/internal/output-contract.ts +173 -0
  526. package/src/engine/internal/primitive-delta.ts +80 -0
  527. package/src/engine/internal/provider-result-staging.ts +211 -0
  528. package/src/engine/internal/tool-derivative.ts +106 -0
  529. package/src/engine/internal/tool-exposure.ts +224 -0
  530. package/src/engine/internal/tool-telemetry.ts +484 -0
  531. package/src/index.ts +96 -53
  532. package/src/sandbox/CodeExecutor.ts +352 -0
  533. package/src/sandbox/InteractiveBrowser.ts +257 -0
  534. package/src/sandbox/PageCapture.ts +692 -0
  535. package/src/sandbox/PageCrawl.ts +148 -0
  536. package/src/sandbox/PageScreenshot.ts +81 -0
  537. package/src/sandbox/ProtectedBrowser.ts +413 -0
  538. package/src/sandbox/Sandbox.ts +241 -0
  539. package/dist/Agent.d.mts +0 -5
  540. package/dist/Agent.mjs +0 -10
  541. package/dist/Agent.mjs.map +0 -1
  542. package/dist/AgentError.d.mts +0 -5
  543. package/dist/AgentError.mjs +0 -10
  544. package/dist/AgentError.mjs.map +0 -1
  545. package/dist/AgentPolicy.d.mts +0 -5
  546. package/dist/AgentPolicy.mjs +0 -10
  547. package/dist/AgentPolicy.mjs.map +0 -1
  548. package/dist/AgentRuntime.d.mts +0 -5
  549. package/dist/AgentRuntime.mjs +0 -10
  550. package/dist/AgentRuntime.mjs.map +0 -1
  551. package/dist/AgentUpdates.d.mts +0 -5
  552. package/dist/AgentUpdates.mjs +0 -10
  553. package/dist/AgentUpdates.mjs.map +0 -1
  554. package/dist/Approval.d.mts +0 -5
  555. package/dist/Approval.mjs +0 -10
  556. package/dist/Approval.mjs.map +0 -1
  557. package/dist/Budget.d.mts +0 -5
  558. package/dist/Budget.mjs +0 -10
  559. package/dist/Budget.mjs.map +0 -1
  560. package/dist/CodeMode.d.mts +0 -5
  561. package/dist/CodeMode.mjs +0 -10
  562. package/dist/CodeMode.mjs.map +0 -1
  563. package/dist/Commands.d.mts +0 -5
  564. package/dist/Commands.mjs +0 -10
  565. package/dist/Commands.mjs.map +0 -1
  566. package/dist/Compaction.d.mts +0 -5
  567. package/dist/Compaction.mjs +0 -10
  568. package/dist/Compaction.mjs.map +0 -1
  569. package/dist/ContextCompactor.d.mts +0 -5
  570. package/dist/ContextCompactor.mjs +0 -10
  571. package/dist/ContextCompactor.mjs.map +0 -1
  572. package/dist/ContextHistory.d.mts +0 -5
  573. package/dist/ContextHistory.mjs +0 -10
  574. package/dist/ContextHistory.mjs.map +0 -1
  575. package/dist/ContextTools.d.mts +0 -5
  576. package/dist/ContextTools.mjs +0 -10
  577. package/dist/ContextTools.mjs.map +0 -1
  578. package/dist/ContextWindow.d.mts +0 -5
  579. package/dist/ContextWindow.mjs +0 -10
  580. package/dist/ContextWindow.mjs.map +0 -1
  581. package/dist/DurableStep.d.mts +0 -5
  582. package/dist/DurableStep.mjs +0 -10
  583. package/dist/DurableStep.mjs.map +0 -1
  584. package/dist/EphemeralThreads.d.mts +0 -5
  585. package/dist/EphemeralThreads.mjs +0 -10
  586. package/dist/EphemeralThreads.mjs.map +0 -1
  587. package/dist/IdGenerator.d.mts +0 -5
  588. package/dist/IdGenerator.mjs +0 -10
  589. package/dist/IdGenerator.mjs.map +0 -1
  590. package/dist/Identifiers.d.mts +0 -5
  591. package/dist/Identifiers.mjs +0 -10
  592. package/dist/Identifiers.mjs.map +0 -1
  593. package/dist/Mcp.d.mts +0 -5
  594. package/dist/Mcp.mjs +0 -10
  595. package/dist/Mcp.mjs.map +0 -1
  596. package/dist/McpClient.d.mts +0 -5
  597. package/dist/McpClient.mjs +0 -10
  598. package/dist/McpClient.mjs.map +0 -1
  599. package/dist/Memory.d.mts +0 -5
  600. package/dist/Memory.mjs +0 -10
  601. package/dist/Memory.mjs.map +0 -1
  602. package/dist/MemoryNamespace.d.mts +0 -5
  603. package/dist/MemoryNamespace.mjs +0 -10
  604. package/dist/MemoryNamespace.mjs.map +0 -1
  605. package/dist/MemoryNotes.d.mts +0 -5
  606. package/dist/MemoryNotes.mjs +0 -10
  607. package/dist/MemoryNotes.mjs.map +0 -1
  608. package/dist/MemoryReference.d.mts +0 -5
  609. package/dist/MemoryReference.mjs +0 -10
  610. package/dist/MemoryReference.mjs.map +0 -1
  611. package/dist/MemoryRevalidation.d.mts +0 -5
  612. package/dist/MemoryRevalidation.mjs +0 -10
  613. package/dist/MemoryRevalidation.mjs.map +0 -1
  614. package/dist/MemoryStore.d.mts +0 -5
  615. package/dist/MemoryStore.mjs +0 -10
  616. package/dist/MemoryStore.mjs.map +0 -1
  617. package/dist/Messaging.d.mts +0 -5
  618. package/dist/Messaging.mjs +0 -10
  619. package/dist/Messaging.mjs.map +0 -1
  620. package/dist/MessagingHost.d.mts +0 -5
  621. package/dist/MessagingHost.mjs +0 -10
  622. package/dist/MessagingHost.mjs.map +0 -1
  623. package/dist/ModelContext.d.mts +0 -5
  624. package/dist/ModelContext.mjs +0 -10
  625. package/dist/ModelContext.mjs.map +0 -1
  626. package/dist/Receipt.d.mts +0 -5
  627. package/dist/Receipt.mjs +0 -10
  628. package/dist/Receipt.mjs.map +0 -1
  629. package/dist/Redaction.d.mts +0 -5
  630. package/dist/Redaction.mjs +0 -10
  631. package/dist/Redaction.mjs.map +0 -1
  632. package/dist/Remembering.d.mts +0 -5
  633. package/dist/Remembering.mjs +0 -10
  634. package/dist/Remembering.mjs.map +0 -1
  635. package/dist/RememberingStore.d.mts +0 -5
  636. package/dist/RememberingStore.mjs +0 -10
  637. package/dist/RememberingStore.mjs.map +0 -1
  638. package/dist/RunEvent.d.mts +0 -5
  639. package/dist/RunEvent.mjs +0 -10
  640. package/dist/RunEvent.mjs.map +0 -1
  641. package/dist/RunEventSink.d.mts +0 -5
  642. package/dist/RunEventSink.mjs +0 -10
  643. package/dist/RunEventSink.mjs.map +0 -1
  644. package/dist/RunHooks.d.mts +0 -5
  645. package/dist/RunHooks.mjs +0 -10
  646. package/dist/RunHooks.mjs.map +0 -1
  647. package/dist/RunOptions.d.mts +0 -5
  648. package/dist/RunOptions.mjs +0 -10
  649. package/dist/RunOptions.mjs.map +0 -1
  650. package/dist/RunPolicyUsage.d.mts +0 -5
  651. package/dist/RunPolicyUsage.mjs +0 -10
  652. package/dist/RunPolicyUsage.mjs.map +0 -1
  653. package/dist/SemanticMemory.d.mts +0 -5
  654. package/dist/SemanticMemory.mjs +0 -10
  655. package/dist/SemanticMemory.mjs.map +0 -1
  656. package/dist/SemanticMemoryIndex.d.mts +0 -5
  657. package/dist/SemanticMemoryIndex.mjs +0 -10
  658. package/dist/SemanticMemoryIndex.mjs.map +0 -1
  659. package/dist/SemanticMemoryRevalidation.d.mts +0 -5
  660. package/dist/SemanticMemoryRevalidation.mjs +0 -10
  661. package/dist/SemanticMemoryRevalidation.mjs.map +0 -1
  662. package/dist/Subagent.d.mts +0 -5
  663. package/dist/Subagent.mjs +0 -10
  664. package/dist/Subagent.mjs.map +0 -1
  665. package/dist/SubagentContract.d.mts +0 -5
  666. package/dist/SubagentContract.mjs +0 -10
  667. package/dist/SubagentContract.mjs.map +0 -1
  668. package/dist/SubagentHost.d.mts +0 -5
  669. package/dist/SubagentHost.mjs +0 -10
  670. package/dist/SubagentHost.mjs.map +0 -1
  671. package/dist/SubagentReservations.d.mts +0 -5
  672. package/dist/SubagentReservations.mjs +0 -10
  673. package/dist/SubagentReservations.mjs.map +0 -1
  674. package/dist/ThreadHistory.d.mts +0 -5
  675. package/dist/ThreadHistory.mjs +0 -10
  676. package/dist/ThreadHistory.mjs.map +0 -1
  677. package/dist/ToolBroker.d.mts +0 -5
  678. package/dist/ToolBroker.mjs +0 -10
  679. package/dist/ToolBroker.mjs.map +0 -1
  680. package/dist/ToolDiscovery.d.mts +0 -5
  681. package/dist/ToolDiscovery.mjs +0 -10
  682. package/dist/ToolDiscovery.mjs.map +0 -1
  683. package/dist/ToolResult.d.mts +0 -5
  684. package/dist/ToolResult.mjs +0 -10
  685. package/dist/ToolResult.mjs.map +0 -1
  686. package/dist/Usage.d.mts +0 -5
  687. package/dist/Usage.mjs +0 -10
  688. package/dist/Usage.mjs.map +0 -1
  689. package/dist/WebCapture.d.mts +0 -5
  690. package/dist/WebCapture.mjs +0 -10
  691. package/dist/WebCapture.mjs.map +0 -1
  692. package/dist/WebSearch.d.mts +0 -5
  693. package/dist/WebSearch.mjs +0 -10
  694. package/dist/WebSearch.mjs.map +0 -1
  695. package/dist/Worker.d.mts +0 -5
  696. package/dist/Worker.mjs +0 -10
  697. package/dist/Worker.mjs.map +0 -1
  698. package/dist/rolldown-runtime-BBjsoOtd.mjs +0 -27
  699. package/src/Agent.ts +0 -1
  700. package/src/AgentError.ts +0 -1
  701. package/src/AgentPolicy.ts +0 -1
  702. package/src/AgentRuntime.ts +0 -1
  703. package/src/AgentUpdates.ts +0 -1
  704. package/src/Approval.ts +0 -1
  705. package/src/Budget.ts +0 -1
  706. package/src/CodeMode.ts +0 -1
  707. package/src/Commands.ts +0 -1
  708. package/src/Compaction.ts +0 -1
  709. package/src/ContextCompactor.ts +0 -1
  710. package/src/ContextHistory.ts +0 -1
  711. package/src/ContextTools.ts +0 -1
  712. package/src/ContextWindow.ts +0 -1
  713. package/src/DurableStep.ts +0 -1
  714. package/src/EphemeralThreads.ts +0 -1
  715. package/src/IdGenerator.ts +0 -1
  716. package/src/Identifiers.ts +0 -1
  717. package/src/Mcp.ts +0 -1
  718. package/src/McpClient.ts +0 -1
  719. package/src/Memory.ts +0 -1
  720. package/src/MemoryNamespace.ts +0 -1
  721. package/src/MemoryNotes.ts +0 -1
  722. package/src/MemoryReference.ts +0 -1
  723. package/src/MemoryRevalidation.ts +0 -1
  724. package/src/MemoryStore.ts +0 -1
  725. package/src/Messaging.ts +0 -1
  726. package/src/MessagingHost.ts +0 -1
  727. package/src/ModelContext.ts +0 -1
  728. package/src/Receipt.ts +0 -1
  729. package/src/Redaction.ts +0 -1
  730. package/src/Remembering.ts +0 -1
  731. package/src/RememberingStore.ts +0 -1
  732. package/src/RunEvent.ts +0 -1
  733. package/src/RunEventSink.ts +0 -1
  734. package/src/RunHooks.ts +0 -1
  735. package/src/RunOptions.ts +0 -1
  736. package/src/RunPolicyUsage.ts +0 -1
  737. package/src/SemanticMemory.ts +0 -1
  738. package/src/SemanticMemoryIndex.ts +0 -1
  739. package/src/SemanticMemoryRevalidation.ts +0 -1
  740. package/src/Subagent.ts +0 -1
  741. package/src/SubagentContract.ts +0 -1
  742. package/src/SubagentHost.ts +0 -1
  743. package/src/SubagentReservations.ts +0 -1
  744. package/src/ThreadHistory.ts +0 -1
  745. package/src/ToolBroker.ts +0 -1
  746. package/src/ToolDiscovery.ts +0 -1
  747. package/src/ToolResult.ts +0 -1
  748. package/src/Usage.ts +0 -1
  749. package/src/WebCapture.ts +0 -1
  750. package/src/WebSearch.ts +0 -1
  751. package/src/Worker.ts +0 -1
@@ -0,0 +1,2277 @@
1
+ import type { Layer } from "effect";
2
+ import { Cause, Clock, Duration, Effect, Exit, Option, Ref, Schema, Scope } from "effect";
3
+ import { Tool, Toolkit } from "effect/unstable/ai";
4
+
5
+ import {
6
+ type Definition,
7
+ type InputPromptSource,
8
+ type InstructionSource,
9
+ type RunDispositionDeclaration,
10
+ } from "../core/Agent.ts";
11
+ import type { AgentPolicy } from "../core/AgentPolicy.ts";
12
+ import { type AgentId, DelegationId, ToolCallId } from "../core/Identifiers.ts";
13
+ import { IdGenerator } from "../core/IdGenerator.ts";
14
+ import { utf8ByteLength } from "../core/internal/utf8.ts";
15
+ import type { SubagentDelegationCaps } from "../core/SubagentContract.ts";
16
+ import {
17
+ DelegationTool,
18
+ narrowSubagentGrant,
19
+ SubagentBudgetReservation,
20
+ SubagentGrant,
21
+ SubagentReservationAmounts,
22
+ } from "../core/SubagentContract.ts";
23
+ import { type RunTotals, RunUsageReport, unknownRunTotals } from "../core/Usage.ts";
24
+ import {
25
+ type AgentRuntimeFailure,
26
+ type AgentRuntimeRequirements,
27
+ AgentSpawner,
28
+ type AgentSpawnerParent,
29
+ type AgentSpawnerService,
30
+ type RuntimeBinding,
31
+ type SpawnRunOptions,
32
+ SubagentDurability,
33
+ type SubagentDurabilityDurable,
34
+ SubagentDurabilityError,
35
+ ToolCallWaiting,
36
+ } from "../engine/AgentRuntime.ts";
37
+ import {
38
+ RunEventSink,
39
+ type SubagentEventBasePayload,
40
+ type SubagentEventPayload,
41
+ } from "../engine/RunEventSink.ts";
42
+ import {
43
+ type RunContextPreparation,
44
+ type RunBudgetHook,
45
+ type RunSubagentChildIdentity,
46
+ type RunSubagentDigests,
47
+ type RunUsageDelta,
48
+ } from "../engine/RunOptions.ts";
49
+ import { type ThreadHistory } from "../engine/ThreadHistory.ts";
50
+ import type {
51
+ SubagentPolicy,
52
+ SubagentExecutionFailureClassification,
53
+ } from "./internal/subagent-contract.ts";
54
+ import {
55
+ SubagentPrestartDenied,
56
+ SubagentProjectionFailure,
57
+ SubagentExecutionFailure,
58
+ maxErrorTagLength,
59
+ } from "./internal/subagent-contract.ts";
60
+ import {
61
+ resolveSubagentPolicy,
62
+ resolveToolCallAllowance,
63
+ residualSubagentCaps,
64
+ } from "./internal/subagent-policy.ts";
65
+ import {
66
+ type BudgetReservationId,
67
+ makeBudgetReservationId,
68
+ SubagentBudgetExhausted,
69
+ SubagentObservedUsage,
70
+ SubagentReservationRequest,
71
+ SubagentReservations,
72
+ } from "./SubagentReservations.ts";
73
+
74
+ export { WorkerCompletion } from "../core/Worker.ts";
75
+
76
+ export { SubagentGrant } from "../core/SubagentContract.ts";
77
+
78
+ export {
79
+ SubagentPolicy,
80
+ type SubagentPolicyInput,
81
+ SubagentPrestartDenied,
82
+ SubagentProjectionFailure,
83
+ SubagentExecutionFailureClassification,
84
+ SubagentExecutionFailure,
85
+ delegationCapsFromPolicy,
86
+ delegationAllocationFromPolicy,
87
+ } from "./internal/subagent-contract.ts";
88
+
89
+ import {
90
+ background as backgroundDeclaration,
91
+ type BackgroundOptions,
92
+ type Declaration,
93
+ } from "./internal/subagent-background.ts";
94
+
95
+ const decodeDelegationId = Schema.decodeSync(DelegationId);
96
+
97
+ /**
98
+ * Bounded parent metadata visible to `prepareInput`.
99
+ * It never contains the parent transcript, prompt, or a root runtime Context.
100
+ */
101
+ export type SubagentPrepareContext = {
102
+ readonly delegationId: DelegationId;
103
+ } & (
104
+ | {
105
+ readonly source: "tool";
106
+ readonly toolCallId: ToolCallId;
107
+ readonly parent: AgentSpawnerParent;
108
+ }
109
+ | {
110
+ readonly source: "programmatic";
111
+ readonly parent: Pick<AgentSpawnerParent, "agentId" | "threadId">;
112
+ }
113
+ );
114
+
115
+ /**
116
+ * Bounded framework context handed to `projectResult` (SUB-034).
117
+ * `budgetExhausted` is true exactly when the child settled through the
118
+ * final-answer exhaustion resolution (RUN-018) — on the ephemeral path from
119
+ * the child result's `finishReason`, on the durable path from the child
120
+ * Settlement's honest marker — so the projection can surface a
121
+ * budget-truncated partial to the orchestrator.
122
+ */
123
+ export interface SubagentResultContext {
124
+ readonly budgetExhausted: boolean;
125
+ /** Own and disjoint attached-descendant usage; absent only for legacy/custom hosts. */
126
+ readonly usage?: RunTotals;
127
+ readonly delegatedUsage?: RunTotals;
128
+ }
129
+
130
+ /** Default delegation result, preserving partial-output information. */
131
+ export const SubagentResult = <Output extends Schema.Top>(output: Output) =>
132
+ Schema.Struct({ output, budgetExhausted: Schema.Boolean });
133
+
134
+ export type SubagentResult<Output extends Schema.Top> = ReturnType<typeof SubagentResult<Output>>;
135
+
136
+ /**
137
+ * The delegation Tool failure Schema: the author's declared failure plus the
138
+ * framework's preflight/budget/projection/durable-execution failure family.
139
+ * With the default `failureMode: "error"`, exactly
140
+ * this union (plus Effect AI's own error) can enter the parent handler `E`.
141
+ *
142
+ * The engine-owned `ToolCallWaiting` suspension signal and the typed
143
+ * `SubagentDurabilityError` are members so the durable branch's waiting
144
+ * signal and coordinator-seam failures travel typed through
145
+ * `failureMode: "error"` (S2 plan §2); neither ever reaches an ephemeral
146
+ * caller, and a waiting signal is not a Tool failure — the batch executor
147
+ * keeps the raising call open and suspends the Run.
148
+ */
149
+ export type SubagentToolFailure<Failure extends Schema.Top> = Schema.Union<
150
+ readonly [
151
+ Failure,
152
+ typeof SubagentPrestartDenied,
153
+ typeof SubagentBudgetExhausted,
154
+ typeof SubagentProjectionFailure,
155
+ typeof SubagentExecutionFailure,
156
+ typeof ToolCallWaiting,
157
+ typeof SubagentDurabilityError,
158
+ ]
159
+ >;
160
+
161
+ /**
162
+ * Resolution for expected delegation failures (SUB-033, ADR-0019 S2).
163
+ * `"error"` (the default) keeps today's semantics: every expected failure
164
+ * travels the Effect error channel and fails the parent Tool batch (D-008).
165
+ * `"return"` contains them: the declared child failure and the framework
166
+ * failure family become model-visible result data instead of parent-fatal
167
+ * errors, so one dead child cannot detonate the whole parent Run.
168
+ *
169
+ * Effect AI's native `failureMode: "return"` is deliberately NOT used: its
170
+ * `Stream.catch` converts every handler failure into a result, which would
171
+ * encode the engine-owned `ToolCallWaiting` suspension signal as data and
172
+ * silently orphan a durable child. Containment therefore lives in the
173
+ * delegation handler — the underlying Tool keeps Effect AI
174
+ * `failureMode: "error"`, the Tool success Schema widens to a union of the
175
+ * declared success and the contained failure family, and exactly
176
+ * `ToolCallWaiting` and `SubagentDurabilityError` stay in the error channel,
177
+ * preserving durable suspension semantics by construction.
178
+ */
179
+ export type SubagentFailureMode = "error" | "return";
180
+
181
+ /**
182
+ * The failure family that becomes model-visible result data under
183
+ * `failureMode: "return"`: the author-declared failure plus every expected
184
+ * framework delegation failure. The engine-signal members are excluded by
185
+ * construction.
186
+ */
187
+ export type SubagentContainedFailure<Failure extends Schema.Top> = Schema.Union<
188
+ readonly [
189
+ Failure,
190
+ typeof SubagentPrestartDenied,
191
+ typeof SubagentBudgetExhausted,
192
+ typeof SubagentProjectionFailure,
193
+ typeof SubagentExecutionFailure,
194
+ ]
195
+ >;
196
+
197
+ /**
198
+ * The only failures a `"return"`-mode delegation Tool can raise: the
199
+ * engine-owned waiting signal (consumed by the batch executor, never a Tool
200
+ * failure) and the durable coordinator-seam error. Neither ever reaches an
201
+ * ephemeral caller.
202
+ */
203
+ export type SubagentReturnModeFailure = Schema.Union<
204
+ readonly [typeof ToolCallWaiting, typeof SubagentDurabilityError]
205
+ >;
206
+
207
+ /**
208
+ * The native Effect AI Tool created by `Subagent.make` (SUB-001, SUB-003).
209
+ * Its per-call dependencies are exactly the engine-provided `AgentSpawner`,
210
+ * `RunEventSink`, and `SubagentDurability`; every child
211
+ * requirement except the inherited Thread history policy is a construction requirement
212
+ * of `Subagent.layer`. The engine excludes its own per-batch services from the runtime's
213
+ * public requirements. Runtime IDs use the overridable default reference.
214
+ */
215
+ export type SubagentTool<
216
+ Name extends string,
217
+ Parameters extends Schema.Top,
218
+ Success extends Schema.Top,
219
+ Failure extends Schema.Top,
220
+ Mode extends SubagentFailureMode = "error",
221
+ > = Mode extends "return"
222
+ ? Tool.Tool<
223
+ Name,
224
+ {
225
+ readonly parameters: Parameters;
226
+ readonly success: Schema.Union<readonly [Success, SubagentContainedFailure<Failure>]>;
227
+ readonly failure: SubagentReturnModeFailure;
228
+ readonly failureMode: "error";
229
+ },
230
+ AgentSpawner | RunEventSink | SubagentDurability
231
+ >
232
+ : Tool.Tool<
233
+ Name,
234
+ {
235
+ readonly parameters: Parameters;
236
+ readonly success: Success;
237
+ readonly failure: SubagentToolFailure<Failure>;
238
+ readonly failureMode: "error";
239
+ },
240
+ AgentSpawner | RunEventSink | SubagentDurability
241
+ >;
242
+
243
+ /** Singleton Tool record provided by one `Subagent.layer`. */
244
+ export type SubagentTools<
245
+ Name extends string,
246
+ Parameters extends Schema.Top,
247
+ Success extends Schema.Top,
248
+ Failure extends Schema.Top,
249
+ Mode extends SubagentFailureMode = "error",
250
+ > = {
251
+ readonly [Key in Name]: SubagentTool<Name, Parameters, Success, Failure, Mode>;
252
+ };
253
+
254
+ /** Explicit options accepted by `Subagent.make`. */
255
+ export interface SubagentDefineOptions<
256
+ TargetInput extends Schema.Top,
257
+ TargetOutput extends Schema.Top,
258
+ TargetInstructions,
259
+ TargetTools extends Record<string, Tool.Any>,
260
+ Parameters extends Schema.Top,
261
+ Success extends Schema.Top,
262
+ Failure extends Schema.Top,
263
+ PrepareRequirements = never,
264
+ ProjectRequirements = never,
265
+ Mode extends SubagentFailureMode = "error",
266
+ > {
267
+ /**
268
+ * Expected-failure resolution (SUB-033): `"error"` (default) fails the
269
+ * parent Tool batch; `"return"` contains the declared failure and the
270
+ * framework failure family as model-visible result data while
271
+ * `ToolCallWaiting`/`SubagentDurabilityError` stay in the error channel.
272
+ */
273
+ readonly failureMode?: Mode;
274
+ /** Model-visible description of the delegated capability. */
275
+ readonly description?: string | undefined;
276
+ /** The model-agnostic child Agent Definition this delegation targets (SUB-002). */
277
+ readonly target: Definition<
278
+ TargetInput,
279
+ TargetOutput,
280
+ TargetInstructions,
281
+ Toolkit.Toolkit<TargetTools>,
282
+ RunDispositionDeclaration<TargetOutput["Type"], Schema.Top> | undefined,
283
+ unknown,
284
+ Schema.Top | undefined
285
+ >;
286
+ /** Schema for the model-decoded delegation parameters. */
287
+ readonly parameters: Parameters;
288
+ /** Schema for the bounded parent Tool result. */
289
+ readonly success: Success;
290
+ /** Schema for the author-declared delegation failure data. */
291
+ readonly failure: Failure;
292
+ /**
293
+ * Effectful, typed projection from decoded parameters and bounded parent
294
+ * metadata to the child Agent input. It never
295
+ * receives the parent transcript or a root Context; its expected failures
296
+ * are already the declared Tool failure.
297
+ */
298
+ readonly prepareInput: (
299
+ parameters: Parameters["Type"],
300
+ context: SubagentPrepareContext,
301
+ ) => Effect.Effect<
302
+ TargetInput["Type"],
303
+ Failure["Type"] | SubagentProjectionFailure,
304
+ PrepareRequirements
305
+ >;
306
+ /**
307
+ * Bounded result projection from the Schema-decoded child output, result
308
+ * context, and original Schema-decoded Tool parameters to the declared Tool
309
+ * success value. This is the explicit
310
+ * declassification boundary for child output: the parameters let it bind
311
+ * echoed identity and scope to the exact request without prompt parsing.
312
+ * The context carries the
313
+ * framework's honest exhaustion marker (SUB-034): when `budgetExhausted` is
314
+ * true the child settled through the final-answer resolution (RUN-018) and
315
+ * its output is a budget-truncated partial — surface it in the declared
316
+ * success Schema so the orchestrator can decide to re-delegate with a
317
+ * raised `toolCallAllowance`.
318
+ */
319
+ readonly projectResult: (
320
+ output: TargetOutput["Type"],
321
+ context: SubagentResultContext,
322
+ parameters: Parameters["Type"],
323
+ ) => Effect.Effect<
324
+ Success["Type"],
325
+ Failure["Type"] | SubagentProjectionFailure,
326
+ ProjectRequirements
327
+ >;
328
+ /**
329
+ * Per-invocation child Tool Call allowance (SUB-034): a tightening-only
330
+ * bound below the child Definition's own `maxToolCalls`, additionally
331
+ * clamped to this delegation's `SubagentPolicy.maxToolCalls` (the
332
+ * per-invocation reservation slice). `fromParameters` lets the orchestrator
333
+ * model grant a larger allowance through an author-owned parameter field —
334
+ * the budget-extension flow is a fresh re-delegation with a raised
335
+ * allowance, never a mid-flight top-up. Durable establishment records the
336
+ * effective allowance before child admission and restores it on every Attempt.
337
+ */
338
+ readonly toolCallAllowance?:
339
+ | {
340
+ /** Applied when `fromParameters` is absent or yields nothing. */
341
+ readonly default: number;
342
+ /** Extract the model-granted allowance from the decoded parameters. */
343
+ readonly fromParameters?: (parameters: Parameters["Type"]) => number | undefined;
344
+ }
345
+ | undefined;
346
+ /** Per-child ceilings. When omitted, reserve from the parent policy's shared delegation pool. */
347
+ readonly policy?: SubagentPolicy | undefined;
348
+ /**
349
+ * Authority ceiling for the child. Defaults to
350
+ * exactly the target's declared Tool names at depth ceiling one. The engine
351
+ * exposes only permitted Tools; nested launches also require depth and lifetime authority.
352
+ */
353
+ readonly grant?: SubagentGrant | undefined;
354
+ /**
355
+ * Native Effect AI approval metadata for establishment only (SUB-026):
356
+ * parent approval never authorizes child actions, siblings, or retries.
357
+ */
358
+ readonly needsApproval?: Tool.NeedsApproval<Parameters> | undefined;
359
+ }
360
+
361
+ /**
362
+ * An immutable Subagent capability: one target Agent Definition exposed to
363
+ * a parent as one Effect AI Tool with explicit projections, policy, and
364
+ * authority ceiling. It owns no acquired resources and
365
+ * is not executable until `Subagent.layer` supplies the child's model Layer.
366
+ */
367
+ export interface SubagentDelegation<
368
+ Name extends string,
369
+ TargetInput extends Schema.Top,
370
+ TargetOutput extends Schema.Top,
371
+ TargetInstructions,
372
+ TargetTools extends Record<string, Tool.Any>,
373
+ Parameters extends Schema.Top,
374
+ Success extends Schema.Top,
375
+ Failure extends Schema.Top,
376
+ PrepareRequirements = never,
377
+ ProjectRequirements = never,
378
+ Mode extends SubagentFailureMode = "error",
379
+ > extends SubagentDefineOptions<
380
+ TargetInput,
381
+ TargetOutput,
382
+ TargetInstructions,
383
+ TargetTools,
384
+ Parameters,
385
+ Success,
386
+ Failure,
387
+ PrepareRequirements,
388
+ ProjectRequirements,
389
+ Mode
390
+ > {
391
+ readonly name: Name;
392
+ /** Stable delegation identity; S1 derives it from the unique Tool name. */
393
+ readonly delegationId: DelegationId;
394
+ readonly grant: SubagentGrant;
395
+ /** The resolved expected-failure resolution (SUB-033); never absent after `make`. */
396
+ readonly failureMode: Mode;
397
+ /**
398
+ * The canonical contained-failure family for this delegation (SUB-033):
399
+ * the declared failure plus the framework members. Consumers that classify
400
+ * returned failure data (for example a coverage gate) MUST decode through
401
+ * this value rather than reconstructing the union, so a framework change
402
+ * to the contained family can never diverge from their decoder.
403
+ */
404
+ readonly containedFailure: SubagentContainedFailure<Failure>;
405
+ /** The real Effect AI Tool to include in the parent Toolkit (SUB-001). */
406
+ readonly tool: SubagentTool<Name, Parameters, Success, Failure, Mode>;
407
+ }
408
+
409
+ /**
410
+ * Declare one attached delegation as a pure value.
411
+ *
412
+ * The returned `.tool` is a native Effect AI Tool whose handler dependencies
413
+ * are exactly the engine-owned `AgentSpawner`, `RunEventSink`, and
414
+ * `SubagentDurability` (SUB-003); runtime IDs have an overridable default.
415
+ * The concrete child Binding arrives only through
416
+ * `Subagent.layer`. Throws on an invalid delegation name. Nested declarations remain inert unless the
417
+ * effective inherited grant and reserved subtree budget permit their lifetime and depth.
418
+ */
419
+ const makeExplicit = <
420
+ const Name extends string,
421
+ TargetInput extends Schema.Top,
422
+ TargetOutput extends Schema.Top,
423
+ TargetInstructions,
424
+ TargetTools extends Record<string, Tool.Any>,
425
+ Parameters extends Schema.Top,
426
+ Success extends Schema.Top,
427
+ Failure extends Schema.Top,
428
+ PrepareRequirements = never,
429
+ ProjectRequirements = never,
430
+ Mode extends SubagentFailureMode = "error",
431
+ >(
432
+ name: Name,
433
+ options: SubagentDefineOptions<
434
+ TargetInput,
435
+ TargetOutput,
436
+ TargetInstructions,
437
+ TargetTools,
438
+ Parameters,
439
+ Success,
440
+ Failure,
441
+ PrepareRequirements,
442
+ ProjectRequirements,
443
+ Mode
444
+ >,
445
+ ): SubagentDelegation<
446
+ Name,
447
+ TargetInput,
448
+ TargetOutput,
449
+ TargetInstructions,
450
+ TargetTools,
451
+ Parameters,
452
+ Success,
453
+ Failure,
454
+ PrepareRequirements,
455
+ ProjectRequirements,
456
+ Mode
457
+ > => {
458
+ const delegationId = decodeDelegationId(name);
459
+
460
+ const grant =
461
+ options.grant ??
462
+ SubagentGrant.make({
463
+ allowedToolNames: Object.keys(options.target.toolkit.tools),
464
+ maxDepth: 1,
465
+ });
466
+
467
+ // `Mode` defaults to `"error"` exactly when `failureMode` is absent, so the
468
+ // resolved literal always inhabits `Mode`; the assertion bridges only that
469
+ // inference gap and crosses no schema boundary.
470
+ const failureMode = (options.failureMode ?? "error") as Mode;
471
+
472
+ const containedFailure = Schema.Union([
473
+ options.failure,
474
+ SubagentPrestartDenied,
475
+ SubagentBudgetExhausted,
476
+ SubagentProjectionFailure,
477
+ SubagentExecutionFailure,
478
+ ]);
479
+
480
+ const returnModeTool = Tool.make(name, {
481
+ description: options.description,
482
+ parameters: options.parameters,
483
+ // Containment (SUB-033): the contained failure family is model-visible
484
+ // RESULT data, so it lives in the success union; only the engine-signal
485
+ // members remain raisable. The underlying Effect AI failureMode stays
486
+ // "error" so the waiting signal is never encoded as a result.
487
+ success: Schema.Union([options.success, containedFailure]),
488
+ failure: Schema.Union([ToolCallWaiting, SubagentDurabilityError]),
489
+ needsApproval: options.needsApproval,
490
+ });
491
+
492
+ const errorModeTool = Tool.make(name, {
493
+ description: options.description,
494
+ parameters: options.parameters,
495
+ success: options.success,
496
+ failure: Schema.Union([
497
+ options.failure,
498
+ SubagentPrestartDenied,
499
+ SubagentBudgetExhausted,
500
+ SubagentProjectionFailure,
501
+ SubagentExecutionFailure,
502
+ ToolCallWaiting,
503
+ SubagentDurabilityError,
504
+ ]),
505
+ needsApproval: options.needsApproval,
506
+ });
507
+
508
+ // Each branch is exactly `SubagentTool<..., Mode>` at its concrete `Mode`;
509
+ // TypeScript cannot relate a runtime branch to the conditional generic, so
510
+ // this assertion bridges only that limitation and crosses no schema
511
+ // boundary (the schemas above are constructed per mode, never reinterpreted).
512
+ const tool = (failureMode === "return" ? returnModeTool : errorModeTool)
513
+ .annotate(DelegationTool, true)
514
+ .addDependency(AgentSpawner)
515
+ .addDependency(RunEventSink)
516
+ .addDependency(SubagentDurability)
517
+ .addDependency(IdGenerator) as unknown as SubagentTool<
518
+ Name,
519
+ Parameters,
520
+ Success,
521
+ Failure,
522
+ Mode
523
+ >;
524
+
525
+ return Object.freeze({
526
+ ...options,
527
+ name,
528
+ delegationId,
529
+ grant,
530
+ failureMode,
531
+ containedFailure,
532
+ tool,
533
+ });
534
+ };
535
+
536
+ /** Pure Subagent authoring surface. */
537
+ /** Optional authoring fields; schemas default to the child's input and result envelope. */
538
+ export type SubagentDeclarationOptions<
539
+ Input extends Schema.Top,
540
+ Output extends Schema.Top,
541
+ Instructions,
542
+ Tools extends Record<string, Tool.Any>,
543
+ Parameters extends Schema.Top,
544
+ Success extends Schema.Top,
545
+ Failure extends Schema.Top,
546
+ Prepare,
547
+ Project,
548
+ Mode extends SubagentFailureMode,
549
+ > = Omit<
550
+ SubagentDefineOptions<
551
+ Input,
552
+ Output,
553
+ Instructions,
554
+ Tools,
555
+ Parameters,
556
+ Success,
557
+ Failure,
558
+ Prepare,
559
+ Project,
560
+ Mode
561
+ >,
562
+ "parameters" | "success" | "failure" | "prepareInput" | "projectResult"
563
+ > & {
564
+ readonly parameters?: Parameters;
565
+ readonly success?: Success;
566
+ readonly failure?: Failure;
567
+ readonly prepareInput?: SubagentDefineOptions<
568
+ Input,
569
+ Output,
570
+ Instructions,
571
+ Tools,
572
+ Parameters,
573
+ Success,
574
+ Failure,
575
+ Prepare,
576
+ Project,
577
+ Mode
578
+ >["prepareInput"];
579
+ readonly projectResult?: SubagentDefineOptions<
580
+ Input,
581
+ Output,
582
+ Instructions,
583
+ Tools,
584
+ Parameters,
585
+ Success,
586
+ Failure,
587
+ Prepare,
588
+ Project,
589
+ Mode
590
+ >["projectResult"];
591
+ };
592
+
593
+ /**
594
+ * Expose one child Agent as an attached Effect AI Tool. The nonempty application
595
+ * name is preserved as both Tool name and delegation identity; no prefix is required.
596
+ * Parameters and result projections default to the child's input and result envelope.
597
+ * Throws when the name is empty. Nested Tool visibility follows the effective inherited grant.
598
+ */
599
+ function make<
600
+ const Name extends string,
601
+ Input extends Schema.Top,
602
+ Output extends Schema.Top,
603
+ Instructions,
604
+ Tools extends Record<string, Tool.Any>,
605
+ Parameters extends Schema.Top = Input,
606
+ Success extends Schema.Top = SubagentResult<Output>,
607
+ Failure extends Schema.Top = typeof Schema.Never,
608
+ Prepare = never,
609
+ Project = never,
610
+ Target extends Definition<
611
+ Input,
612
+ Output,
613
+ Instructions,
614
+ Toolkit.Toolkit<Tools>,
615
+ RunDispositionDeclaration<Output["Type"], Schema.Top> | undefined,
616
+ unknown,
617
+ Schema.Top | undefined
618
+ > = Definition<
619
+ Input,
620
+ Output,
621
+ Instructions,
622
+ Toolkit.Toolkit<Tools>,
623
+ RunDispositionDeclaration<Output["Type"], Schema.Top> | undefined,
624
+ unknown,
625
+ Schema.Top | undefined
626
+ >,
627
+ >(
628
+ name: Name,
629
+ options: SubagentDeclarationOptions<
630
+ Input,
631
+ Output,
632
+ Instructions,
633
+ Tools,
634
+ Parameters,
635
+ Success,
636
+ Failure,
637
+ Prepare,
638
+ Project,
639
+ "return"
640
+ > & { readonly failureMode: "return"; readonly target: Target },
641
+ ): SubagentDelegation<
642
+ Name,
643
+ Input,
644
+ Output,
645
+ Instructions,
646
+ Tools,
647
+ Parameters,
648
+ Success,
649
+ Failure,
650
+ Prepare,
651
+ Project,
652
+ "return"
653
+ > & { readonly target: Target };
654
+ function make<
655
+ const Name extends string,
656
+ Input extends Schema.Top,
657
+ Output extends Schema.Top,
658
+ Instructions,
659
+ Tools extends Record<string, Tool.Any>,
660
+ Parameters extends Schema.Top = Input,
661
+ Success extends Schema.Top = SubagentResult<Output>,
662
+ Failure extends Schema.Top = typeof Schema.Never,
663
+ Prepare = never,
664
+ Project = never,
665
+ Target extends Definition<
666
+ Input,
667
+ Output,
668
+ Instructions,
669
+ Toolkit.Toolkit<Tools>,
670
+ RunDispositionDeclaration<Output["Type"], Schema.Top> | undefined,
671
+ unknown,
672
+ Schema.Top | undefined
673
+ > = Definition<
674
+ Input,
675
+ Output,
676
+ Instructions,
677
+ Toolkit.Toolkit<Tools>,
678
+ RunDispositionDeclaration<Output["Type"], Schema.Top> | undefined,
679
+ unknown,
680
+ Schema.Top | undefined
681
+ >,
682
+ >(
683
+ name: Name,
684
+ options: SubagentDeclarationOptions<
685
+ Input,
686
+ Output,
687
+ Instructions,
688
+ Tools,
689
+ Parameters,
690
+ Success,
691
+ Failure,
692
+ Prepare,
693
+ Project,
694
+ "error"
695
+ > & { readonly target: Target },
696
+ ): SubagentDelegation<
697
+ Name,
698
+ Input,
699
+ Output,
700
+ Instructions,
701
+ Tools,
702
+ Parameters,
703
+ Success,
704
+ Failure,
705
+ Prepare,
706
+ Project
707
+ > & { readonly target: Target };
708
+ function make<
709
+ const Name extends string,
710
+ Input extends Schema.Top,
711
+ Output extends Schema.Top,
712
+ Instructions,
713
+ Tools extends Record<string, Tool.Any>,
714
+ Parameters extends Schema.Top,
715
+ Success extends Schema.Top,
716
+ Failure extends Schema.Top,
717
+ Prepare,
718
+ Project,
719
+ >(
720
+ name: Name,
721
+ options: SubagentDeclarationOptions<
722
+ Input,
723
+ Output,
724
+ Instructions,
725
+ Tools,
726
+ Parameters,
727
+ Success,
728
+ Failure,
729
+ Prepare,
730
+ Project,
731
+ SubagentFailureMode
732
+ >,
733
+ ): unknown {
734
+ const success: Schema.Codec<
735
+ Success["Type"] | SubagentResult<Output>["Type"],
736
+ Success["Encoded"] | SubagentResult<Output>["Encoded"],
737
+ Success["DecodingServices"] | Output["DecodingServices"],
738
+ Success["EncodingServices"] | Output["EncodingServices"]
739
+ > = options.success ?? SubagentResult(options.target.output);
740
+
741
+ const parameters = options.parameters ?? options.target.input;
742
+
743
+ const failure: Schema.Codec<
744
+ Failure["Type"],
745
+ Failure["Encoded"],
746
+ Failure["DecodingServices"],
747
+ Failure["EncodingServices"]
748
+ > = options.failure ?? Schema.Never;
749
+
750
+ const inputValue = Schema.decodeUnknownEffect(Schema.toType(options.target.input));
751
+ const resultValue = Schema.decodeUnknownEffect(Schema.toType(success));
752
+ const needsApproval = options.needsApproval;
753
+ const prepareInput = options.prepareInput;
754
+ const projectResult = options.projectResult;
755
+
756
+ const projectionFailure = (stage: "input" | "result") =>
757
+ SubagentProjectionFailure.make({
758
+ delegationId: decodeDelegationId(name),
759
+ stage,
760
+ message:
761
+ stage === "input"
762
+ ? "Delegation parameters did not satisfy the child input Schema"
763
+ : "Child output did not satisfy the delegation success Schema",
764
+ });
765
+
766
+ const resolved = {
767
+ ...options,
768
+ needsApproval:
769
+ typeof needsApproval === "function"
770
+ ? (input: Parameters["Type"], context: Tool.NeedsApprovalContext) =>
771
+ needsApproval(input, context)
772
+ : needsApproval,
773
+ description: options.description ?? options.target.description,
774
+ parameters,
775
+ success,
776
+ failure,
777
+ prepareInput: (input: Parameters["Type"], context: SubagentPrepareContext) =>
778
+ prepareInput === undefined
779
+ ? inputValue(input).pipe(Effect.mapError(() => projectionFailure("input")))
780
+ : prepareInput(input, context),
781
+ projectResult: (
782
+ output: Output["Type"],
783
+ context: SubagentResultContext,
784
+ input: Parameters["Type"],
785
+ ) =>
786
+ projectResult === undefined
787
+ ? resultValue({ output, budgetExhausted: context.budgetExhausted }).pipe(
788
+ Effect.mapError(() => projectionFailure("result")),
789
+ )
790
+ : projectResult(output, context, input),
791
+ };
792
+
793
+ return options.failureMode === "return"
794
+ ? makeExplicit<
795
+ Name,
796
+ Input,
797
+ Output,
798
+ Instructions,
799
+ Tools,
800
+ Input | Parameters,
801
+ typeof success,
802
+ typeof failure,
803
+ Prepare,
804
+ Project,
805
+ "return"
806
+ >(name, { ...resolved, failureMode: "return" })
807
+ : makeExplicit<
808
+ Name,
809
+ Input,
810
+ Output,
811
+ Instructions,
812
+ Tools,
813
+ Input | Parameters,
814
+ typeof success,
815
+ typeof failure,
816
+ Prepare,
817
+ Project
818
+ >(name, { ...resolved, failureMode: "error" });
819
+ }
820
+
821
+ export { make };
822
+
823
+ /** @deprecated Use `Subagent.make`. */
824
+ export const define: typeof make = make;
825
+
826
+ type InstructionResultOf<Instructions, Input> = Instructions extends (input: Input) => infer Result
827
+ ? Result
828
+ : Instructions;
829
+
830
+ type InstructionErrorOf<Instructions, Input> =
831
+ InstructionResultOf<Instructions, Input> extends Effect.Effect<
832
+ infer _Success,
833
+ infer Error,
834
+ infer _Requirements
835
+ >
836
+ ? Error
837
+ : never;
838
+
839
+ type InstructionRequirementsOf<Instructions, Input> =
840
+ InstructionResultOf<Instructions, Input> extends Effect.Effect<
841
+ infer _Success,
842
+ infer _Error,
843
+ infer Requirements
844
+ >
845
+ ? Requirements
846
+ : never;
847
+
848
+ /**
849
+ * Every expected child Run failure the delegation's total mapping must cover:
850
+ * the child's inferred Agent failures plus
851
+ * the interpreter's policy, protocol, and approval failures. Interruption and
852
+ * defects are not members; they retain their distinct semantics.
853
+ */
854
+ export type SubagentChildRunFailure<
855
+ TargetInput extends Schema.Top,
856
+ TargetOutput extends Schema.Top,
857
+ TargetInstructions,
858
+ TargetTools extends Record<string, Tool.Any>,
859
+ Provider,
860
+ ModelProvides,
861
+ ModelRequires,
862
+ InstructionError = InstructionErrorOf<TargetInstructions, TargetInput["Type"]>,
863
+ InstructionRequirements = InstructionRequirementsOf<TargetInstructions, TargetInput["Type"]>,
864
+ InputPromptValue extends InputPromptSource<TargetInput["Type"], unknown, unknown> | undefined =
865
+ undefined,
866
+ UpdatesSchema extends Schema.Top | undefined = undefined,
867
+ RunDispositionValue extends
868
+ | RunDispositionDeclaration<TargetOutput["Type"], Schema.Top>
869
+ | undefined = undefined,
870
+ > = AgentRuntimeFailure<
871
+ RuntimeBinding<
872
+ TargetInput,
873
+ TargetOutput,
874
+ TargetInstructions,
875
+ TargetTools,
876
+ Provider,
877
+ ModelProvides,
878
+ ModelRequires,
879
+ InstructionError,
880
+ InstructionRequirements,
881
+ RunDispositionValue,
882
+ InputPromptValue,
883
+ UpdatesSchema
884
+ >,
885
+ never,
886
+ InstructionError
887
+ >;
888
+
889
+ /**
890
+ * Construction requirements of one `Subagent.layer`: the child
891
+ * Binding's full runtime requirements (Model Layer requirements, child Tool
892
+ * handlers and their services, Schema services), both projection
893
+ * requirements, and the parent-owned reservation service. Nothing here leaks
894
+ * into the per-call Tool handler requirements. ThreadHistory and RunContextPreparation belong
895
+ * to the parent Run's AgentSpawner and are inherited at invocation rather than captured here.
896
+ */
897
+ export type SubagentLayerRequirements<
898
+ TargetInput extends Schema.Top,
899
+ TargetOutput extends Schema.Top,
900
+ TargetInstructions,
901
+ TargetTools extends Record<string, Tool.Any>,
902
+ Provider,
903
+ ModelProvides,
904
+ ModelRequires,
905
+ PrepareRequirements,
906
+ ProjectRequirements,
907
+ HookRequirements = never,
908
+ InstructionError = InstructionErrorOf<TargetInstructions, TargetInput["Type"]>,
909
+ InstructionRequirements = InstructionRequirementsOf<TargetInstructions, TargetInput["Type"]>,
910
+ InputPromptValue extends InputPromptSource<TargetInput["Type"], unknown, unknown> | undefined =
911
+ undefined,
912
+ UpdatesSchema extends Schema.Top | undefined = undefined,
913
+ RunDispositionValue extends
914
+ | RunDispositionDeclaration<TargetOutput["Type"], Schema.Top>
915
+ | undefined = undefined,
916
+ > =
917
+ | Exclude<
918
+ AgentRuntimeRequirements<
919
+ RuntimeBinding<
920
+ TargetInput,
921
+ TargetOutput,
922
+ TargetInstructions,
923
+ TargetTools,
924
+ Provider,
925
+ ModelProvides,
926
+ ModelRequires,
927
+ InstructionError,
928
+ InstructionRequirements,
929
+ RunDispositionValue,
930
+ InputPromptValue,
931
+ UpdatesSchema
932
+ >,
933
+ HookRequirements,
934
+ InstructionRequirements
935
+ >,
936
+ ThreadHistory | RunContextPreparation
937
+ >
938
+ | TargetInput["EncodingServices"]
939
+ | PrepareRequirements
940
+ | ProjectRequirements
941
+ | SubagentReservations;
942
+
943
+ /**
944
+ * Optional construction-fixed digest override for durable delegation.
945
+ * The coordinator normally resolves the exact target Definition through its
946
+ * existing host registration. An override must agree with that registration.
947
+ */
948
+ export interface SubagentDurableOptions {
949
+ /**
950
+ * Exact digests from the target's host registration. Fixed once at handler
951
+ * Layer construction and checked against that registration at establishment.
952
+ * Recovery uses the canonical request's recorded digests, never current code.
953
+ */
954
+ readonly targetDigests: RunSubagentDigests;
955
+ }
956
+
957
+ /**
958
+ * The conservative final accounting summary the durable delegation handler
959
+ * attaches to every settlement join. The handler has no live child usage stream at durable join
960
+ * time, so every dimension conservatively consumes its full reservation and
961
+ * releases nothing — unreported usage never creates budget. The coordinator
962
+ * owns the canonical accounting decision on `SubagentJoined` and may replace
963
+ * structural dimensions from canonical child evidence; this value is opaque
964
+ * encoded policy math to the engine and to storage adapters (D8).
965
+ */
966
+ export class SubagentDurableAccounting extends Schema.Class<SubagentDurableAccounting>(
967
+ "@effect-agent/capabilities/SubagentDurableAccounting",
968
+ )({
969
+ /** The per-invocation allocation reserved at establishment. */
970
+ allocation: SubagentReservationAmounts,
971
+ /** Final consumed decision per dimension. */
972
+ consumed: SubagentReservationAmounts,
973
+ /** Amounts returned to the parent: `allocation - consumed` per dimension. */
974
+ released: SubagentReservationAmounts,
975
+ /** How the decision was computed; the handler only ever reports conservatively. */
976
+ basis: Schema.Literals(["reserved-conservative"]),
977
+ }) {}
978
+
979
+ /** Options accepted by `Subagent.layer`. */
980
+ export interface SubagentRuntimeOptions<
981
+ Failure extends Schema.Top,
982
+ ChildFailure,
983
+ HookRequirements = never,
984
+ > {
985
+ /**
986
+ * Optional exact digest override. Without it, the durable coordinator resolves
987
+ * the target Definition from its existing host registrations.
988
+ */
989
+ readonly durable?: SubagentDurableOptions | undefined;
990
+ /**
991
+ * Total mapping from every expected child Run failure to the declared Tool
992
+ * failure (SUB-028). The parameter type is the child Binding's complete
993
+ * expected failure union, so a mapping that covers only part of it is a
994
+ * compile error. Interruption stays interruption and defects stay defects;
995
+ * neither reaches this mapping.
996
+ * When omitted, failures become bounded `SubagentExecutionFailure` values.
997
+ */
998
+ readonly mapChildFailure?: ((failure: ChildFailure) => Failure["Type"]) | undefined;
999
+ /**
1000
+ * Override the parent-Run delegation caps registered with
1001
+ * `SubagentReservations`. An explicit policy uses `delegationCapsFromPolicy(policy)`;
1002
+ * an omitted policy uses one pool sized from the parent policy.
1003
+ * Supply shared caps explicitly when one parent Run uses several delegation
1004
+ * Tools, because re-registering different caps denies start fail-closed.
1005
+ */
1006
+ readonly parentCaps?: SubagentDelegationCaps | undefined;
1007
+ /**
1008
+ * Seed child Run options (approval, context, input hooks) so child actions
1009
+ * follow their own ordinary approval and policy (SUB-026). Hook failures
1010
+ * must be handled inside the hook (`never` in `E`); a supplied budget hook
1011
+ * is composed after the reservation's own usage observation.
1012
+ */
1013
+ readonly child?: SpawnRunOptions<never, HookRequirements> | undefined;
1014
+ }
1015
+
1016
+ const maxEventTextLength = 4 * 1024;
1017
+
1018
+ const boundedEventText = (text: string): string =>
1019
+ text.length <= maxEventTextLength ? text : `${text.slice(0, maxEventTextLength - 1)}…`;
1020
+
1021
+ const ErrorMessage = Schema.Struct({ message: Schema.String });
1022
+ const ErrorTag = Schema.Struct({ _tag: Schema.NonEmptyString });
1023
+
1024
+ const errorMessageOf = (error: unknown): string =>
1025
+ Option.match(Schema.decodeUnknownOption(ErrorMessage)(error), {
1026
+ onNone: () => String(error),
1027
+ onSome: ({ message }) => message,
1028
+ });
1029
+
1030
+ const errorTagOf = (error: unknown): string =>
1031
+ Option.match(Schema.decodeUnknownOption(ErrorTag)(error), {
1032
+ onNone: () => "UnknownError",
1033
+ onSome: ({ _tag }) => _tag,
1034
+ });
1035
+
1036
+ const boundedErrorTag = (tag: string): string => {
1037
+ const nonEmpty = tag.length === 0 ? "UnknownError" : tag;
1038
+
1039
+ return nonEmpty.length <= maxErrorTagLength ? nonEmpty : nonEmpty.slice(0, maxErrorTagLength);
1040
+ };
1041
+
1042
+ /**
1043
+ * The coordinator's bounded projection of a failed/aborted child Settlement
1044
+ * result (S2 plan §1.6, D5): `{errorTag, message}`, never a raw Cause. The
1045
+ * fallback tolerates any other bounded shape without ever surfacing the raw
1046
+ * value beyond a tag and message.
1047
+ */
1048
+ const ChildFailureProjection = Schema.Struct({
1049
+ errorTag: Schema.NonEmptyString,
1050
+ message: Schema.String,
1051
+ });
1052
+
1053
+ const childFailureProjectionOf = (
1054
+ encodedResult: unknown,
1055
+ ): { readonly errorTag: string; readonly message: string } =>
1056
+ Option.match(Schema.decodeUnknownOption(ChildFailureProjection)(encodedResult), {
1057
+ onNone: () => ({
1058
+ errorTag: errorTagOf(encodedResult),
1059
+ message: errorMessageOf(encodedResult),
1060
+ }),
1061
+ onSome: (projection) => projection,
1062
+ });
1063
+
1064
+ const zeroReservationAmounts = SubagentReservationAmounts.make({
1065
+ turns: 0,
1066
+ toolCalls: 0,
1067
+ durationMillis: 0,
1068
+ inputTokens: 0,
1069
+ outputTokens: 0,
1070
+ costMicrousd: 0,
1071
+ resultBytes: 0,
1072
+ });
1073
+
1074
+ const encodeDurableAccounting = Schema.encodeEffect(SubagentDurableAccounting);
1075
+ const encodeProjectionFailure = Schema.encodeEffect(SubagentProjectionFailure);
1076
+ const encodeBudgetFailure = Schema.encodeEffect(SubagentBudgetExhausted);
1077
+ const encodeExecutionFailure = Schema.encodeEffect(SubagentExecutionFailure);
1078
+ const encodeGrant = Schema.encodeEffect(SubagentGrant);
1079
+ const encodeAllocationAmounts = Schema.encodeEffect(SubagentReservationAmounts);
1080
+
1081
+ const toNatural = (value: number): number =>
1082
+ Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
1083
+
1084
+ const observedUsageFromDelta = (delta: RunUsageDelta): SubagentObservedUsage =>
1085
+ SubagentObservedUsage.make({
1086
+ turns: delta.modelCalls,
1087
+ toolCalls: toNatural(delta.toolCalls),
1088
+ inputTokens: toNatural(delta.inputTokens),
1089
+ outputTokens: toNatural(delta.outputTokens),
1090
+ costMicrousd: toNatural(delta.costMicrousd),
1091
+ });
1092
+
1093
+ /** A child that never started consumed nothing; observing zeros releases everything. */
1094
+ const neverStartedUsage = SubagentObservedUsage.make({
1095
+ turns: 0,
1096
+ toolCalls: 0,
1097
+ durationMillis: 0,
1098
+ inputTokens: 0,
1099
+ outputTokens: 0,
1100
+ costMicrousd: 0,
1101
+ resultBytes: 0,
1102
+ });
1103
+
1104
+ /**
1105
+ * Finalizer-driven settlement: observe honest final usage, then release the
1106
+ * unused allocation exactly once. Runs on every handler exit path — success,
1107
+ * declared failure, interruption, and defect — through the reservation's
1108
+ * `Effect.acquireRelease`; a missing reservation after a successful reserve
1109
+ * is a ledger invariant violation and therefore a defect.
1110
+ */
1111
+ const settleReservation = (
1112
+ reservations: SubagentReservations["Service"],
1113
+ reservationId: BudgetReservationId,
1114
+ startedAt: Ref.Ref<number | undefined>,
1115
+ conservative?: {
1116
+ readonly parentRunId: AgentSpawnerParent["runId"];
1117
+ readonly allocation: SubagentReservationAmounts;
1118
+ },
1119
+ ): Effect.Effect<void> =>
1120
+ Effect.gen(function* () {
1121
+ const started = yield* Ref.get(startedAt);
1122
+
1123
+ if (started === undefined) {
1124
+ yield* reservations.observe(reservationId, neverStartedUsage);
1125
+ } else {
1126
+ const now = yield* Clock.currentTimeMillis;
1127
+
1128
+ yield* reservations.observe(
1129
+ reservationId,
1130
+ SubagentObservedUsage.make({ durationMillis: Math.max(0, Math.floor(now - started)) }),
1131
+ );
1132
+ }
1133
+ if (started !== undefined && conservative !== undefined) {
1134
+ const snapshot = yield* reservations.parentSnapshot(conservative.parentRunId);
1135
+ const own = snapshot.reservations.find((entry) => entry.reservationId === reservationId);
1136
+
1137
+ if (own === undefined)
1138
+ return yield* Effect.die("Missing subtree reservation during finalization");
1139
+
1140
+ const additional = (key: keyof typeof conservative.allocation) =>
1141
+ Math.max(0, conservative.allocation[key] - (own.observedConsumed[key] ?? 0));
1142
+
1143
+ yield* reservations.observe(
1144
+ reservationId,
1145
+ SubagentObservedUsage.make({
1146
+ turns: additional("turns"),
1147
+ toolCalls: additional("toolCalls"),
1148
+ durationMillis: additional("durationMillis"),
1149
+ inputTokens: additional("inputTokens"),
1150
+ outputTokens: additional("outputTokens"),
1151
+ costMicrousd: additional("costMicrousd"),
1152
+ resultBytes: additional("resultBytes"),
1153
+ }),
1154
+ );
1155
+ }
1156
+ yield* reservations.release(reservationId);
1157
+ }).pipe(Effect.orDie);
1158
+
1159
+ /**
1160
+ * Module-private provenance wrapper (SUB-033 hardening): ONLY the operations
1161
+ * that can genuinely produce the engine signals wrap them here, so
1162
+ * containment classification never trusts the runtime identity of classes an
1163
+ * author could declare in their own failure Schema — a spoofed
1164
+ * `ToolCallWaiting` in author data is contained as data, never rethrown as a
1165
+ * suspension signal.
1166
+ */
1167
+ class GenuineEngineSignal {
1168
+ readonly _tag = "GenuineEngineSignal";
1169
+ constructor(readonly signal: ToolCallWaiting | SubagentDurabilityError) {}
1170
+ }
1171
+
1172
+ const wrapEngineSignal = (signal: ToolCallWaiting | SubagentDurabilityError) =>
1173
+ new GenuineEngineSignal(signal);
1174
+
1175
+ type SubagentHandler<
1176
+ Name extends string,
1177
+ Parameters extends Schema.Top,
1178
+ Success extends Schema.Top,
1179
+ Failure extends Schema.Top,
1180
+ Mode extends SubagentFailureMode = "error",
1181
+ > = (
1182
+ parameters: Parameters["Type"],
1183
+ context: Toolkit.HandlerContext<SubagentTool<Name, Parameters, Success, Failure, Mode>>,
1184
+ ) => Effect.Effect<
1185
+ Mode extends "return"
1186
+ ? Success["Type"] | SubagentContainedFailure<Failure>["Type"]
1187
+ : Success["Type"],
1188
+ Mode extends "return" ? SubagentReturnModeFailure["Type"] : SubagentToolFailure<Failure>["Type"],
1189
+ Tool.HandlerServices<SubagentTool<Name, Parameters, Success, Failure, Mode>>
1190
+ >;
1191
+
1192
+ /**
1193
+ * Build the Toolkit handler Layer for one delegation Tool from a model Layer or
1194
+ * an explicit child Agent Binding.
1195
+ *
1196
+ * Construction requirements carry the child Binding's full runtime needs and
1197
+ * both projections; they are captured once via `Effect.context` so the
1198
+ * per-call handler requirements stay exactly the Tool's declared engine
1199
+ * dependencies. The handler dispatches on the engine-provided per-batch
1200
+ * `SubagentDurability` service mode:
1201
+ *
1202
+ * - **ephemeral** (the explicit engine default when no durable coordinator
1203
+ * supplied `RunOptions.subagent`): the S1 path unchanged — preflight, an
1204
+ * in-process scoped child Run (SUB-011/012), stable lifecycle events,
1205
+ * total-mapped expected child failures, and Scope-finalizer reservation
1206
+ * settlement on every exit path.
1207
+ * - **durable** (S2): the same fail-closed preflight and input projection,
1208
+ * then idempotent establishment through the coordinator (spec §12 steps
1209
+ * 2-9) with construction-fixed child Binding digests, encoded grant, and
1210
+ * encoded allocation; the engine-owned waiting signal while the attached
1211
+ * child is nonterminal; and, on re-entry with a settled child, output
1212
+ * decoding, `projectResult`, and ONE atomic settlement join carrying the
1213
+ * conservative accounting summary. Failed children join as the bounded
1214
+ * `SubagentExecutionFailure`; no in-process child fiber ever starts.
1215
+ */
1216
+ export const layer = <
1217
+ Name extends string,
1218
+ TargetInput extends Schema.Top,
1219
+ TargetOutput extends Schema.Top,
1220
+ TargetInstructions,
1221
+ TargetTools extends Record<string, Tool.Any>,
1222
+ Parameters extends Schema.Top,
1223
+ Success extends Schema.Top,
1224
+ Failure extends Schema.Top,
1225
+ PrepareRequirements,
1226
+ ProjectRequirements,
1227
+ Provider,
1228
+ ModelProvides,
1229
+ ModelRequires,
1230
+ HookRequirements = never,
1231
+ Mode extends SubagentFailureMode = "error",
1232
+ InstructionError = InstructionErrorOf<TargetInstructions, TargetInput["Type"]>,
1233
+ InstructionRequirements = InstructionRequirementsOf<TargetInstructions, TargetInput["Type"]>,
1234
+ InputPromptValue extends InputPromptSource<TargetInput["Type"], unknown, unknown> | undefined =
1235
+ undefined,
1236
+ UpdatesSchema extends Schema.Top | undefined = undefined,
1237
+ RunDispositionValue extends
1238
+ | RunDispositionDeclaration<TargetOutput["Type"], Schema.Top>
1239
+ | undefined = undefined,
1240
+ >(
1241
+ delegation: SubagentDelegation<
1242
+ Name,
1243
+ TargetInput,
1244
+ TargetOutput,
1245
+ TargetInstructions,
1246
+ TargetTools,
1247
+ Parameters,
1248
+ Success,
1249
+ Failure,
1250
+ PrepareRequirements,
1251
+ ProjectRequirements,
1252
+ Mode
1253
+ > & {
1254
+ readonly target: {
1255
+ readonly instructions: InstructionSource<
1256
+ TargetInput["Type"],
1257
+ NoInfer<InstructionError>,
1258
+ NoInfer<InstructionRequirements>
1259
+ >;
1260
+ readonly inputPrompt?: InputPromptValue | undefined;
1261
+ readonly updates?: UpdatesSchema | undefined;
1262
+ readonly runDisposition?: RunDispositionValue | undefined;
1263
+ };
1264
+ },
1265
+ modelOrBinding:
1266
+ | RuntimeBinding<
1267
+ TargetInput,
1268
+ TargetOutput,
1269
+ TargetInstructions,
1270
+ TargetTools,
1271
+ Provider,
1272
+ ModelProvides,
1273
+ ModelRequires,
1274
+ InstructionError,
1275
+ InstructionRequirements,
1276
+ RunDispositionValue,
1277
+ InputPromptValue,
1278
+ UpdatesSchema
1279
+ >
1280
+ | RuntimeBinding<
1281
+ TargetInput,
1282
+ TargetOutput,
1283
+ TargetInstructions,
1284
+ TargetTools,
1285
+ Provider,
1286
+ ModelProvides,
1287
+ ModelRequires,
1288
+ InstructionError,
1289
+ InstructionRequirements,
1290
+ RunDispositionValue,
1291
+ InputPromptValue,
1292
+ UpdatesSchema
1293
+ >["model"],
1294
+ options: SubagentRuntimeOptions<
1295
+ Failure,
1296
+ SubagentChildRunFailure<
1297
+ TargetInput,
1298
+ TargetOutput,
1299
+ TargetInstructions,
1300
+ TargetTools,
1301
+ Provider,
1302
+ ModelProvides,
1303
+ ModelRequires,
1304
+ InstructionError,
1305
+ InstructionRequirements,
1306
+ InputPromptValue,
1307
+ UpdatesSchema,
1308
+ RunDispositionValue
1309
+ >,
1310
+ HookRequirements
1311
+ > = {},
1312
+ ): Layer.Layer<
1313
+ Tool.HandlersFor<SubagentTools<Name, Parameters, Success, Failure, Mode>>,
1314
+ never,
1315
+ SubagentLayerRequirements<
1316
+ TargetInput,
1317
+ TargetOutput,
1318
+ TargetInstructions,
1319
+ TargetTools,
1320
+ Provider,
1321
+ ModelProvides,
1322
+ ModelRequires,
1323
+ PrepareRequirements,
1324
+ ProjectRequirements,
1325
+ HookRequirements,
1326
+ InstructionError,
1327
+ InstructionRequirements,
1328
+ InputPromptValue,
1329
+ UpdatesSchema,
1330
+ RunDispositionValue
1331
+ >
1332
+ > => {
1333
+ const childBinding =
1334
+ "definition" in modelOrBinding
1335
+ ? modelOrBinding
1336
+ : { definition: delegation.target, model: modelOrBinding };
1337
+
1338
+ if (childBinding.definition !== delegation.target) {
1339
+ throw new Error("Subagent.layer requires the delegation's exact target Definition");
1340
+ }
1341
+
1342
+ const resolvePolicy = (spawner: AgentSpawnerService) =>
1343
+ resolveSubagentPolicy(
1344
+ delegation,
1345
+ spawner.policy,
1346
+ options.parentCaps,
1347
+ spawner.depth === 0 && spawner.budget === undefined ? "root-attached" : "conserved",
1348
+ );
1349
+
1350
+ // `Toolkit.ToolsByName` cannot reduce its mapped-as key while `Name` is
1351
+ // generic (it degrades to a string index signature); at every concrete
1352
+ // `Name` the two records are identical, so this assertion bridges only that
1353
+ // compiler limitation and crosses no schema boundary.
1354
+ const toolkit = Toolkit.make(delegation.tool as Tool.Any) as unknown as Toolkit.Toolkit<
1355
+ SubagentTools<Name, Parameters, Success, Failure, Mode>
1356
+ >;
1357
+
1358
+ // Containment (SUB-033): under `failureMode: "return"` every expected
1359
+ // delegation failure becomes the handler's SUCCESS value (the Tool success
1360
+ // Schema is the union of the declared success and the contained family);
1361
+ // exactly the engine signals stay raisable, so the durable waiting
1362
+ // suspension and coordinator-seam errors keep their semantics.
1363
+ const contained = delegation.failureMode === "return";
1364
+ const encodeChildInput = Schema.encodeEffect(delegation.target.input);
1365
+ const encodeSuccess = Schema.encodeEffect(delegation.success);
1366
+ const decodeChildOutput = Schema.decodeUnknownEffect(delegation.target.output);
1367
+
1368
+ const encodeResultProjectionFailure = Schema.encodeEffect(
1369
+ Schema.Union([delegation.failure, SubagentProjectionFailure]),
1370
+ );
1371
+
1372
+ const childToolCallAllowance = (
1373
+ parameters: Parameters["Type"],
1374
+ policy: SubagentPolicy,
1375
+ childPolicy: AgentPolicy,
1376
+ ) => resolveToolCallAllowance(delegation.toolCallAllowance, parameters, policy, childPolicy);
1377
+
1378
+ // Capture an explicit digest override without retaining mutable author options.
1379
+ const durableDeclaration: SubagentDurableOptions | undefined =
1380
+ options.durable === undefined
1381
+ ? undefined
1382
+ : {
1383
+ targetDigests: {
1384
+ agent: options.durable.targetDigests.agent,
1385
+ model: options.durable.targetDigests.model,
1386
+ tools: options.durable.targetDigests.tools,
1387
+ },
1388
+ };
1389
+
1390
+ const executionFailure = (
1391
+ classification: SubagentExecutionFailureClassification,
1392
+ errorTag: string,
1393
+ message: string,
1394
+ child?: RunSubagentChildIdentity,
1395
+ ): SubagentExecutionFailure =>
1396
+ SubagentExecutionFailure.make({
1397
+ delegationId: delegation.delegationId,
1398
+ targetAgentId: delegation.target.id,
1399
+ classification,
1400
+ errorTag: boundedErrorTag(errorTag),
1401
+ message: boundedEventText(message),
1402
+ ...(child === undefined
1403
+ ? {}
1404
+ : {
1405
+ childThreadId: child.childThreadId,
1406
+ childSubmissionId: child.childSubmissionId,
1407
+ childRunId: child.childRunId,
1408
+ }),
1409
+ });
1410
+
1411
+ const prestartDenied = (
1412
+ reason: SubagentPrestartDenied["reason"],
1413
+ message: string,
1414
+ ): SubagentPrestartDenied =>
1415
+ SubagentPrestartDenied.make({
1416
+ delegationId: delegation.delegationId,
1417
+ targetAgentId: delegation.target.id,
1418
+ reason,
1419
+ message: boundedEventText(message),
1420
+ });
1421
+
1422
+ const build = Effect.gen(function* () {
1423
+ const captured =
1424
+ yield* Effect.context<
1425
+ SubagentLayerRequirements<
1426
+ TargetInput,
1427
+ TargetOutput,
1428
+ TargetInstructions,
1429
+ TargetTools,
1430
+ Provider,
1431
+ ModelProvides,
1432
+ ModelRequires,
1433
+ PrepareRequirements,
1434
+ ProjectRequirements,
1435
+ HookRequirements,
1436
+ InstructionError,
1437
+ InstructionRequirements,
1438
+ InputPromptValue,
1439
+ UpdatesSchema,
1440
+ RunDispositionValue
1441
+ >
1442
+ >();
1443
+
1444
+ const invoke = Effect.fn(`SubagentRuntime.${delegation.name}`)(function* (
1445
+ parameters: Parameters["Type"],
1446
+ handlerContext: Toolkit.HandlerContext<
1447
+ SubagentTool<Name, Parameters, Success, Failure, Mode>
1448
+ >,
1449
+ ) {
1450
+ const spawner = yield* AgentSpawner;
1451
+ const resolved = resolvePolicy(spawner);
1452
+ const { policy, childPolicy, allocation } = resolved;
1453
+
1454
+ const caps =
1455
+ spawner.budget === undefined
1456
+ ? resolved.caps
1457
+ : residualSubagentCaps(
1458
+ resolved.caps,
1459
+ spawner.policy,
1460
+ spawner.budget,
1461
+ spawner.budgetScope === "worker-run",
1462
+ );
1463
+
1464
+ const sink = yield* RunEventSink;
1465
+ const reservations = yield* SubagentReservations;
1466
+
1467
+ // The interpreter supplies the parent Tool Call identity for every
1468
+ // executed Tool Call; its absence is an engine defect, not an expected
1469
+ // failure of the delegation.
1470
+ const toolCallId = yield* Schema.decodeUnknownEffect(ToolCallId)(
1471
+ handlerContext.toolCallId,
1472
+ ).pipe(Effect.orDie);
1473
+
1474
+ const grant = narrowSubagentGrant(delegation.grant, spawner.grant);
1475
+ const depth = spawner.depth + 1;
1476
+
1477
+ if (depth > grant.maxDepth) {
1478
+ return yield* prestartDenied(
1479
+ "nested-delegation",
1480
+ "Delegation exceeds the inherited depth ceiling",
1481
+ );
1482
+ }
1483
+ if (!(spawner.grant?.childLifetimes ?? ["attached", "background"]).includes("attached")) {
1484
+ return yield* prestartDenied(
1485
+ "grant-violation",
1486
+ "The inherited grant does not permit attached children",
1487
+ );
1488
+ }
1489
+ if (spawner.depth > 0 && spawner.budget === undefined) {
1490
+ return yield* prestartDenied(
1491
+ "budget-conflict",
1492
+ "Nested ephemeral delegation requires an inherited subtree reservation",
1493
+ );
1494
+ }
1495
+
1496
+ const prepared = yield* delegation.prepareInput(parameters, {
1497
+ source: "tool",
1498
+ delegationId: delegation.delegationId,
1499
+ toolCallId,
1500
+ parent: spawner.parent,
1501
+ });
1502
+
1503
+ const encodedInput = yield* encodeChildInput(prepared).pipe(
1504
+ Effect.mapError(() =>
1505
+ SubagentProjectionFailure.make({
1506
+ delegationId: delegation.delegationId,
1507
+ stage: "input",
1508
+ message: "Prepared child input did not satisfy the target Agent input Schema",
1509
+ }),
1510
+ ),
1511
+ );
1512
+
1513
+ const parentRunId = spawner.parent.runId;
1514
+
1515
+ yield* reservations
1516
+ .registerParent(parentRunId, caps)
1517
+ .pipe(
1518
+ Effect.catchTag("SubagentParentBudgetConflict", () =>
1519
+ Effect.fail(
1520
+ prestartDenied(
1521
+ "budget-conflict",
1522
+ "The parent Run is already registered with different delegation caps; supply shared parentCaps explicitly",
1523
+ ),
1524
+ ),
1525
+ ),
1526
+ );
1527
+
1528
+ const reservationId = makeBudgetReservationId(parentRunId, toolCallId);
1529
+ const startedAt = yield* Ref.make<number | undefined>(undefined);
1530
+
1531
+ // Reservation settlement is finalizer-driven from this point on: every
1532
+ // exit path — success, declared failure, interruption, defect — settles
1533
+ // accounting exactly once when the handler scope closes.
1534
+ yield* Effect.acquireRelease(
1535
+ reservations
1536
+ .reserve(
1537
+ SubagentReservationRequest.make({
1538
+ parentRunId,
1539
+ parentToolCallId: toolCallId,
1540
+ allocation,
1541
+ ...(policy.descendantInvocations === undefined
1542
+ ? {}
1543
+ : { descendantInvocations: policy.descendantInvocations }),
1544
+ }),
1545
+ )
1546
+ .pipe(
1547
+ // A same-key conflict or unregistered parent after a successful
1548
+ // registerParent is a ledger invariant violation, not an expected
1549
+ // delegation failure.
1550
+ Effect.catchTags({
1551
+ SubagentReservationConflict: (conflict) => Effect.die(conflict),
1552
+ SubagentParentBudgetUnknown: (unknown) => Effect.die(unknown),
1553
+ }),
1554
+ ),
1555
+ () =>
1556
+ settleReservation(
1557
+ reservations,
1558
+ reservationId,
1559
+ startedAt,
1560
+ (policy.descendantInvocations ?? 0) > 0 ? { parentRunId, allocation } : undefined,
1561
+ ),
1562
+ );
1563
+ // Scope-owned concurrency permit: interruption while queued frees the
1564
+ // slot, and the settlement finalizer above releases the reservation.
1565
+ yield* reservations
1566
+ .acquireChildSlot(parentRunId, 1 + (policy.descendantInvocations ?? 0))
1567
+ .pipe(Effect.catchTag("SubagentParentBudgetUnknown", (unknown) => Effect.die(unknown)));
1568
+
1569
+ const seededChild = options.child;
1570
+ const seededBudget = seededChild?.budget;
1571
+
1572
+ const budget: RunBudgetHook<never, HookRequirements> = {
1573
+ guard:
1574
+ seededBudget === undefined ? (effect) => effect : (effect) => seededBudget.guard(effect),
1575
+ consume: (delta) =>
1576
+ reservations
1577
+ .observe(reservationId, observedUsageFromDelta(delta))
1578
+ .pipe(
1579
+ Effect.orDie,
1580
+ Effect.andThen(
1581
+ seededBudget === undefined ? Effect.void : seededBudget.consume(delta),
1582
+ ),
1583
+ ),
1584
+ };
1585
+
1586
+ const toolCallAllowance = childToolCallAllowance(parameters, policy, childPolicy);
1587
+
1588
+ const childOptions: SpawnRunOptions<never, HookRequirements> = {
1589
+ ...seededChild,
1590
+ subagentGrant: grant,
1591
+ delegationDepth: depth,
1592
+ subagentBudget: SubagentBudgetReservation.make({
1593
+ caps,
1594
+ allocation,
1595
+ ...(policy.descendantInvocations === undefined
1596
+ ? {}
1597
+ : { descendantInvocations: policy.descendantInvocations }),
1598
+ }),
1599
+ budget,
1600
+ ...(toolCallAllowance === undefined ? {} : { toolCallAllowance }),
1601
+ };
1602
+
1603
+ yield* Ref.set(startedAt, yield* Clock.currentTimeMillis);
1604
+
1605
+ const childScope = yield* Scope.make();
1606
+
1607
+ yield* Effect.addFinalizer((exit) => Scope.close(childScope, exit));
1608
+
1609
+ const child = yield* spawner
1610
+ .spawn<
1611
+ TargetInput,
1612
+ TargetOutput,
1613
+ TargetInstructions,
1614
+ TargetTools,
1615
+ Provider,
1616
+ ModelProvides,
1617
+ ModelRequires,
1618
+ never,
1619
+ HookRequirements,
1620
+ InstructionError,
1621
+ InstructionRequirements,
1622
+ RunDispositionValue,
1623
+ InputPromptValue,
1624
+ UpdatesSchema
1625
+ >(
1626
+ { ...childBinding, definition: { ...childBinding.definition, policy: childPolicy } },
1627
+ encodedInput,
1628
+ { delegationId: delegation.delegationId, parentToolCallId: toolCallId },
1629
+ childOptions,
1630
+ )
1631
+ .pipe(Scope.provide(childScope));
1632
+
1633
+ const payload: SubagentEventBasePayload = {
1634
+ toolCallId,
1635
+ delegationId: delegation.delegationId,
1636
+ childThreadId: child.threadId,
1637
+ childRunId: child.runId,
1638
+ targetAgentId: delegation.target.id,
1639
+ depth: child.parentLink.depth,
1640
+ };
1641
+
1642
+ // The sink cannot be closed while this Tool batch is live; a closed
1643
+ // sink here is an engine defect.
1644
+ const emit = (event: SubagentEventPayload): Effect.Effect<void> =>
1645
+ sink.emit(event).pipe(Effect.orDie);
1646
+
1647
+ yield* emit({ _tag: "SubagentRequested", ...payload });
1648
+ yield* emit({ _tag: "SubagentStarted", ...payload });
1649
+
1650
+ const joined = Effect.gen(function* () {
1651
+ const result = yield* child.await.pipe(
1652
+ Effect.catch((childFailure) =>
1653
+ child.usageReport.pipe(
1654
+ Effect.flatMap((report) =>
1655
+ emit({
1656
+ _tag: "SubagentFailed",
1657
+ ...payload,
1658
+ ...report,
1659
+ errorTag: errorTagOf(childFailure),
1660
+ message: boundedEventText(errorMessageOf(childFailure)),
1661
+ }),
1662
+ ),
1663
+ Effect.andThen(
1664
+ Effect.fail(
1665
+ options.mapChildFailure === undefined
1666
+ ? executionFailure(
1667
+ "child-failed",
1668
+ errorTagOf(childFailure),
1669
+ "The child Run failed",
1670
+ )
1671
+ : options.mapChildFailure(childFailure),
1672
+ ),
1673
+ ),
1674
+ ),
1675
+ ),
1676
+ Effect.timeoutOrElse({
1677
+ duration: Duration.millis(allocation.durationMillis),
1678
+ orElse: () => Effect.succeed(undefined),
1679
+ }),
1680
+ Effect.tapCause((cause) =>
1681
+ Cause.hasDies(cause)
1682
+ ? child.usageReport.pipe(
1683
+ Effect.flatMap((report) =>
1684
+ emit({
1685
+ _tag: "SubagentFailed",
1686
+ ...payload,
1687
+ ...report,
1688
+ errorTag: "Defect",
1689
+ message: "The child Run ended with a defect",
1690
+ }),
1691
+ ),
1692
+ Effect.ignore,
1693
+ )
1694
+ : Effect.void,
1695
+ ),
1696
+ );
1697
+
1698
+ if (result === undefined) {
1699
+ // Choose the timeout before interrupting the child; otherwise its interrupted await
1700
+ // can win the timeout race and replace the typed delegation failure.
1701
+ yield* Scope.close(childScope, Exit.void);
1702
+ const report = yield* child.usageReport;
1703
+
1704
+ yield* emit({
1705
+ _tag: "SubagentFailed",
1706
+ ...payload,
1707
+ ...report,
1708
+ errorTag: "SubagentBudgetExhausted",
1709
+ message: `Attached child exceeded its ${allocation.durationMillis}ms delegation duration budget`,
1710
+ });
1711
+
1712
+ return yield* SubagentBudgetExhausted.make({
1713
+ parentRunId,
1714
+ dimension: "duration",
1715
+ limitValue: allocation.durationMillis,
1716
+ observedValue: allocation.durationMillis,
1717
+ });
1718
+ }
1719
+ const report = yield* child.usageReport;
1720
+
1721
+ yield* emit({
1722
+ _tag: "SubagentCompleted",
1723
+ ...payload,
1724
+ ...report,
1725
+ turns: result.turns,
1726
+ finishReason: result.finishReason,
1727
+ ...(result.exhausted !== undefined ? { exhausted: result.exhausted } : {}),
1728
+ });
1729
+
1730
+ const projected = yield* delegation.projectResult(
1731
+ result.output,
1732
+ {
1733
+ budgetExhausted: result.finishReason === "budget-exhausted",
1734
+ ...report,
1735
+ },
1736
+ parameters,
1737
+ );
1738
+
1739
+ const encodedResult = yield* encodeSuccess(projected).pipe(
1740
+ Effect.mapError(() =>
1741
+ SubagentProjectionFailure.make({
1742
+ delegationId: delegation.delegationId,
1743
+ stage: "result",
1744
+ message: "Projected child result did not satisfy the delegation success Schema",
1745
+ }),
1746
+ ),
1747
+ );
1748
+
1749
+ const resultBytes = utf8ByteLength(JSON.stringify(encodedResult) ?? "");
1750
+
1751
+ yield* reservations
1752
+ .observe(reservationId, SubagentObservedUsage.make({ resultBytes }))
1753
+ .pipe(Effect.orDie);
1754
+ if (policy.maxResultBytes !== undefined && resultBytes > policy.maxResultBytes) {
1755
+ yield* emit({
1756
+ _tag: "SubagentFailed",
1757
+ ...payload,
1758
+ ...report,
1759
+ errorTag: "SubagentBudgetExhausted",
1760
+ message: `Projected child result of ${resultBytes} bytes exceeds the ${policy.maxResultBytes}-byte delegation budget`,
1761
+ });
1762
+
1763
+ return yield* SubagentBudgetExhausted.make({
1764
+ parentRunId,
1765
+ dimension: "result-bytes",
1766
+ limitValue: policy.maxResultBytes,
1767
+ observedValue: resultBytes,
1768
+ });
1769
+ }
1770
+ yield* emit({ _tag: "SubagentJoined", ...payload, ...report });
1771
+
1772
+ return projected;
1773
+ });
1774
+
1775
+ // Join the interrupted child before observing its final usage. Keep the original
1776
+ // interruption even when the closing parent can no longer accept lifecycle events.
1777
+ return yield* joined.pipe(
1778
+ Effect.onInterrupt(() =>
1779
+ Scope.close(childScope, Exit.void).pipe(
1780
+ Effect.andThen(child.usageReport),
1781
+ Effect.flatMap((report) =>
1782
+ sink.emit({
1783
+ _tag: "SubagentInterrupted",
1784
+ ...payload,
1785
+ ...report,
1786
+ reason: "Parent Run interrupted the attached child before it settled",
1787
+ }),
1788
+ ),
1789
+ Effect.ignore,
1790
+ ),
1791
+ ),
1792
+ );
1793
+ });
1794
+
1795
+ /**
1796
+ * Durable branch: establishment through the
1797
+ * coordinator's idempotent protocol instead of an in-process spawn. No
1798
+ * child fiber ever starts here, and the S1 in-memory reservation service
1799
+ * is deliberately not consulted — its Scope-finalizer settlement
1800
+ * contradicts a handler that exits with the waiting signal while the
1801
+ * child keeps running; durable budget lives in the coordinator's fenced
1802
+ * ledger reservation built from `encodedAllocation`.
1803
+ */
1804
+ const invokeDurable = Effect.fn(`SubagentRuntime.${delegation.name}.durable`)(function* (
1805
+ parameters: Parameters["Type"],
1806
+ handlerContext: Toolkit.HandlerContext<
1807
+ SubagentTool<Name, Parameters, Success, Failure, Mode>
1808
+ >,
1809
+ durability: SubagentDurabilityDurable,
1810
+ ) {
1811
+ const spawner = yield* AgentSpawner;
1812
+ const { policy, childPolicy, allocation, caps } = resolvePolicy(spawner);
1813
+ const encodedAllocation = yield* encodeAllocationAmounts(allocation).pipe(Effect.orDie);
1814
+
1815
+ const conservativeAccounting = yield* encodeDurableAccounting(
1816
+ SubagentDurableAccounting.make({
1817
+ allocation,
1818
+ consumed: allocation,
1819
+ released: zeroReservationAmounts,
1820
+ basis: "reserved-conservative",
1821
+ }),
1822
+ ).pipe(Effect.orDie);
1823
+
1824
+ const sink = yield* RunEventSink;
1825
+
1826
+ const toolCallId = yield* Schema.decodeUnknownEffect(ToolCallId)(
1827
+ handlerContext.toolCallId,
1828
+ ).pipe(Effect.orDie);
1829
+
1830
+ const emit = (event: SubagentEventPayload): Effect.Effect<void> =>
1831
+ sink.emit(event).pipe(Effect.orDie);
1832
+
1833
+ // Resume cannot restore authority removed by an ancestor.
1834
+ const grant = narrowSubagentGrant(delegation.grant, spawner.grant);
1835
+ const depth = spawner.depth + 1;
1836
+
1837
+ if (depth > grant.maxDepth) {
1838
+ return yield* prestartDenied(
1839
+ "nested-delegation",
1840
+ "Delegation exceeds the inherited depth ceiling",
1841
+ );
1842
+ }
1843
+ if (!(spawner.grant?.childLifetimes ?? ["attached", "background"]).includes("attached")) {
1844
+ return yield* prestartDenied(
1845
+ "grant-violation",
1846
+ "The inherited grant does not permit attached children",
1847
+ );
1848
+ }
1849
+ const encodedGrant = yield* encodeGrant(grant).pipe(Effect.orDie);
1850
+
1851
+ const prepared = yield* delegation.prepareInput(parameters, {
1852
+ source: "tool",
1853
+ delegationId: delegation.delegationId,
1854
+ toolCallId,
1855
+ parent: spawner.parent,
1856
+ });
1857
+
1858
+ const encodedInput = yield* encodeChildInput(prepared).pipe(
1859
+ Effect.mapError(() =>
1860
+ SubagentProjectionFailure.make({
1861
+ delegationId: delegation.delegationId,
1862
+ stage: "input",
1863
+ message: "Prepared child input did not satisfy the target Agent input Schema",
1864
+ }),
1865
+ ),
1866
+ );
1867
+
1868
+ // Establishment is idempotent by construction (SUB-016): the identical
1869
+ // request replays spec §12 steps 2-9 under the parent fence and
1870
+ // converges on the one existing child; a divergent replay (changed
1871
+ // digests, grant, allocation, or input) is denied fail-closed by the
1872
+ // coordinator and surfaces below as `"establishment-denied"`.
1873
+ const status = yield* Effect.mapError(wrapEngineSignal)(
1874
+ durability.establish({
1875
+ toolCallId,
1876
+ delegationId: delegation.delegationId,
1877
+ target: delegation.target,
1878
+ targetAgentId: delegation.target.id,
1879
+ depth,
1880
+ ...(durableDeclaration === undefined
1881
+ ? {}
1882
+ : { targetDigests: durableDeclaration.targetDigests }),
1883
+ encodedChildInput: encodedInput,
1884
+ encodedGrant,
1885
+ encodedAllocation,
1886
+ toolCallAllowance: childToolCallAllowance(parameters, policy, childPolicy),
1887
+ policy: childPolicy,
1888
+ budget: {
1889
+ caps,
1890
+ allocation,
1891
+ ...(policy.descendantInvocations === undefined
1892
+ ? {}
1893
+ : { descendantInvocations: policy.descendantInvocations }),
1894
+ },
1895
+ }),
1896
+ );
1897
+
1898
+ switch (status._tag) {
1899
+ case "denied": {
1900
+ return yield* executionFailure("establishment-denied", status.errorTag, status.message);
1901
+ }
1902
+ case "waiting": {
1903
+ const payload: SubagentEventBasePayload = {
1904
+ toolCallId,
1905
+ delegationId: delegation.delegationId,
1906
+ childThreadId: status.childThreadId,
1907
+ childRunId: status.childRunId,
1908
+ targetAgentId: delegation.target.id,
1909
+ depth,
1910
+ };
1911
+
1912
+ yield* emit({ _tag: "SubagentRequested", ...payload });
1913
+ yield* emit({ _tag: "SubagentStarted", ...payload });
1914
+
1915
+ // The handler ends here and never returns: the engine keeps the
1916
+ // call open (no Tool failure, no batch failure policy), siblings
1917
+ // finish, and the Run suspends waitingForChild — never polling,
1918
+ // never respawning (SUB-018, SUB-030).
1919
+ return yield* Effect.mapError(wrapEngineSignal)(durability.waiting(toolCallId, status));
1920
+ }
1921
+ case "settled": {
1922
+ const payload: SubagentEventBasePayload = {
1923
+ toolCallId,
1924
+ delegationId: delegation.delegationId,
1925
+ childThreadId: status.childThreadId,
1926
+ childRunId: status.childRunId,
1927
+ targetAgentId: delegation.target.id,
1928
+ depth,
1929
+ };
1930
+
1931
+ const report = RunUsageReport.make({
1932
+ usage: status.usage ?? unknownRunTotals(),
1933
+ delegatedUsage: status.delegatedUsage ?? unknownRunTotals(),
1934
+ });
1935
+
1936
+ // Every terminal projection of a settled child — success or typed
1937
+ // failure — goes through ONE atomic join (SUB-019): the coordinator
1938
+ // appends `SubagentJoined` + the parent `ToolCallSettled` in one
1939
+ // canonical batch and applies the accounting decision. The handler
1940
+ // then fails/returns the same value so the live batch continues
1941
+ // with exactly what canonical history recorded.
1942
+ const settleFailure = <F>(
1943
+ failure: F,
1944
+ encodedFailure: unknown,
1945
+ ): Effect.Effect<never, F | GenuineEngineSignal> =>
1946
+ emit({
1947
+ _tag: "SubagentFailed",
1948
+ ...payload,
1949
+ ...report,
1950
+ errorTag: errorTagOf(failure),
1951
+ message: boundedEventText(errorMessageOf(failure)),
1952
+ }).pipe(
1953
+ Effect.andThen(
1954
+ Effect.mapError(wrapEngineSignal)(
1955
+ durability.join({
1956
+ toolCallId,
1957
+ encodedResult: encodedFailure,
1958
+ // Canonical history must record exactly what the live
1959
+ // batch continues with (SUB-019): under containment the
1960
+ // failure is the call's model-visible RESULT (the dispatch
1961
+ // wrapper converts the fail below into a success), so the
1962
+ // joined settlement records it as a non-failure result;
1963
+ // the child's own failed Settlement and the
1964
+ // `SubagentFailed` event stay the honest failure record.
1965
+ isFailure: !contained,
1966
+ encodedAccounting: conservativeAccounting,
1967
+ }),
1968
+ ),
1969
+ ),
1970
+ Effect.andThen(Effect.fail(failure)),
1971
+ );
1972
+
1973
+ if (status.outcome !== "completed") {
1974
+ const projection = childFailureProjectionOf(status.encodedResult);
1975
+
1976
+ const failure = executionFailure(
1977
+ status.outcome === "aborted"
1978
+ ? "child-aborted"
1979
+ : projection.errorTag === "ChildCompatibilityFailure"
1980
+ ? "child-compatibility"
1981
+ : "child-failed",
1982
+ projection.errorTag,
1983
+ projection.message,
1984
+ status,
1985
+ );
1986
+
1987
+ const encodedFailure = yield* encodeExecutionFailure(failure).pipe(Effect.orDie);
1988
+
1989
+ return yield* settleFailure(failure, encodedFailure);
1990
+ }
1991
+
1992
+ // The coordinator already verified lineage, target, digests, and
1993
+ // settlement identity fail-closed (spec §12 join steps 1-2); the
1994
+ // handler still refuses settled output that escapes the target
1995
+ // output Schema — hostile child output cannot cross the
1996
+ // declassification boundary undecoded, and the fixed message never
1997
+ // carries the raw value.
1998
+ const decoded = yield* decodeChildOutput(status.encodedResult).pipe(
1999
+ Effect.catch(() => {
2000
+ const failure = SubagentProjectionFailure.make({
2001
+ delegationId: delegation.delegationId,
2002
+ stage: "result",
2003
+ message: "Settled child output did not satisfy the target Agent output Schema",
2004
+ });
2005
+
2006
+ return encodeProjectionFailure(failure).pipe(
2007
+ Effect.orDie,
2008
+ Effect.flatMap((encodedFailure) => settleFailure(failure, encodedFailure)),
2009
+ );
2010
+ }),
2011
+ );
2012
+
2013
+ const projected = yield* delegation
2014
+ .projectResult(
2015
+ decoded,
2016
+ {
2017
+ budgetExhausted: status.finishReason === "budget-exhausted",
2018
+ ...report,
2019
+ },
2020
+ parameters,
2021
+ )
2022
+ .pipe(
2023
+ Effect.catch((declared) =>
2024
+ encodeResultProjectionFailure(declared).pipe(
2025
+ Effect.orDie,
2026
+ Effect.flatMap((encodedFailure) => settleFailure(declared, encodedFailure)),
2027
+ ),
2028
+ ),
2029
+ );
2030
+
2031
+ const encodedResult = yield* encodeSuccess(projected).pipe(
2032
+ Effect.catch(() => {
2033
+ const failure = SubagentProjectionFailure.make({
2034
+ delegationId: delegation.delegationId,
2035
+ stage: "result",
2036
+ message: "Projected child result did not satisfy the delegation success Schema",
2037
+ });
2038
+
2039
+ return encodeProjectionFailure(failure).pipe(
2040
+ Effect.orDie,
2041
+ Effect.flatMap((encodedFailure) => settleFailure(failure, encodedFailure)),
2042
+ );
2043
+ }),
2044
+ );
2045
+
2046
+ const resultBytes = utf8ByteLength(JSON.stringify(encodedResult) ?? "");
2047
+
2048
+ if (policy.maxResultBytes !== undefined && resultBytes > policy.maxResultBytes) {
2049
+ const failure = SubagentBudgetExhausted.make({
2050
+ parentRunId: spawner.parent.runId,
2051
+ dimension: "result-bytes",
2052
+ limitValue: policy.maxResultBytes,
2053
+ observedValue: resultBytes,
2054
+ });
2055
+
2056
+ const encodedFailure = yield* encodeBudgetFailure(failure).pipe(Effect.orDie);
2057
+
2058
+ return yield* settleFailure(failure, encodedFailure);
2059
+ }
2060
+ yield* Effect.mapError(wrapEngineSignal)(
2061
+ durability.join({
2062
+ toolCallId,
2063
+ encodedResult,
2064
+ isFailure: false,
2065
+ encodedAccounting: conservativeAccounting,
2066
+ }),
2067
+ );
2068
+ yield* emit({ _tag: "SubagentJoined", ...payload, ...report });
2069
+
2070
+ return projected;
2071
+ }
2072
+ }
2073
+ });
2074
+
2075
+ // Containment boundary (SUB-033): under `"return"`, every expected
2076
+ // delegation failure becomes the handler's success value; exactly the
2077
+ // GENUINE engine signals re-fail unwrapped. Provenance comes from the
2078
+ // module-private `GenuineEngineSignal` wrapper applied at the only
2079
+ // operations that can produce those signals — an author-declared failure
2080
+ // that happens to use the exported signal classes is contained as data,
2081
+ // never rethrown as a suspension signal.
2082
+ const containSignals = (
2083
+ failure: SubagentToolFailure<Failure>["Type"] | GenuineEngineSignal,
2084
+ ): Effect.Effect<
2085
+ SubagentContainedFailure<Failure>["Type"],
2086
+ ToolCallWaiting | SubagentDurabilityError
2087
+ > =>
2088
+ failure instanceof GenuineEngineSignal
2089
+ ? Effect.fail(failure.signal)
2090
+ : Effect.succeed(failure);
2091
+
2092
+ // Error mode still unwraps genuine signals so the engine sees the raw
2093
+ // `ToolCallWaiting`/`SubagentDurabilityError` it owns.
2094
+ const unwrapSignals = (
2095
+ failure: SubagentToolFailure<Failure>["Type"] | GenuineEngineSignal,
2096
+ ): SubagentToolFailure<Failure>["Type"] =>
2097
+ failure instanceof GenuineEngineSignal ? failure.signal : failure;
2098
+
2099
+ const handlerImpl = (
2100
+ parameters: Parameters["Type"],
2101
+ handlerContext: Toolkit.HandlerContext<
2102
+ SubagentTool<Name, Parameters, Success, Failure, Mode>
2103
+ >,
2104
+ ) =>
2105
+ Effect.gen(function* () {
2106
+ // Resolve the engine-provided per-call services before providing the
2107
+ // captured construction context and re-provide them innermost: if the
2108
+ // Layer was constructed inside another Run's Tool batch, the captured
2109
+ // context would otherwise shadow this Run's `AgentSpawner` (and its
2110
+ // delegation depth), this batch's live `RunEventSink`, and this
2111
+ // batch's live `SubagentDurability` mode.
2112
+ const spawner = yield* AgentSpawner;
2113
+ const sink = yield* RunEventSink;
2114
+ const durability = yield* SubagentDurability;
2115
+
2116
+ // Service-mode dispatch (S2 plan §2): the engine states ephemeral
2117
+ // mode explicitly when no durable coordinator supplied the hook, so
2118
+ // absence keeps the S1 in-process spawn semantics honestly.
2119
+ if (durability.mode === "durable") {
2120
+ const durable = invokeDurable(parameters, handlerContext, durability).pipe(
2121
+ Effect.scoped,
2122
+ Effect.provideService(AgentSpawner, spawner),
2123
+ Effect.provideService(RunEventSink, sink),
2124
+ Effect.provideService(SubagentDurability, durability),
2125
+ Effect.provide(captured),
2126
+ );
2127
+
2128
+ return yield* contained
2129
+ ? durable.pipe(Effect.catch(containSignals))
2130
+ : durable.pipe(Effect.mapError(unwrapSignals));
2131
+ }
2132
+
2133
+ const ephemeral = invoke(parameters, handlerContext).pipe(
2134
+ Effect.scoped,
2135
+ Effect.provideService(AgentSpawner, spawner),
2136
+ Effect.provideService(RunEventSink, sink),
2137
+ Effect.provideService(SubagentDurability, durability),
2138
+ Effect.provide(captured),
2139
+ );
2140
+
2141
+ return yield* contained
2142
+ ? ephemeral.pipe(Effect.catch(containSignals))
2143
+ : ephemeral.pipe(Effect.mapError(unwrapSignals));
2144
+ });
2145
+
2146
+ // `handlerImpl`'s channels are the UNION of both modes because
2147
+ // `contained` is a runtime branch TypeScript cannot relate to the
2148
+ // conditional generic `Mode`; at every concrete `Mode` the branch taken
2149
+ // matches `SubagentHandler`'s channels exactly (proven by the mode type
2150
+ // tests), so this assertion bridges only that limitation and crosses no
2151
+ // schema boundary.
2152
+ const handler = handlerImpl as SubagentHandler<Name, Parameters, Success, Failure, Mode>;
2153
+
2154
+ // TypeScript cannot relate a computed single-key object literal to the
2155
+ // generic mapped key `Name`; `handler` is fully checked against the
2156
+ // Tool's declared handler signature above, so this assertion bridges only
2157
+ // that compiler limitation and crosses no schema boundary.
2158
+ return { [delegation.name]: handler } as Toolkit.HandlersFrom<
2159
+ SubagentTools<Name, Parameters, Success, Failure, Mode>
2160
+ >;
2161
+ });
2162
+
2163
+ return toolkit.toLayer(build);
2164
+ };
2165
+
2166
+ export { reporting, reportingToWorker, WorkerReport } from "./internal/subagent-reporting.ts";
2167
+
2168
+ export {
2169
+ Worker,
2170
+ WorkerObservation,
2171
+ start,
2172
+ followUp,
2173
+ inspect,
2174
+ observe,
2175
+ awaitWorker as await,
2176
+ list,
2177
+ cancel,
2178
+ type BackgroundOptions,
2179
+ type BackgroundTools,
2180
+ } from "./internal/subagent-background.ts";
2181
+
2182
+ /**
2183
+ * Derive selected background Tools directly from a child Agent, using its ID as the delegation
2184
+ * name and its input/output Schemas as the default contract. Pass an explicit Subagent.make
2185
+ * declaration to customize the name, projections, grants, or policy bounds.
2186
+ */
2187
+ export function background<
2188
+ const Name extends string,
2189
+ Input extends Schema.Top,
2190
+ Output extends Schema.Top,
2191
+ Instructions,
2192
+ Tools extends Record<string, Tool.Any>,
2193
+ const Selected extends BackgroundOptions,
2194
+ >(
2195
+ target: Definition<
2196
+ Input,
2197
+ Output,
2198
+ Instructions,
2199
+ Toolkit.Toolkit<Tools>,
2200
+ RunDispositionDeclaration<Output["Type"], Schema.Top> | undefined,
2201
+ unknown,
2202
+ Schema.Top | undefined
2203
+ > & {
2204
+ readonly id: AgentId & Name;
2205
+ },
2206
+ selected: Selected,
2207
+ ): ReturnType<
2208
+ typeof backgroundDeclaration<
2209
+ Name,
2210
+ Input,
2211
+ Output,
2212
+ Input,
2213
+ SubagentResult<Output>,
2214
+ typeof Schema.Never,
2215
+ never,
2216
+ never,
2217
+ Selected
2218
+ >
2219
+ >;
2220
+
2221
+ export function background<
2222
+ const Name extends string,
2223
+ Input extends Schema.Top,
2224
+ Output extends Schema.Top,
2225
+ Parameters extends Schema.Top,
2226
+ Success extends Schema.Top,
2227
+ Failure extends Schema.Top,
2228
+ Prepare,
2229
+ Project,
2230
+ const Selected extends BackgroundOptions,
2231
+ >(
2232
+ declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,
2233
+ selected: Selected,
2234
+ ): ReturnType<
2235
+ typeof backgroundDeclaration<
2236
+ Name,
2237
+ Input,
2238
+ Output,
2239
+ Parameters,
2240
+ Success,
2241
+ Failure,
2242
+ Prepare,
2243
+ Project,
2244
+ Selected
2245
+ >
2246
+ >;
2247
+
2248
+ export function background(
2249
+ targetOrDeclaration:
2250
+ | Definition<
2251
+ Schema.Top,
2252
+ Schema.Top,
2253
+ unknown,
2254
+ Toolkit.Toolkit<Record<string, Tool.Any>>,
2255
+ RunDispositionDeclaration<unknown, Schema.Top> | undefined,
2256
+ unknown,
2257
+ Schema.Top | undefined
2258
+ >
2259
+ | Declaration<
2260
+ string,
2261
+ Schema.Top,
2262
+ Schema.Top,
2263
+ Schema.Top,
2264
+ Schema.Top,
2265
+ Schema.Top,
2266
+ unknown,
2267
+ unknown
2268
+ >,
2269
+ selected: BackgroundOptions,
2270
+ ): unknown {
2271
+ const declaration =
2272
+ "target" in targetOrDeclaration
2273
+ ? targetOrDeclaration
2274
+ : make(targetOrDeclaration.id, { target: targetOrDeclaration });
2275
+
2276
+ return backgroundDeclaration(declaration, selected);
2277
+ }