effect-agent 0.1.0-beta.16 → 0.1.0-beta.160

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