@systemfsoftware/agent 0.0.0-stage → 0.1.0

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