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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (751) hide show
  1. package/dist/Agent-CN0EWRsR.d.mts +226 -0
  2. package/dist/Agent-RklVROrm.mjs +83 -0
  3. package/dist/Agent-RklVROrm.mjs.map +1 -0
  4. package/dist/AgentError-CggcAQ7V.d.mts +101 -0
  5. package/dist/AgentPolicy-CetmQrf3.d.mts +96 -0
  6. package/dist/AgentRuntime-BLyETCPo.mjs +4562 -0
  7. package/dist/AgentRuntime-BLyETCPo.mjs.map +1 -0
  8. package/dist/AgentRuntime-uxR_a4VM.d.mts +346 -0
  9. package/dist/AgentUpdates-DMJ-_xow.d.mts +53 -0
  10. package/dist/ContextCompactor-Dxu5zhOL.d.mts +161 -0
  11. package/dist/ContextWindow-DRQ5Mbm2.d.mts +58 -0
  12. package/dist/DurableAgentRuntime-uggeJpv3.mjs +6368 -0
  13. package/dist/DurableAgentRuntime-uggeJpv3.mjs.map +1 -0
  14. package/dist/DurableFailpoint-Oinuuedm.d.mts +41 -0
  15. package/dist/DurableStep-Cry_iol4.d.mts +103 -0
  16. package/dist/Ephemeral.d.mts +22 -0
  17. package/dist/Ephemeral.mjs +22 -0
  18. package/dist/Ephemeral.mjs.map +1 -0
  19. package/dist/EventSource-OqS_P9ug.d.mts +51 -0
  20. package/dist/Identifiers-CN2s30fF.d.mts +40 -0
  21. package/dist/MemoryNamespace-BbRW5p71.d.mts +36 -0
  22. package/dist/MemoryReference-B8Q3UJoJ.d.mts +79 -0
  23. package/dist/Messaging-CkcIdt4I.d.mts +490 -0
  24. package/dist/MessagingHost-CRk0kXzT.d.mts +246 -0
  25. package/dist/MessagingHost-CWi_PP3g.mjs +137 -0
  26. package/dist/MessagingHost-CWi_PP3g.mjs.map +1 -0
  27. package/dist/OperationAuthorizer-TzcQtpX5.d.mts +61 -0
  28. package/dist/Output-D6SkedVx.d.mts +25 -0
  29. package/dist/PageCapture-Df8Xwskw.d.mts +583 -0
  30. package/dist/PageScreenshot-BpgZKAxl.d.mts +48 -0
  31. package/dist/PreparedInputAdmission-C4HbjHgl.d.mts +38 -0
  32. package/dist/Receipt-BAHyigAF.d.mts +33 -0
  33. package/dist/Records-BAGkekt8.d.mts +3570 -0
  34. package/dist/RunEvent-DIrzkjLr.d.mts +460 -0
  35. package/dist/RunEventSink-D5aVhISG.d.mts +108 -0
  36. package/dist/RunJournal-Cgg1kNvc.mjs +825 -0
  37. package/dist/RunJournal-Cgg1kNvc.mjs.map +1 -0
  38. package/dist/RunOptions-g1aigcKI.d.mts +915 -0
  39. package/dist/RunPolicyUsage-ClZxyR46.d.mts +21 -0
  40. package/dist/Sandbox-CEsDWBLq.d.mts +173 -0
  41. package/dist/Schedule-H3SEYX9g.d.mts +842 -0
  42. package/dist/Scheduling-C9aIP8zT.mjs +691 -0
  43. package/dist/Scheduling-C9aIP8zT.mjs.map +1 -0
  44. package/dist/Subagent-Cy_hU1tv.mjs +1469 -0
  45. package/dist/Subagent-Cy_hU1tv.mjs.map +1 -0
  46. package/dist/Subagent-DyfzHNdv.d.mts +826 -0
  47. package/dist/SubagentContract-DdT7Cqe6.d.mts +116 -0
  48. package/dist/SubagentHost-CJUBQlcc.d.mts +140 -0
  49. package/dist/Subscription-BEP8oQO5.d.mts +921 -0
  50. package/dist/SubscriptionInput-vAAOBrK7.d.mts +41 -0
  51. package/dist/Thread-DOBQ0QUY.d.mts +96 -0
  52. package/dist/ThreadHistory-tS1KwxHR.d.mts +60 -0
  53. package/dist/ToolBroker-DWs4tZra.d.mts +133 -0
  54. package/dist/ToolExposure-9uF_Yo0T.mjs +10 -0
  55. package/dist/ToolExposure-9uF_Yo0T.mjs.map +1 -0
  56. package/dist/ToolExposure-C93U1sPu.mjs +30 -0
  57. package/dist/ToolExposure-C93U1sPu.mjs.map +1 -0
  58. package/dist/ToolExposure-UCN12eCd.d.mts +39 -0
  59. package/dist/ToolExposure-r2eOWk4F.d.mts +46 -0
  60. package/dist/ToolExposure.d.mts +6 -5
  61. package/dist/ToolExposure.mjs +17 -9
  62. package/dist/ToolExposure.mjs.map +1 -1
  63. package/dist/ToolReconciler-DQVaJfpE.d.mts +76 -0
  64. package/dist/ToolResult-DmmgoChv.d.mts +61 -0
  65. package/dist/Usage-Dx0aknfk.d.mts +121 -0
  66. package/dist/WakeScheduler-EjUF-GhC.d.mts +56 -0
  67. package/dist/Worker-CaPYykpe.d.mts +228 -0
  68. package/dist/agent-registration-CWDMOAZA.mjs +172 -0
  69. package/dist/agent-registration-CWDMOAZA.mjs.map +1 -0
  70. package/dist/capabilities/Approval.d.mts +114 -0
  71. package/dist/capabilities/Approval.mjs +226 -0
  72. package/dist/capabilities/Approval.mjs.map +1 -0
  73. package/dist/capabilities/Budget.d.mts +112 -0
  74. package/dist/capabilities/Budget.mjs +346 -0
  75. package/dist/capabilities/Budget.mjs.map +1 -0
  76. package/dist/capabilities/CodeMode.d.mts +157 -0
  77. package/dist/capabilities/CodeMode.mjs +522 -0
  78. package/dist/capabilities/CodeMode.mjs.map +1 -0
  79. package/dist/capabilities/Commands.d.mts +55 -0
  80. package/dist/capabilities/Commands.mjs +57 -0
  81. package/dist/capabilities/Commands.mjs.map +1 -0
  82. package/dist/capabilities/ContextTools.d.mts +321 -0
  83. package/dist/capabilities/ContextTools.mjs +126 -0
  84. package/dist/capabilities/ContextTools.mjs.map +1 -0
  85. package/dist/capabilities/Mcp.d.mts +108 -0
  86. package/dist/capabilities/Mcp.mjs +260 -0
  87. package/dist/capabilities/Mcp.mjs.map +1 -0
  88. package/dist/capabilities/McpClient.d.mts +115 -0
  89. package/dist/capabilities/McpClient.mjs +506 -0
  90. package/dist/capabilities/McpClient.mjs.map +1 -0
  91. package/dist/capabilities/MemoryNotes.d.mts +424 -0
  92. package/dist/capabilities/MemoryNotes.mjs +128 -0
  93. package/dist/capabilities/MemoryNotes.mjs.map +1 -0
  94. package/dist/capabilities/Messaging.d.mts +3 -0
  95. package/dist/capabilities/Messaging.mjs +151 -0
  96. package/dist/capabilities/Messaging.mjs.map +1 -0
  97. package/dist/capabilities/ModelContext.d.mts +89 -0
  98. package/dist/capabilities/ModelContext.mjs +168 -0
  99. package/dist/capabilities/ModelContext.mjs.map +1 -0
  100. package/dist/capabilities/Redaction.d.mts +37 -0
  101. package/dist/capabilities/Redaction.mjs +104 -0
  102. package/dist/capabilities/Redaction.mjs.map +1 -0
  103. package/dist/capabilities/Remembering.d.mts +434 -0
  104. package/dist/capabilities/Remembering.mjs +290 -0
  105. package/dist/capabilities/Remembering.mjs.map +1 -0
  106. package/dist/capabilities/RunHooks.d.mts +82 -0
  107. package/dist/capabilities/RunHooks.mjs +144 -0
  108. package/dist/capabilities/RunHooks.mjs.map +1 -0
  109. package/dist/capabilities/SemanticMemory.d.mts +431 -0
  110. package/dist/capabilities/SemanticMemory.mjs +315 -0
  111. package/dist/capabilities/SemanticMemory.mjs.map +1 -0
  112. package/dist/capabilities/Subagent.d.mts +4 -0
  113. package/dist/capabilities/Subagent.mjs +5 -0
  114. package/dist/capabilities/SubagentReservations.d.mts +186 -0
  115. package/dist/capabilities/SubagentReservations.mjs +479 -0
  116. package/dist/capabilities/SubagentReservations.mjs.map +1 -0
  117. package/dist/capabilities/ToolDiscovery.d.mts +109 -0
  118. package/dist/capabilities/ToolDiscovery.mjs +211 -0
  119. package/dist/capabilities/ToolDiscovery.mjs.map +1 -0
  120. package/dist/capabilities/WebCapture.d.mts +163 -0
  121. package/dist/capabilities/WebCapture.mjs +335 -0
  122. package/dist/capabilities/WebCapture.mjs.map +1 -0
  123. package/dist/capabilities/WebSearch.d.mts +71 -0
  124. package/dist/capabilities/WebSearch.mjs +112 -0
  125. package/dist/capabilities/WebSearch.mjs.map +1 -0
  126. package/dist/compaction-C2OTceKw.mjs +505 -0
  127. package/dist/compaction-C2OTceKw.mjs.map +1 -0
  128. package/dist/core/Agent.d.mts +2 -0
  129. package/dist/core/Agent.mjs +2 -0
  130. package/dist/core/AgentError.d.mts +2 -0
  131. package/dist/core/AgentError.mjs +117 -0
  132. package/dist/core/AgentError.mjs.map +1 -0
  133. package/dist/core/AgentPolicy.d.mts +2 -0
  134. package/dist/core/AgentPolicy.mjs +94 -0
  135. package/dist/core/AgentPolicy.mjs.map +1 -0
  136. package/dist/core/AgentUpdates.d.mts +2 -0
  137. package/dist/core/AgentUpdates.mjs +63 -0
  138. package/dist/core/AgentUpdates.mjs.map +1 -0
  139. package/dist/core/IdGenerator.d.mts +26 -0
  140. package/dist/core/IdGenerator.mjs +27 -0
  141. package/dist/core/IdGenerator.mjs.map +1 -0
  142. package/dist/core/Identifiers.d.mts +2 -0
  143. package/dist/core/Identifiers.mjs +43 -0
  144. package/dist/core/Identifiers.mjs.map +1 -0
  145. package/dist/core/Memory.d.mts +57 -0
  146. package/dist/core/Memory.mjs +203 -0
  147. package/dist/core/Memory.mjs.map +1 -0
  148. package/dist/core/MemoryNamespace.d.mts +2 -0
  149. package/dist/core/MemoryNamespace.mjs +116 -0
  150. package/dist/core/MemoryNamespace.mjs.map +1 -0
  151. package/dist/core/MemoryReference.d.mts +2 -0
  152. package/dist/core/MemoryReference.mjs +109 -0
  153. package/dist/core/MemoryReference.mjs.map +1 -0
  154. package/dist/core/MemoryRevalidation.d.mts +65 -0
  155. package/dist/core/MemoryRevalidation.mjs +126 -0
  156. package/dist/core/MemoryRevalidation.mjs.map +1 -0
  157. package/dist/core/MemoryStore.d.mts +186 -0
  158. package/dist/core/MemoryStore.mjs +243 -0
  159. package/dist/core/MemoryStore.mjs.map +1 -0
  160. package/dist/core/Receipt.d.mts +2 -0
  161. package/dist/core/Receipt.mjs +36 -0
  162. package/dist/core/Receipt.mjs.map +1 -0
  163. package/dist/core/RememberingStore.d.mts +1562 -0
  164. package/dist/core/RememberingStore.mjs +190 -0
  165. package/dist/core/RememberingStore.mjs.map +1 -0
  166. package/dist/core/RunEvent.d.mts +2 -0
  167. package/dist/core/RunEvent.mjs +337 -0
  168. package/dist/core/RunEvent.mjs.map +1 -0
  169. package/dist/core/RunPolicyUsage.d.mts +2 -0
  170. package/dist/core/RunPolicyUsage.mjs +21 -0
  171. package/dist/core/RunPolicyUsage.mjs.map +1 -0
  172. package/dist/core/SemanticMemoryIndex.d.mts +826 -0
  173. package/dist/core/SemanticMemoryIndex.mjs +185 -0
  174. package/dist/core/SemanticMemoryIndex.mjs.map +1 -0
  175. package/dist/core/SemanticMemoryRevalidation.d.mts +45 -0
  176. package/dist/core/SemanticMemoryRevalidation.mjs +191 -0
  177. package/dist/core/SemanticMemoryRevalidation.mjs.map +1 -0
  178. package/dist/core/SubagentContract.d.mts +2 -0
  179. package/dist/core/SubagentContract.mjs +148 -0
  180. package/dist/core/SubagentContract.mjs.map +1 -0
  181. package/dist/core/Thread.d.mts +2 -0
  182. package/dist/core/Thread.mjs +250 -0
  183. package/dist/core/Thread.mjs.map +1 -0
  184. package/dist/core/ToolResult.d.mts +2 -0
  185. package/dist/core/ToolResult.mjs +140 -0
  186. package/dist/core/ToolResult.mjs.map +1 -0
  187. package/dist/core/Usage.d.mts +2 -0
  188. package/dist/core/Usage.mjs +319 -0
  189. package/dist/core/Usage.mjs.map +1 -0
  190. package/dist/core/Worker.d.mts +3 -0
  191. package/dist/core/Worker.mjs +147 -0
  192. package/dist/core/Worker.mjs.map +1 -0
  193. package/dist/durable/ActivityStore.d.mts +116 -0
  194. package/dist/durable/ActivityStore.mjs +131 -0
  195. package/dist/durable/ActivityStore.mjs.map +1 -0
  196. package/dist/durable/Admin.d.mts +2 -0
  197. package/dist/durable/Admin.mjs +328 -0
  198. package/dist/durable/Admin.mjs.map +1 -0
  199. package/dist/durable/AgentRegistration.d.mts +2 -0
  200. package/dist/durable/AgentRegistration.mjs +14 -0
  201. package/dist/durable/AgentRegistration.mjs.map +1 -0
  202. package/dist/durable/Certification.d.mts +111 -0
  203. package/dist/durable/Certification.mjs +159 -0
  204. package/dist/durable/Certification.mjs.map +1 -0
  205. package/dist/durable/CommittedActivity.d.mts +62 -0
  206. package/dist/durable/CommittedActivity.mjs +159 -0
  207. package/dist/durable/CommittedActivity.mjs.map +1 -0
  208. package/dist/durable/Digest.d.mts +2 -0
  209. package/dist/durable/Digest.mjs +50 -0
  210. package/dist/durable/Digest.mjs.map +1 -0
  211. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  212. package/dist/durable/DurableAgentRuntime.mjs +3 -0
  213. package/dist/durable/DurableFailpoint.d.mts +2 -0
  214. package/dist/durable/DurableFailpoint.mjs +94 -0
  215. package/dist/durable/DurableFailpoint.mjs.map +1 -0
  216. package/dist/durable/DurableFailpointTestControl.d.mts +15 -0
  217. package/dist/durable/DurableFailpointTestControl.mjs +19 -0
  218. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  219. package/dist/durable/EventSource.d.mts +2 -0
  220. package/dist/durable/EventSource.mjs +65 -0
  221. package/dist/durable/EventSource.mjs.map +1 -0
  222. package/dist/durable/GitHubWorkflowSource.d.mts +144 -0
  223. package/dist/durable/GitHubWorkflowSource.mjs +209 -0
  224. package/dist/durable/GitHubWorkflowSource.mjs.map +1 -0
  225. package/dist/durable/MessageDelivery.d.mts +492 -0
  226. package/dist/durable/MessageDelivery.mjs +495 -0
  227. package/dist/durable/MessageDelivery.mjs.map +1 -0
  228. package/dist/durable/MessageDeliveryStoreConformance.d.mts +358 -0
  229. package/dist/durable/MessageDeliveryStoreConformance.mjs +243 -0
  230. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  231. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  232. package/dist/durable/OperationAuthorizer.mjs +70 -0
  233. package/dist/durable/OperationAuthorizer.mjs.map +1 -0
  234. package/dist/durable/PersistentHistory.d.mts +16 -0
  235. package/dist/durable/PersistentHistory.mjs +125 -0
  236. package/dist/durable/PersistentHistory.mjs.map +1 -0
  237. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  238. package/dist/durable/PreparedInputAdmission.mjs +34 -0
  239. package/dist/durable/PreparedInputAdmission.mjs.map +1 -0
  240. package/dist/durable/Records.d.mts +2 -0
  241. package/dist/durable/Records.mjs +795 -0
  242. package/dist/durable/Records.mjs.map +1 -0
  243. package/dist/durable/Recovery.d.mts +2 -0
  244. package/dist/durable/Recovery.mjs +739 -0
  245. package/dist/durable/Recovery.mjs.map +1 -0
  246. package/dist/durable/RunJournal.d.mts +2 -0
  247. package/dist/durable/RunJournal.mjs +2 -0
  248. package/dist/durable/Schedule.d.mts +2 -0
  249. package/dist/durable/Schedule.mjs +382 -0
  250. package/dist/durable/Schedule.mjs.map +1 -0
  251. package/dist/durable/ScheduleStoreConformance.d.mts +18 -0
  252. package/dist/durable/ScheduleStoreConformance.mjs +420 -0
  253. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  254. package/dist/durable/ScheduleTransition.d.mts +24 -0
  255. package/dist/durable/ScheduleTransition.mjs +180 -0
  256. package/dist/durable/ScheduleTransition.mjs.map +1 -0
  257. package/dist/durable/Scheduling.d.mts +54 -0
  258. package/dist/durable/Scheduling.mjs +2 -0
  259. package/dist/durable/SqlMemoryStore.d.mts +30 -0
  260. package/dist/durable/SqlMemoryStore.mjs +435 -0
  261. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  262. package/dist/durable/SqlMessageDeliveryStore.d.mts +40 -0
  263. package/dist/durable/SqlMessageDeliveryStore.mjs +167 -0
  264. package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -0
  265. package/dist/durable/SqlStorageV2Upgrade.d.mts +22 -0
  266. package/dist/durable/SqlStorageV2Upgrade.mjs +459 -0
  267. package/dist/durable/SqlStorageV2Upgrade.mjs.map +1 -0
  268. package/dist/durable/SqlSubscriptionStore.d.mts +63 -0
  269. package/dist/durable/SqlSubscriptionStore.mjs +751 -0
  270. package/dist/durable/SqlSubscriptionStore.mjs.map +1 -0
  271. package/dist/durable/SubmissionLedger.d.mts +3 -0
  272. package/dist/durable/SubmissionLedger.mjs +914 -0
  273. package/dist/durable/SubmissionLedger.mjs.map +1 -0
  274. package/dist/durable/SubmissionLedgerConformance.d.mts +30 -0
  275. package/dist/durable/SubmissionLedgerConformance.mjs +1986 -0
  276. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  277. package/dist/durable/SubmissionStatus.d.mts +2 -0
  278. package/dist/durable/SubmissionStatus.mjs +18 -0
  279. package/dist/durable/SubmissionStatus.mjs.map +1 -0
  280. package/dist/durable/Subscription.d.mts +2 -0
  281. package/dist/durable/Subscription.mjs +360 -0
  282. package/dist/durable/Subscription.mjs.map +1 -0
  283. package/dist/durable/SubscriptionInput.d.mts +2 -0
  284. package/dist/durable/SubscriptionInput.mjs +52 -0
  285. package/dist/durable/SubscriptionInput.mjs.map +1 -0
  286. package/dist/durable/SubscriptionStoreConformance.d.mts +17 -0
  287. package/dist/durable/SubscriptionStoreConformance.mjs +625 -0
  288. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  289. package/dist/durable/SubscriptionTools.d.mts +273 -0
  290. package/dist/durable/SubscriptionTools.mjs +190 -0
  291. package/dist/durable/SubscriptionTools.mjs.map +1 -0
  292. package/dist/durable/SubscriptionTransition.d.mts +21 -0
  293. package/dist/durable/SubscriptionTransition.mjs +148 -0
  294. package/dist/durable/SubscriptionTransition.mjs.map +1 -0
  295. package/dist/durable/Subscriptions.d.mts +73 -0
  296. package/dist/durable/Subscriptions.mjs +627 -0
  297. package/dist/durable/Subscriptions.mjs.map +1 -0
  298. package/dist/durable/ThreadContextHistory.d.mts +32 -0
  299. package/dist/durable/ThreadContextHistory.mjs +152 -0
  300. package/dist/durable/ThreadContextHistory.mjs.map +1 -0
  301. package/dist/durable/ThreadContextHistoryProjection.d.mts +60 -0
  302. package/dist/durable/ThreadContextHistoryProjection.mjs +149 -0
  303. package/dist/durable/ThreadContextHistoryProjection.mjs.map +1 -0
  304. package/dist/durable/ThreadInvariants.d.mts +74 -0
  305. package/dist/durable/ThreadInvariants.mjs +200 -0
  306. package/dist/durable/ThreadInvariants.mjs.map +1 -0
  307. package/dist/durable/ThreadProjection.d.mts +78 -0
  308. package/dist/durable/ThreadProjection.mjs +158 -0
  309. package/dist/durable/ThreadProjection.mjs.map +1 -0
  310. package/dist/durable/ThreadProjectionMaintenance.d.mts +49 -0
  311. package/dist/durable/ThreadProjectionMaintenance.mjs +33 -0
  312. package/dist/durable/ThreadProjectionMaintenance.mjs.map +1 -0
  313. package/dist/durable/ThreadStore.d.mts +2 -0
  314. package/dist/durable/ThreadStore.mjs +147 -0
  315. package/dist/durable/ThreadStore.mjs.map +1 -0
  316. package/dist/durable/ThreadStoreConformance.d.mts +29 -0
  317. package/dist/durable/ThreadStoreConformance.mjs +248 -0
  318. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  319. package/dist/durable/ToolReconciler.d.mts +2 -0
  320. package/dist/durable/ToolReconciler.mjs +81 -0
  321. package/dist/durable/ToolReconciler.mjs.map +1 -0
  322. package/dist/durable/WakeScheduler.d.mts +2 -0
  323. package/dist/durable/WakeScheduler.mjs +85 -0
  324. package/dist/durable/WakeScheduler.mjs.map +1 -0
  325. package/dist/durable/WorkerHost.d.mts +129 -0
  326. package/dist/durable/WorkerHost.mjs +77 -0
  327. package/dist/durable/WorkerHost.mjs.map +1 -0
  328. package/dist/engine/AgentRuntime.d.mts +2 -0
  329. package/dist/engine/AgentRuntime.mjs +2 -0
  330. package/dist/engine/Compaction.d.mts +7 -0
  331. package/dist/engine/Compaction.mjs +16 -0
  332. package/dist/engine/Compaction.mjs.map +1 -0
  333. package/dist/engine/ContextCompactor.d.mts +2 -0
  334. package/dist/engine/ContextCompactor.mjs +119 -0
  335. package/dist/engine/ContextCompactor.mjs.map +1 -0
  336. package/dist/engine/ContextHistory.d.mts +65 -0
  337. package/dist/engine/ContextHistory.mjs +76 -0
  338. package/dist/engine/ContextHistory.mjs.map +1 -0
  339. package/dist/engine/ContextWindow.d.mts +2 -0
  340. package/dist/engine/ContextWindow.mjs +59 -0
  341. package/dist/engine/ContextWindow.mjs.map +1 -0
  342. package/dist/engine/DurableStep.d.mts +2 -0
  343. package/dist/engine/DurableStep.mjs +62 -0
  344. package/dist/engine/DurableStep.mjs.map +1 -0
  345. package/dist/engine/MessagingHost.d.mts +2 -0
  346. package/dist/engine/MessagingHost.mjs +2 -0
  347. package/dist/engine/Output.d.mts +2 -0
  348. package/dist/engine/Output.mjs +8 -0
  349. package/dist/engine/Output.mjs.map +1 -0
  350. package/dist/engine/RunEventSink.d.mts +2 -0
  351. package/dist/engine/RunEventSink.mjs +22 -0
  352. package/dist/engine/RunEventSink.mjs.map +1 -0
  353. package/dist/engine/RunOptions.d.mts +2 -0
  354. package/dist/engine/RunOptions.mjs +122 -0
  355. package/dist/engine/RunOptions.mjs.map +1 -0
  356. package/dist/engine/SubagentHost.d.mts +2 -0
  357. package/dist/engine/SubagentHost.mjs +72 -0
  358. package/dist/engine/SubagentHost.mjs.map +1 -0
  359. package/dist/engine/ThreadHistory.d.mts +2 -0
  360. package/dist/engine/ThreadHistory.mjs +67 -0
  361. package/dist/engine/ThreadHistory.mjs.map +1 -0
  362. package/dist/engine/ToolBroker.d.mts +2 -0
  363. package/dist/engine/ToolBroker.mjs +42 -0
  364. package/dist/engine/ToolBroker.mjs.map +1 -0
  365. package/dist/foreign-diagnostic-DBQ1XHKh.mjs +37 -0
  366. package/dist/foreign-diagnostic-DBQ1XHKh.mjs.map +1 -0
  367. package/dist/index.d.mts +88 -54
  368. package/dist/index.mjs +97 -54
  369. package/dist/output-contract-BC7tjlGw.mjs +84 -0
  370. package/dist/output-contract-BC7tjlGw.mjs.map +1 -0
  371. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  372. package/dist/sandbox/CodeExecutor.d.mts +194 -0
  373. package/dist/sandbox/CodeExecutor.mjs +278 -0
  374. package/dist/sandbox/CodeExecutor.mjs.map +1 -0
  375. package/dist/sandbox/InteractiveBrowser.d.mts +142 -0
  376. package/dist/sandbox/InteractiveBrowser.mjs +165 -0
  377. package/dist/sandbox/InteractiveBrowser.mjs.map +1 -0
  378. package/dist/sandbox/PageCapture.d.mts +2 -0
  379. package/dist/sandbox/PageCapture.mjs +450 -0
  380. package/dist/sandbox/PageCapture.mjs.map +1 -0
  381. package/dist/sandbox/PageCrawl.d.mts +88 -0
  382. package/dist/sandbox/PageCrawl.mjs +124 -0
  383. package/dist/sandbox/PageCrawl.mjs.map +1 -0
  384. package/dist/sandbox/PageScreenshot.d.mts +2 -0
  385. package/dist/sandbox/PageScreenshot.mjs +53 -0
  386. package/dist/sandbox/PageScreenshot.mjs.map +1 -0
  387. package/dist/sandbox/ProtectedBrowser.d.mts +252 -0
  388. package/dist/sandbox/ProtectedBrowser.mjs +270 -0
  389. package/dist/sandbox/ProtectedBrowser.mjs.map +1 -0
  390. package/dist/sandbox/Sandbox.d.mts +2 -0
  391. package/dist/sandbox/Sandbox.mjs +208 -0
  392. package/dist/sandbox/Sandbox.mjs.map +1 -0
  393. package/dist/utf8-BYfhEkcj.mjs +11 -0
  394. package/dist/utf8-BYfhEkcj.mjs.map +1 -0
  395. package/dist/utf8-DchGZRBd.mjs +23 -0
  396. package/dist/utf8-DchGZRBd.mjs.map +1 -0
  397. package/package.json +1 -1
  398. package/src/Ephemeral.ts +17 -0
  399. package/src/ToolExposure.ts +2 -2
  400. package/src/capabilities/Approval.ts +352 -0
  401. package/src/capabilities/Budget.ts +536 -0
  402. package/src/capabilities/CodeMode.ts +1090 -0
  403. package/src/capabilities/Commands.ts +86 -0
  404. package/src/capabilities/ContextTools.ts +184 -0
  405. package/src/capabilities/Mcp.ts +427 -0
  406. package/src/capabilities/McpClient.ts +967 -0
  407. package/src/capabilities/MemoryNotes.ts +174 -0
  408. package/src/capabilities/Messaging.ts +261 -0
  409. package/src/capabilities/ModelContext.ts +354 -0
  410. package/src/capabilities/Redaction.ts +157 -0
  411. package/src/capabilities/Remembering.ts +550 -0
  412. package/src/capabilities/RunHooks.ts +280 -0
  413. package/src/capabilities/SemanticMemory.ts +447 -0
  414. package/src/capabilities/Subagent.ts +2277 -0
  415. package/src/capabilities/SubagentReservations.ts +850 -0
  416. package/src/capabilities/ToolDiscovery.ts +339 -0
  417. package/src/capabilities/WebCapture.ts +722 -0
  418. package/src/capabilities/WebSearch.ts +184 -0
  419. package/src/capabilities/internal/subagent-background.ts +1106 -0
  420. package/src/capabilities/internal/subagent-contract.ts +142 -0
  421. package/src/capabilities/internal/subagent-policy.ts +235 -0
  422. package/src/capabilities/internal/subagent-reporting.ts +261 -0
  423. package/src/capabilities/internal/utf8.ts +10 -0
  424. package/src/core/Agent.ts +575 -0
  425. package/src/core/AgentError.ts +152 -0
  426. package/src/core/AgentPolicy.ts +153 -0
  427. package/src/core/AgentUpdates.ts +100 -0
  428. package/src/core/IdGenerator.ts +39 -0
  429. package/src/core/Identifiers.ts +48 -0
  430. package/src/core/Memory.ts +290 -0
  431. package/src/core/MemoryNamespace.ts +196 -0
  432. package/src/core/MemoryReference.ts +121 -0
  433. package/src/core/MemoryRevalidation.ts +185 -0
  434. package/src/core/MemoryStore.ts +368 -0
  435. package/src/core/Messaging.ts +90 -0
  436. package/src/core/Receipt.ts +42 -0
  437. package/src/core/RememberingStore.ts +300 -0
  438. package/src/core/RunEvent.ts +366 -0
  439. package/src/core/RunPolicyUsage.ts +17 -0
  440. package/src/core/SemanticMemoryIndex.ts +250 -0
  441. package/src/core/SemanticMemoryRevalidation.ts +254 -0
  442. package/src/core/SubagentContract.ts +196 -0
  443. package/src/core/Thread.ts +371 -0
  444. package/src/core/ToolExposure.ts +74 -0
  445. package/src/core/ToolResult.ts +170 -0
  446. package/src/core/Usage.ts +529 -0
  447. package/src/core/Worker.ts +173 -0
  448. package/src/core/internal/agent-updates.ts +32 -0
  449. package/src/core/internal/utf8.ts +23 -0
  450. package/src/durable/ActivityStore.ts +160 -0
  451. package/src/durable/Admin.ts +496 -0
  452. package/src/durable/AgentRegistration.ts +13 -0
  453. package/src/durable/Certification.ts +210 -0
  454. package/src/durable/CommittedActivity.ts +296 -0
  455. package/src/durable/Digest.ts +93 -0
  456. package/src/durable/DurableAgentRuntime.ts +10340 -0
  457. package/src/durable/DurableFailpoint.ts +103 -0
  458. package/src/durable/DurableFailpointTestControl.ts +39 -0
  459. package/src/durable/EventSource.ts +172 -0
  460. package/src/durable/GitHubWorkflowSource.ts +453 -0
  461. package/src/durable/MessageDelivery.ts +708 -0
  462. package/src/durable/MessageDeliveryStoreConformance.ts +363 -0
  463. package/src/durable/OperationAuthorizer.ts +85 -0
  464. package/src/durable/PersistentHistory.ts +260 -0
  465. package/src/durable/PreparedInputAdmission.ts +44 -0
  466. package/src/durable/Records.ts +1010 -0
  467. package/src/durable/Recovery.ts +1018 -0
  468. package/src/durable/RunJournal.ts +1479 -0
  469. package/src/durable/Schedule.ts +504 -0
  470. package/src/durable/ScheduleStoreConformance.ts +638 -0
  471. package/src/durable/ScheduleTransition.ts +265 -0
  472. package/src/durable/Scheduling.ts +1077 -0
  473. package/src/durable/SqlMemoryStore.ts +774 -0
  474. package/src/durable/SqlMessageDeliveryStore.ts +302 -0
  475. package/src/durable/SqlStorageV2Upgrade.ts +500 -0
  476. package/src/durable/SqlSubscriptionStore.ts +1440 -0
  477. package/src/durable/SubmissionLedger.ts +1201 -0
  478. package/src/durable/SubmissionLedgerConformance.ts +4579 -0
  479. package/src/durable/SubmissionStatus.ts +14 -0
  480. package/src/durable/Subscription.ts +544 -0
  481. package/src/durable/SubscriptionInput.ts +144 -0
  482. package/src/durable/SubscriptionStoreConformance.ts +945 -0
  483. package/src/durable/SubscriptionTools.ts +327 -0
  484. package/src/durable/SubscriptionTransition.ts +302 -0
  485. package/src/durable/Subscriptions.ts +1210 -0
  486. package/src/durable/ThreadContextHistory.ts +227 -0
  487. package/src/durable/ThreadContextHistoryProjection.ts +216 -0
  488. package/src/durable/ThreadInvariants.ts +442 -0
  489. package/src/durable/ThreadProjection.ts +269 -0
  490. package/src/durable/ThreadProjectionMaintenance.ts +67 -0
  491. package/src/durable/ThreadStore.ts +242 -0
  492. package/src/durable/ThreadStoreConformance.ts +710 -0
  493. package/src/durable/ToolReconciler.ts +105 -0
  494. package/src/durable/WakeScheduler.ts +134 -0
  495. package/src/durable/WorkerHost.ts +171 -0
  496. package/src/durable/internal/agent-registration.ts +525 -0
  497. package/src/durable/internal/agent-updates.ts +302 -0
  498. package/src/durable/internal/foreign-diagnostic.ts +47 -0
  499. package/src/durable/internal/journal-checkpoint.ts +104 -0
  500. package/src/durable/internal/journal-metadata.ts +107 -0
  501. package/src/durable/internal/messaging-host.ts +608 -0
  502. package/src/durable/internal/schedule-time.ts +303 -0
  503. package/src/durable/internal/storage-v2-layout.ts +163 -0
  504. package/src/durable/internal/storage-v2.ts +73 -0
  505. package/src/durable/internal/worker-host.ts +2467 -0
  506. package/src/durable/internal/worker-runtime.ts +9 -0
  507. package/src/engine/AgentRuntime.ts +37 -0
  508. package/src/engine/Compaction.ts +11 -0
  509. package/src/engine/ContextCompactor.ts +277 -0
  510. package/src/engine/ContextHistory.ts +73 -0
  511. package/src/engine/ContextWindow.ts +72 -0
  512. package/src/engine/DurableStep.ts +132 -0
  513. package/src/engine/MessagingHost.ts +110 -0
  514. package/src/engine/Output.ts +2 -0
  515. package/src/engine/RunEventSink.ts +132 -0
  516. package/src/engine/RunOptions.ts +1077 -0
  517. package/src/engine/SubagentHost.ts +181 -0
  518. package/src/engine/ThreadHistory.ts +120 -0
  519. package/src/engine/ToolBroker.ts +157 -0
  520. package/src/engine/ToolExposure.ts +48 -0
  521. package/src/engine/internal/agent-runtime.ts +10117 -0
  522. package/src/engine/internal/bounded-value.ts +315 -0
  523. package/src/engine/internal/compaction.ts +678 -0
  524. package/src/engine/internal/error-diagnostic.ts +39 -0
  525. package/src/engine/internal/output-contract.ts +173 -0
  526. package/src/engine/internal/primitive-delta.ts +80 -0
  527. package/src/engine/internal/provider-result-staging.ts +211 -0
  528. package/src/engine/internal/tool-derivative.ts +106 -0
  529. package/src/engine/internal/tool-exposure.ts +224 -0
  530. package/src/engine/internal/tool-telemetry.ts +484 -0
  531. package/src/index.ts +96 -53
  532. package/src/sandbox/CodeExecutor.ts +352 -0
  533. package/src/sandbox/InteractiveBrowser.ts +257 -0
  534. package/src/sandbox/PageCapture.ts +692 -0
  535. package/src/sandbox/PageCrawl.ts +148 -0
  536. package/src/sandbox/PageScreenshot.ts +81 -0
  537. package/src/sandbox/ProtectedBrowser.ts +413 -0
  538. package/src/sandbox/Sandbox.ts +241 -0
  539. package/dist/Agent.d.mts +0 -5
  540. package/dist/Agent.mjs +0 -10
  541. package/dist/Agent.mjs.map +0 -1
  542. package/dist/AgentError.d.mts +0 -5
  543. package/dist/AgentError.mjs +0 -10
  544. package/dist/AgentError.mjs.map +0 -1
  545. package/dist/AgentPolicy.d.mts +0 -5
  546. package/dist/AgentPolicy.mjs +0 -10
  547. package/dist/AgentPolicy.mjs.map +0 -1
  548. package/dist/AgentRuntime.d.mts +0 -5
  549. package/dist/AgentRuntime.mjs +0 -10
  550. package/dist/AgentRuntime.mjs.map +0 -1
  551. package/dist/AgentUpdates.d.mts +0 -5
  552. package/dist/AgentUpdates.mjs +0 -10
  553. package/dist/AgentUpdates.mjs.map +0 -1
  554. package/dist/Approval.d.mts +0 -5
  555. package/dist/Approval.mjs +0 -10
  556. package/dist/Approval.mjs.map +0 -1
  557. package/dist/Budget.d.mts +0 -5
  558. package/dist/Budget.mjs +0 -10
  559. package/dist/Budget.mjs.map +0 -1
  560. package/dist/CodeMode.d.mts +0 -5
  561. package/dist/CodeMode.mjs +0 -10
  562. package/dist/CodeMode.mjs.map +0 -1
  563. package/dist/Commands.d.mts +0 -5
  564. package/dist/Commands.mjs +0 -10
  565. package/dist/Commands.mjs.map +0 -1
  566. package/dist/Compaction.d.mts +0 -5
  567. package/dist/Compaction.mjs +0 -10
  568. package/dist/Compaction.mjs.map +0 -1
  569. package/dist/ContextCompactor.d.mts +0 -5
  570. package/dist/ContextCompactor.mjs +0 -10
  571. package/dist/ContextCompactor.mjs.map +0 -1
  572. package/dist/ContextHistory.d.mts +0 -5
  573. package/dist/ContextHistory.mjs +0 -10
  574. package/dist/ContextHistory.mjs.map +0 -1
  575. package/dist/ContextTools.d.mts +0 -5
  576. package/dist/ContextTools.mjs +0 -10
  577. package/dist/ContextTools.mjs.map +0 -1
  578. package/dist/ContextWindow.d.mts +0 -5
  579. package/dist/ContextWindow.mjs +0 -10
  580. package/dist/ContextWindow.mjs.map +0 -1
  581. package/dist/DurableStep.d.mts +0 -5
  582. package/dist/DurableStep.mjs +0 -10
  583. package/dist/DurableStep.mjs.map +0 -1
  584. package/dist/EphemeralThreads.d.mts +0 -5
  585. package/dist/EphemeralThreads.mjs +0 -10
  586. package/dist/EphemeralThreads.mjs.map +0 -1
  587. package/dist/IdGenerator.d.mts +0 -5
  588. package/dist/IdGenerator.mjs +0 -10
  589. package/dist/IdGenerator.mjs.map +0 -1
  590. package/dist/Identifiers.d.mts +0 -5
  591. package/dist/Identifiers.mjs +0 -10
  592. package/dist/Identifiers.mjs.map +0 -1
  593. package/dist/Mcp.d.mts +0 -5
  594. package/dist/Mcp.mjs +0 -10
  595. package/dist/Mcp.mjs.map +0 -1
  596. package/dist/McpClient.d.mts +0 -5
  597. package/dist/McpClient.mjs +0 -10
  598. package/dist/McpClient.mjs.map +0 -1
  599. package/dist/Memory.d.mts +0 -5
  600. package/dist/Memory.mjs +0 -10
  601. package/dist/Memory.mjs.map +0 -1
  602. package/dist/MemoryNamespace.d.mts +0 -5
  603. package/dist/MemoryNamespace.mjs +0 -10
  604. package/dist/MemoryNamespace.mjs.map +0 -1
  605. package/dist/MemoryNotes.d.mts +0 -5
  606. package/dist/MemoryNotes.mjs +0 -10
  607. package/dist/MemoryNotes.mjs.map +0 -1
  608. package/dist/MemoryReference.d.mts +0 -5
  609. package/dist/MemoryReference.mjs +0 -10
  610. package/dist/MemoryReference.mjs.map +0 -1
  611. package/dist/MemoryRevalidation.d.mts +0 -5
  612. package/dist/MemoryRevalidation.mjs +0 -10
  613. package/dist/MemoryRevalidation.mjs.map +0 -1
  614. package/dist/MemoryStore.d.mts +0 -5
  615. package/dist/MemoryStore.mjs +0 -10
  616. package/dist/MemoryStore.mjs.map +0 -1
  617. package/dist/Messaging.d.mts +0 -5
  618. package/dist/Messaging.mjs +0 -10
  619. package/dist/Messaging.mjs.map +0 -1
  620. package/dist/MessagingHost.d.mts +0 -5
  621. package/dist/MessagingHost.mjs +0 -10
  622. package/dist/MessagingHost.mjs.map +0 -1
  623. package/dist/ModelContext.d.mts +0 -5
  624. package/dist/ModelContext.mjs +0 -10
  625. package/dist/ModelContext.mjs.map +0 -1
  626. package/dist/Receipt.d.mts +0 -5
  627. package/dist/Receipt.mjs +0 -10
  628. package/dist/Receipt.mjs.map +0 -1
  629. package/dist/Redaction.d.mts +0 -5
  630. package/dist/Redaction.mjs +0 -10
  631. package/dist/Redaction.mjs.map +0 -1
  632. package/dist/Remembering.d.mts +0 -5
  633. package/dist/Remembering.mjs +0 -10
  634. package/dist/Remembering.mjs.map +0 -1
  635. package/dist/RememberingStore.d.mts +0 -5
  636. package/dist/RememberingStore.mjs +0 -10
  637. package/dist/RememberingStore.mjs.map +0 -1
  638. package/dist/RunEvent.d.mts +0 -5
  639. package/dist/RunEvent.mjs +0 -10
  640. package/dist/RunEvent.mjs.map +0 -1
  641. package/dist/RunEventSink.d.mts +0 -5
  642. package/dist/RunEventSink.mjs +0 -10
  643. package/dist/RunEventSink.mjs.map +0 -1
  644. package/dist/RunHooks.d.mts +0 -5
  645. package/dist/RunHooks.mjs +0 -10
  646. package/dist/RunHooks.mjs.map +0 -1
  647. package/dist/RunOptions.d.mts +0 -5
  648. package/dist/RunOptions.mjs +0 -10
  649. package/dist/RunOptions.mjs.map +0 -1
  650. package/dist/RunPolicyUsage.d.mts +0 -5
  651. package/dist/RunPolicyUsage.mjs +0 -10
  652. package/dist/RunPolicyUsage.mjs.map +0 -1
  653. package/dist/SemanticMemory.d.mts +0 -5
  654. package/dist/SemanticMemory.mjs +0 -10
  655. package/dist/SemanticMemory.mjs.map +0 -1
  656. package/dist/SemanticMemoryIndex.d.mts +0 -5
  657. package/dist/SemanticMemoryIndex.mjs +0 -10
  658. package/dist/SemanticMemoryIndex.mjs.map +0 -1
  659. package/dist/SemanticMemoryRevalidation.d.mts +0 -5
  660. package/dist/SemanticMemoryRevalidation.mjs +0 -10
  661. package/dist/SemanticMemoryRevalidation.mjs.map +0 -1
  662. package/dist/Subagent.d.mts +0 -5
  663. package/dist/Subagent.mjs +0 -10
  664. package/dist/Subagent.mjs.map +0 -1
  665. package/dist/SubagentContract.d.mts +0 -5
  666. package/dist/SubagentContract.mjs +0 -10
  667. package/dist/SubagentContract.mjs.map +0 -1
  668. package/dist/SubagentHost.d.mts +0 -5
  669. package/dist/SubagentHost.mjs +0 -10
  670. package/dist/SubagentHost.mjs.map +0 -1
  671. package/dist/SubagentReservations.d.mts +0 -5
  672. package/dist/SubagentReservations.mjs +0 -10
  673. package/dist/SubagentReservations.mjs.map +0 -1
  674. package/dist/ThreadHistory.d.mts +0 -5
  675. package/dist/ThreadHistory.mjs +0 -10
  676. package/dist/ThreadHistory.mjs.map +0 -1
  677. package/dist/ToolBroker.d.mts +0 -5
  678. package/dist/ToolBroker.mjs +0 -10
  679. package/dist/ToolBroker.mjs.map +0 -1
  680. package/dist/ToolDiscovery.d.mts +0 -5
  681. package/dist/ToolDiscovery.mjs +0 -10
  682. package/dist/ToolDiscovery.mjs.map +0 -1
  683. package/dist/ToolResult.d.mts +0 -5
  684. package/dist/ToolResult.mjs +0 -10
  685. package/dist/ToolResult.mjs.map +0 -1
  686. package/dist/Usage.d.mts +0 -5
  687. package/dist/Usage.mjs +0 -10
  688. package/dist/Usage.mjs.map +0 -1
  689. package/dist/WebCapture.d.mts +0 -5
  690. package/dist/WebCapture.mjs +0 -10
  691. package/dist/WebCapture.mjs.map +0 -1
  692. package/dist/WebSearch.d.mts +0 -5
  693. package/dist/WebSearch.mjs +0 -10
  694. package/dist/WebSearch.mjs.map +0 -1
  695. package/dist/Worker.d.mts +0 -5
  696. package/dist/Worker.mjs +0 -10
  697. package/dist/Worker.mjs.map +0 -1
  698. package/dist/rolldown-runtime-BBjsoOtd.mjs +0 -27
  699. package/src/Agent.ts +0 -1
  700. package/src/AgentError.ts +0 -1
  701. package/src/AgentPolicy.ts +0 -1
  702. package/src/AgentRuntime.ts +0 -1
  703. package/src/AgentUpdates.ts +0 -1
  704. package/src/Approval.ts +0 -1
  705. package/src/Budget.ts +0 -1
  706. package/src/CodeMode.ts +0 -1
  707. package/src/Commands.ts +0 -1
  708. package/src/Compaction.ts +0 -1
  709. package/src/ContextCompactor.ts +0 -1
  710. package/src/ContextHistory.ts +0 -1
  711. package/src/ContextTools.ts +0 -1
  712. package/src/ContextWindow.ts +0 -1
  713. package/src/DurableStep.ts +0 -1
  714. package/src/EphemeralThreads.ts +0 -1
  715. package/src/IdGenerator.ts +0 -1
  716. package/src/Identifiers.ts +0 -1
  717. package/src/Mcp.ts +0 -1
  718. package/src/McpClient.ts +0 -1
  719. package/src/Memory.ts +0 -1
  720. package/src/MemoryNamespace.ts +0 -1
  721. package/src/MemoryNotes.ts +0 -1
  722. package/src/MemoryReference.ts +0 -1
  723. package/src/MemoryRevalidation.ts +0 -1
  724. package/src/MemoryStore.ts +0 -1
  725. package/src/Messaging.ts +0 -1
  726. package/src/MessagingHost.ts +0 -1
  727. package/src/ModelContext.ts +0 -1
  728. package/src/Receipt.ts +0 -1
  729. package/src/Redaction.ts +0 -1
  730. package/src/Remembering.ts +0 -1
  731. package/src/RememberingStore.ts +0 -1
  732. package/src/RunEvent.ts +0 -1
  733. package/src/RunEventSink.ts +0 -1
  734. package/src/RunHooks.ts +0 -1
  735. package/src/RunOptions.ts +0 -1
  736. package/src/RunPolicyUsage.ts +0 -1
  737. package/src/SemanticMemory.ts +0 -1
  738. package/src/SemanticMemoryIndex.ts +0 -1
  739. package/src/SemanticMemoryRevalidation.ts +0 -1
  740. package/src/Subagent.ts +0 -1
  741. package/src/SubagentContract.ts +0 -1
  742. package/src/SubagentHost.ts +0 -1
  743. package/src/SubagentReservations.ts +0 -1
  744. package/src/ThreadHistory.ts +0 -1
  745. package/src/ToolBroker.ts +0 -1
  746. package/src/ToolDiscovery.ts +0 -1
  747. package/src/ToolResult.ts +0 -1
  748. package/src/Usage.ts +0 -1
  749. package/src/WebCapture.ts +0 -1
  750. package/src/WebSearch.ts +0 -1
  751. package/src/Worker.ts +0 -1
@@ -0,0 +1,1469 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { n as utf8ByteLength } from "./utf8-DchGZRBd.mjs";
3
+ import { AgentPolicy } from "./core/AgentPolicy.mjs";
4
+ import { AgentId, DelegationId, RunId, SettlementId, ThreadId, ToolCallId } from "./core/Identifiers.mjs";
5
+ import { IdempotencyKey, JoinedToHost, Receipt } from "./core/Receipt.mjs";
6
+ import { IdGenerator as IdGenerator$1 } from "./core/IdGenerator.mjs";
7
+ import { BackgroundSpawnTool, DelegationTool, SubagentBudgetReservation, SubagentDelegationCaps, SubagentExecutionFailure, SubagentExecutionFailureClassification, SubagentGrant, SubagentReservationAmounts, WorkerOperationTool, narrowSubagentGrant } from "./core/SubagentContract.mjs";
8
+ import { RunUsageReport, unknownRunTotals } from "./core/Usage.mjs";
9
+ import { WorkerCompletion, WorkerContext, WorkerError, WorkerPage, WorkerRef, WorkerReport, WorkerStarted, WorkerSummary } from "./core/Worker.mjs";
10
+ import { BackgroundReporting, SubagentHost, WorkerReportPreparationFailure } from "./engine/SubagentHost.mjs";
11
+ import { a as SubagentDurability, i as AgentSpawner, o as SubagentDurabilityError, s as ToolCallWaiting } from "./AgentRuntime-BLyETCPo.mjs";
12
+ import { RunEventSink } from "./engine/RunEventSink.mjs";
13
+ import { SubagentBudgetExhausted, SubagentObservedUsage, SubagentReservationRequest, SubagentReservations, makeBudgetReservationId } from "./capabilities/SubagentReservations.mjs";
14
+ import { t as utf8Bytes } from "./utf8-BYfhEkcj.mjs";
15
+ import { Tool, Toolkit } from "effect/unstable/ai";
16
+ import { Cause, Clock, Context, Crypto, Duration, Effect, Encoding, Exit, Layer, Option, Ref, Schema, Scope, Stream } from "effect";
17
+ //#region src/capabilities/internal/subagent-contract.ts
18
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
19
+ const Natural = Schema.Natural;
20
+ const FinitePositiveDuration = Schema.Duration.pipe(Schema.refine((duration) => Duration.isFinite(duration) && Duration.isPositive(duration), { expected: "a finite positive duration" }));
21
+ const SubagentPolicyFields = Schema.Struct({
22
+ /** Total invocation slots, including reserved descendants, available through this delegation budget. */
23
+ maxChildren: PositiveInt,
24
+ /** Concurrently executing children per parent Run. */
25
+ maxConcurrency: PositiveInt,
26
+ /** Invocation slots held for the entire descendant subtree; omitted reserves zero. */
27
+ descendantInvocations: Schema.optionalKey(Natural),
28
+ /** Model turns reserved for each child invocation. */
29
+ maxTurns: PositiveInt,
30
+ /** Tool Calls reserved for each child invocation. */
31
+ maxToolCalls: PositiveInt,
32
+ /** Wall-clock duration reserved for each child invocation. */
33
+ maxDuration: FinitePositiveDuration,
34
+ maxInputTokens: Schema.optionalKey(PositiveInt),
35
+ maxOutputTokens: Schema.optionalKey(PositiveInt),
36
+ maxCostMicrousd: Schema.optionalKey(Natural),
37
+ maxResultBytes: Schema.optionalKey(PositiveInt)
38
+ });
39
+ /**
40
+ * Finite delegation bounds declared by one Subagent capability.
41
+ * Structural limits are hard limits; token
42
+ * and cost caps are optional and enforced only as honestly as provider
43
+ * reporting allows.
44
+ */
45
+ var SubagentPolicy = class extends Schema.Class("@effect-agent/capabilities/SubagentPolicy")(SubagentPolicyFields) {
46
+ /** Normalize and validate finite delegation bounds, throwing on invalid input. */
47
+ static make(input) {
48
+ return super.make({
49
+ ...input,
50
+ maxDuration: Duration.fromInputUnsafe(input.maxDuration)
51
+ });
52
+ }
53
+ };
54
+ const BoundedFailureText = Schema.String.check(Schema.isMaxLength(4096));
55
+ /**
56
+ * Delegation preflight denied before any child started.
57
+ * No reservation, identity, or event exists for the
58
+ * denied invocation; retry requires a new authorized parent Tool Call.
59
+ */
60
+ var SubagentPrestartDenied = class extends Schema.TaggedError()("SubagentPrestartDenied", {
61
+ delegationId: DelegationId,
62
+ targetAgentId: AgentId,
63
+ reason: Schema.Literals([
64
+ "nested-delegation",
65
+ "grant-violation",
66
+ "budget-conflict"
67
+ ]),
68
+ message: BoundedFailureText
69
+ }) {};
70
+ /**
71
+ * Input or result projection failed its Schema or bounds.
72
+ * Fail closed: the message is a fixed description and
73
+ * never carries the raw child value.
74
+ */
75
+ var SubagentProjectionFailure = class extends Schema.TaggedError()("SubagentProjectionFailure", {
76
+ delegationId: DelegationId,
77
+ stage: Schema.Literals(["input", "result"]),
78
+ message: BoundedFailureText
79
+ }) {};
80
+ const millisOfMaxDuration = (policy) => Math.max(1, Math.ceil(Duration.toMillis(policy.maxDuration)));
81
+ /**
82
+ * Derive the parent-Run delegation caps registered with
83
+ * `SubagentReservations` from one delegation policy: the per-invocation
84
+ * bounds scaled by `maxChildren` plus the invocation and concurrency limits.
85
+ */
86
+ const delegationCapsFromPolicy = (policy) => SubagentDelegationCaps.make({
87
+ maxTotalChildInvocations: policy.maxChildren,
88
+ maxConcurrentChildren: policy.maxConcurrency,
89
+ maxTurns: policy.maxChildren * policy.maxTurns,
90
+ maxToolCalls: policy.maxChildren * policy.maxToolCalls,
91
+ maxDurationMillis: policy.maxChildren * millisOfMaxDuration(policy),
92
+ ...policy.maxInputTokens === void 0 ? {} : { maxInputTokens: policy.maxChildren * policy.maxInputTokens },
93
+ ...policy.maxOutputTokens === void 0 ? {} : { maxOutputTokens: policy.maxChildren * policy.maxOutputTokens },
94
+ ...policy.maxCostMicrousd === void 0 ? {} : { maxCostMicrousd: policy.maxChildren * policy.maxCostMicrousd },
95
+ ...policy.maxResultBytes === void 0 ? {} : { maxResultBytes: policy.maxChildren * policy.maxResultBytes }
96
+ });
97
+ /** Derive the all-or-nothing per-invocation reservation from one delegation policy. */
98
+ const delegationAllocationFromPolicy = (policy) => SubagentReservationAmounts.make({
99
+ turns: policy.maxTurns,
100
+ toolCalls: policy.maxToolCalls,
101
+ durationMillis: millisOfMaxDuration(policy),
102
+ inputTokens: policy.maxInputTokens ?? 0,
103
+ outputTokens: policy.maxOutputTokens ?? 0,
104
+ costMicrousd: policy.maxCostMicrousd ?? 0,
105
+ resultBytes: policy.maxResultBytes ?? 0
106
+ });
107
+ //#endregion
108
+ //#region src/capabilities/internal/subagent-policy.ts
109
+ const resolveSubagentPolicy = (delegation, parent, parentCaps, mode = "conserved", resolvedTarget) => {
110
+ const parentCeiling = mode === "conserved" ? parent : void 0;
111
+ const inherited = resolvedTarget ?? AgentPolicy.resolve(delegation.target.policyOverrides ?? delegation.target.policy, parent);
112
+ const policy = delegation.policy ?? SubagentPolicy.make({
113
+ maxChildren: parent.maxToolCalls,
114
+ maxConcurrency: parent.toolConcurrency,
115
+ maxTurns: Math.min(inherited.maxTurns, parent.maxTurns),
116
+ maxToolCalls: Math.min(inherited.maxToolCalls, parent.maxToolCalls),
117
+ maxDuration: Duration.min(inherited.maxDuration, parent.maxDuration),
118
+ ...parent.tokenBudget === void 0 ? {} : {
119
+ maxInputTokens: parent.tokenBudget,
120
+ maxOutputTokens: parent.tokenBudget
121
+ },
122
+ ...parent.costBudgetMicrousd === void 0 ? {} : { maxCostMicrousd: parent.costBudgetMicrousd },
123
+ maxResultBytes: parent.toolResultBounds.maxBytes
124
+ });
125
+ const tokenCeiling = policy.maxInputTokens === void 0 || policy.maxOutputTokens === void 0 ? Math.min(inherited.tokenBudget ?? Infinity, parentCeiling?.tokenBudget ?? Infinity) : Math.min(inherited.tokenBudget ?? Infinity, parentCeiling?.tokenBudget ?? Infinity, policy.maxInputTokens + policy.maxOutputTokens);
126
+ const childPolicy = AgentPolicy.make({
127
+ ...inherited,
128
+ maxTurns: Math.min(inherited.maxTurns, policy.maxTurns, parentCeiling?.maxTurns ?? Infinity),
129
+ maxToolCalls: Math.min(inherited.maxToolCalls, policy.maxToolCalls, parentCeiling?.maxToolCalls ?? Infinity),
130
+ maxDuration: Duration.min(Duration.min(inherited.maxDuration, policy.maxDuration), parentCeiling?.maxDuration ?? Duration.infinity),
131
+ toolConcurrency: Math.min(inherited.toolConcurrency, parentCeiling?.toolConcurrency ?? Infinity),
132
+ ...parentCeiling === void 0 ? {} : { toolResultBounds: { maxBytes: Math.min(inherited.toolResultBounds.maxBytes, parentCeiling.toolResultBounds.maxBytes, Math.max(256, policy.maxResultBytes ?? Infinity)) } },
133
+ ...tokenCeiling === Infinity ? {} : {
134
+ tokenBudget: tokenCeiling,
135
+ completionReserveTokens: Math.min(inherited.completionReserveTokens, tokenCeiling)
136
+ },
137
+ ...Math.min(inherited.costBudgetMicrousd ?? Infinity, parentCeiling?.costBudgetMicrousd ?? Infinity, policy.maxCostMicrousd ?? Infinity) === Infinity ? {} : { costBudgetMicrousd: Math.min(inherited.costBudgetMicrousd ?? Infinity, parentCeiling?.costBudgetMicrousd ?? Infinity, policy.maxCostMicrousd ?? Infinity) }
138
+ });
139
+ const caps = parentCaps ?? (delegation.policy === void 0 ? SubagentDelegationCaps.make({
140
+ maxTotalChildInvocations: parent.maxToolCalls,
141
+ maxConcurrentChildren: parent.toolConcurrency,
142
+ maxTurns: parent.maxTurns,
143
+ maxToolCalls: parent.maxToolCalls,
144
+ maxDurationMillis: Math.ceil(Duration.toMillis(parent.maxDuration)),
145
+ ...parent.tokenBudget === void 0 ? {} : {
146
+ maxInputTokens: parent.tokenBudget,
147
+ maxOutputTokens: parent.tokenBudget
148
+ },
149
+ ...parent.costBudgetMicrousd === void 0 ? {} : { maxCostMicrousd: parent.costBudgetMicrousd }
150
+ }) : delegationCapsFromPolicy(policy));
151
+ return {
152
+ policy,
153
+ childPolicy,
154
+ allocation: delegationAllocationFromPolicy(policy),
155
+ caps
156
+ };
157
+ };
158
+ const resolveToolCallAllowance = (option, parameters, policy, childPolicy) => {
159
+ if (option === void 0) return childPolicy.maxToolCalls;
160
+ const extracted = option.fromParameters?.(parameters);
161
+ const requested = extracted !== void 0 && Number.isFinite(extracted) ? extracted : Number.isFinite(option.default) ? option.default : policy.maxToolCalls;
162
+ return Math.min(Math.max(1, Math.floor(requested)), policy.maxToolCalls, childPolicy.maxToolCalls);
163
+ };
164
+ /** Conservative subtree remainder after reserving this Run's own full execution ceiling. */
165
+ const residualSubagentCaps = (declared, parent, inherited, independentRun = false) => {
166
+ const allocation = inherited.allocation;
167
+ const remaining = (allocated, own, cap) => Math.min(cap ?? Infinity, Math.max(0, allocated - own));
168
+ return SubagentDelegationCaps.make({
169
+ maxTotalChildInvocations: Math.min(declared.maxTotalChildInvocations ?? Infinity, inherited.descendantInvocations ?? 0),
170
+ maxConcurrentChildren: Math.min(declared.maxConcurrentChildren ?? Infinity, parent.toolConcurrency, inherited.descendantInvocations ?? 0),
171
+ maxTurns: remaining(allocation.turns, parent.maxTurns, declared.maxTurns),
172
+ maxToolCalls: remaining(allocation.toolCalls, parent.maxToolCalls, declared.maxToolCalls),
173
+ maxDurationMillis: remaining(allocation.durationMillis, Math.ceil(Duration.toMillis(parent.maxDuration)), declared.maxDurationMillis),
174
+ ...independentRun && inherited.caps.maxInputTokens === void 0 && allocation.inputTokens === 0 && parent.tokenBudget === void 0 ? declared.maxInputTokens === void 0 ? {} : { maxInputTokens: declared.maxInputTokens } : { maxInputTokens: remaining(allocation.inputTokens, parent.tokenBudget ?? allocation.inputTokens, declared.maxInputTokens) },
175
+ ...independentRun && inherited.caps.maxOutputTokens === void 0 && allocation.outputTokens === 0 && parent.tokenBudget === void 0 ? declared.maxOutputTokens === void 0 ? {} : { maxOutputTokens: declared.maxOutputTokens } : { maxOutputTokens: remaining(allocation.outputTokens, parent.tokenBudget ?? allocation.outputTokens, declared.maxOutputTokens) },
176
+ ...independentRun && inherited.caps.maxCostMicrousd === void 0 && allocation.costMicrousd === 0 && parent.costBudgetMicrousd === void 0 ? declared.maxCostMicrousd === void 0 ? {} : { maxCostMicrousd: declared.maxCostMicrousd } : { maxCostMicrousd: remaining(allocation.costMicrousd, parent.costBudgetMicrousd ?? allocation.costMicrousd, declared.maxCostMicrousd) },
177
+ maxResultBytes: remaining(allocation.resultBytes, parent.toolResultBounds.maxBytes, declared.maxResultBytes)
178
+ });
179
+ };
180
+ //#endregion
181
+ //#region src/capabilities/internal/subagent-reporting.ts
182
+ const projectReport = (declaration) => Effect.fn("Subagent.projectReport")(function* (report) {
183
+ const { worker, observation } = report;
184
+ const invalid = () => WorkerReportPreparationFailure.make({ stage: "projection" });
185
+ if (worker.delegationId !== declaration.delegationId || worker.targetAgentId !== declaration.target.id || observation.receipt.threadId !== worker.threadId) return yield* invalid();
186
+ const base = {
187
+ _tag: "Settled",
188
+ worker,
189
+ receipt: yield* Schema.decodeEffect(Receipt)(observation.receipt).pipe(Effect.mapError(invalid)),
190
+ runId: observation.runId,
191
+ settlementId: observation.settlementId
192
+ };
193
+ let projected;
194
+ let encodedResult = null;
195
+ if (observation.outcome === "completed") {
196
+ const parameters = yield* Schema.decodeUnknownEffect(declaration.parameters)(observation.encodedParameters).pipe(Effect.mapError(invalid));
197
+ const output = yield* Schema.decodeUnknownEffect(declaration.target.output)(observation.encodedResult).pipe(Effect.mapError(invalid));
198
+ const result = yield* declaration.projectResult(output, { budgetExhausted: observation.budgetExhausted }, parameters);
199
+ const encoded = yield* Schema.encodeEffect(declaration.success)(result).pipe(Effect.mapError(invalid));
200
+ const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(Effect.mapError(invalid));
201
+ if (utf8ByteLength(JSON.stringify(json)) > (declaration.policy?.maxResultBytes ?? declaration.target.policy.toolResultBounds.maxBytes)) return yield* invalid();
202
+ projected = {
203
+ ...base,
204
+ outcome: "completed",
205
+ result
206
+ };
207
+ encodedResult = json;
208
+ } else projected = {
209
+ ...base,
210
+ outcome: observation.outcome,
211
+ failure: SubagentExecutionFailure.make({
212
+ delegationId: declaration.delegationId,
213
+ targetAgentId: declaration.target.id,
214
+ classification: observation.outcome === "failed" ? "child-failed" : "child-aborted",
215
+ childThreadId: worker.threadId,
216
+ childSubmissionId: observation.receipt.submissionId,
217
+ childRunId: observation.runId,
218
+ errorTag: observation.outcome === "failed" ? "WorkerFailed" : "WorkerAborted",
219
+ message: observation.outcome === "failed" ? "Worker input failed" : "Worker input was aborted"
220
+ })
221
+ };
222
+ return {
223
+ projected,
224
+ encodedResult
225
+ };
226
+ });
227
+ /** Framework reporting shares the same bounded declaration projection as custom mapping. */
228
+ const automaticReporting = (declaration) => ({
229
+ delegationId: declaration.delegationId,
230
+ target: declaration.target,
231
+ mode: "standard",
232
+ prepare: Effect.fn("Subagent.automaticReport")(function* (report) {
233
+ const { projected, encodedResult } = yield* projectReport(declaration)(report);
234
+ const encoded = projected.outcome === "completed" ? {
235
+ ...projected,
236
+ result: encodedResult
237
+ } : {
238
+ ...projected,
239
+ failure: yield* Schema.encodeEffect(SubagentExecutionFailure)(projected.failure).pipe(Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: "projection" })))
240
+ };
241
+ return {
242
+ encodedInput: null,
243
+ message: yield* Schema.decodeEffect(WorkerCompletion)({
244
+ _tag: "WorkerCompletion",
245
+ schemaVersion: 1,
246
+ report: encoded,
247
+ budgetExhausted: report.observation.budgetExhausted
248
+ }).pipe(Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: "projection" })))
249
+ };
250
+ })
251
+ });
252
+ /**
253
+ * Define an optional application-specific conversion for `background({ reportToParent: report })`.
254
+ * Existing Agent Registration `reporting` arrays remain supported. The input Schema must be the coordinator Definition's exact input Schema.
255
+ * Preparation is bounded by the durable host; a retained prepared envelope is never reprojected
256
+ * during delivery retries. The callback should be deterministic and have no external side effects.
257
+ */
258
+ const reporting = (declaration, options) => {
259
+ const prepare = Effect.fn("Subagent.reporting.prepare")(function* (report) {
260
+ const { projected } = yield* projectReport(declaration)(report);
261
+ const input = yield* options.prepare(projected);
262
+ const encoded = yield* Schema.encodeEffect(options.input)(input).pipe(Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: "input" })));
263
+ return { encodedInput: yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: "input" }))) };
264
+ });
265
+ return Object.freeze({
266
+ delegationId: declaration.delegationId,
267
+ target: declaration.target,
268
+ input: options.input,
269
+ prepare
270
+ });
271
+ };
272
+ /**
273
+ * Adapt a report expressed in a receiving worker declaration's Parameters to its Agent input.
274
+ * Use this on that worker's registration when it can itself launch reporting workers. This
275
+ * explicit conversion preserves custom Parameters and charges the next input to its ancestor.
276
+ */
277
+ const reportingToWorker = (report, destination) => {
278
+ if (report.input !== destination.parameters) throw new TypeError("Worker reporting must use the destination declaration's Parameters Schema");
279
+ return Object.freeze({
280
+ delegationId: report.delegationId,
281
+ target: report.target,
282
+ input: destination.target.input,
283
+ destination: {
284
+ delegationId: destination.delegationId,
285
+ target: destination.target
286
+ },
287
+ prepare: Effect.fn("Subagent.reportingToWorker.prepare")(function* (run) {
288
+ const encodedParameters = (yield* report.prepare(run)).encodedInput;
289
+ const invalid = () => WorkerReportPreparationFailure.make({ stage: "input" });
290
+ const parameters = yield* Schema.decodeEffect(destination.parameters)(encodedParameters).pipe(Effect.mapError(invalid));
291
+ const input = yield* destination.prepareInput(parameters, {
292
+ source: "programmatic",
293
+ delegationId: destination.delegationId,
294
+ parent: {
295
+ agentId: run.context.source.agentId,
296
+ threadId: run.context.source.threadId
297
+ }
298
+ });
299
+ const encoded = yield* Schema.encodeEffect(destination.target.input)(input).pipe(Effect.mapError(invalid));
300
+ return {
301
+ encodedInput: yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(Effect.mapError(invalid)),
302
+ encodedParameters
303
+ };
304
+ })
305
+ });
306
+ };
307
+ //#endregion
308
+ //#region src/capabilities/internal/subagent-background.ts
309
+ /** Portable identity checked against this declaration; possession grants no authority. */
310
+ const Worker = (declaration) => WorkerRef.check(Schema.makeFilter((worker) => worker.delegationId === declaration.delegationId && worker.targetAgentId === declaration.target.id)).pipe(Schema.brand(`@effect-agent/Worker/${declaration.name}`));
311
+ /** Observes one exact Receipt. Terminal failure data never includes raw child output. */
312
+ const WorkerObservation = (success) => Schema.Union([
313
+ Schema.Struct({
314
+ _tag: Schema.Literal("Pending"),
315
+ receipt: Receipt
316
+ }),
317
+ Schema.Struct({
318
+ _tag: Schema.Literal("Settled"),
319
+ receipt: Receipt,
320
+ runId: RunId,
321
+ settlementId: SettlementId,
322
+ outcome: Schema.Literal("completed"),
323
+ result: success
324
+ }),
325
+ Schema.Struct({
326
+ _tag: Schema.Literal("Settled"),
327
+ receipt: Receipt,
328
+ runId: Schema.optionalKey(RunId),
329
+ settlementId: SettlementId,
330
+ outcome: Schema.Literals(["failed", "aborted"]),
331
+ failure: SubagentExecutionFailure
332
+ })
333
+ ]);
334
+ const host = Effect.serviceOption(SubagentHost).pipe(Effect.flatMap((service) => Option.match(service, {
335
+ onNone: () => WorkerError.make({
336
+ operation: "context",
337
+ reason: "unavailable"
338
+ }),
339
+ onSome: Effect.succeed
340
+ })));
341
+ const receiptEqual = (left, right) => left.threadId === right.threadId && left.submissionId === right.submissionId && left.receiptId === right.receiptId && left.queueSequence === right.queueSequence;
342
+ const operations = (declaration) => {
343
+ const workerSchema = Worker(declaration);
344
+ const projectionFailure = (stage) => SubagentProjectionFailure.make({
345
+ delegationId: declaration.delegationId,
346
+ stage,
347
+ message: stage === "input" ? "Worker input did not satisfy the declaration Schema" : "Worker result did not satisfy the declaration Schema"
348
+ });
349
+ const validateWorker = (worker, operation) => Schema.decodeUnknownEffect(workerSchema)(worker).pipe(Effect.mapError(() => WorkerError.make({
350
+ operation,
351
+ reason: "worker-mismatch"
352
+ })));
353
+ const validateReceipt = (worker, receipt, operation) => Schema.decodeEffect(Receipt.check(Schema.makeFilter((value) => value.threadId === worker.threadId)))(receipt).pipe(Effect.mapError(() => WorkerError.make({
354
+ operation,
355
+ reason: "receipt-mismatch"
356
+ })));
357
+ const context = host.pipe(Effect.flatMap((service) => service.context), Effect.flatMap(Schema.decodeUnknownEffect(Schema.toType(WorkerContext))), Effect.mapError((error) => Schema.is(WorkerError)(error) ? error : WorkerError.make({
358
+ operation: "context",
359
+ reason: "corrupt"
360
+ })));
361
+ const prepare = Effect.fn("Subagent.prepareWorkerInput")(function* (parameters, caller) {
362
+ const encodedParameters = yield* Schema.encodeEffect(declaration.parameters)(parameters).pipe(Effect.mapError(() => projectionFailure("input")));
363
+ const source = caller.source;
364
+ const preparation = source._tag === "tool" ? {
365
+ source: "tool",
366
+ delegationId: declaration.delegationId,
367
+ toolCallId: source.toolCallId,
368
+ parent: {
369
+ agentId: source.agentId,
370
+ threadId: source.threadId,
371
+ runId: source.runId
372
+ }
373
+ } : {
374
+ source: "programmatic",
375
+ delegationId: declaration.delegationId,
376
+ parent: {
377
+ agentId: source.agentId,
378
+ threadId: source.threadId
379
+ }
380
+ };
381
+ const input = yield* declaration.prepareInput(parameters, preparation);
382
+ return {
383
+ encodedParameters,
384
+ encodedInput: yield* Schema.encodeEffect(declaration.target.input)(input).pipe(Effect.mapError(() => projectionFailure("input")))
385
+ };
386
+ });
387
+ const validateKey = (key, operation) => Schema.decodeEffect(IdempotencyKey)(key).pipe(Effect.mapError(() => WorkerError.make({
388
+ operation,
389
+ reason: "idempotency-conflict"
390
+ })));
391
+ return {
392
+ start: Effect.fn("Subagent.start")(function* (parameters, options) {
393
+ const service = yield* host;
394
+ const caller = yield* context;
395
+ const key = yield* validateKey(options.idempotencyKey, "start");
396
+ const grant = narrowSubagentGrant(declaration.grant, caller.grant);
397
+ if (caller.depth + 1 > grant.maxDepth) return yield* SubagentPrestartDenied.make({
398
+ delegationId: declaration.delegationId,
399
+ targetAgentId: declaration.target.id,
400
+ reason: "nested-delegation",
401
+ message: "Worker start exceeds the inherited depth ceiling"
402
+ });
403
+ if (!(caller.grant?.childLifetimes ?? ["attached", "background"]).includes("background")) return yield* SubagentPrestartDenied.make({
404
+ delegationId: declaration.delegationId,
405
+ targetAgentId: declaration.target.id,
406
+ reason: "grant-violation",
407
+ message: "The inherited grant does not permit background children"
408
+ });
409
+ const prepared = yield* prepare(parameters, caller);
410
+ const effectiveTarget = yield* service.resolveTargetPolicy({
411
+ target: declaration.target,
412
+ encodedInput: prepared.encodedInput
413
+ });
414
+ const resolvedTarget = Option.getOrUndefined(effectiveTarget);
415
+ const resolved = resolveSubagentPolicy(declaration, options.budgetScope === "worker-run" ? resolvedTarget ?? declaration.target.policy : caller.policy, void 0, options.budgetScope === "worker-run" ? "root-attached" : "conserved", resolvedTarget);
416
+ const encodedGrant = yield* Schema.encodeEffect(SubagentGrant)(grant).pipe(Effect.mapError(() => projectionFailure("input")));
417
+ const started = yield* service.start({
418
+ ...prepared,
419
+ delegationId: declaration.delegationId,
420
+ target: declaration.target,
421
+ idempotencyKey: key,
422
+ ...options.budgetScope === void 0 ? {} : { budgetScope: options.budgetScope },
423
+ encodedGrant,
424
+ policy: resolved.childPolicy,
425
+ budget: SubagentBudgetReservation.make({
426
+ caps: resolved.caps,
427
+ allocation: resolved.allocation,
428
+ ...resolved.policy.descendantInvocations === void 0 ? {} : { descendantInvocations: resolved.policy.descendantInvocations }
429
+ }),
430
+ toolCallAllowance: resolveToolCallAllowance(declaration.toolCallAllowance, parameters, resolved.policy, resolved.childPolicy)
431
+ });
432
+ const validated = yield* Schema.decodeEffect(WorkerStarted)(started).pipe(Effect.mapError(() => WorkerError.make({
433
+ operation: "start",
434
+ reason: "corrupt"
435
+ })));
436
+ return {
437
+ worker: yield* validateWorker(validated.worker, "start"),
438
+ receipt: validated.receipt
439
+ };
440
+ }),
441
+ followUp: Effect.fn("Subagent.followUp")(function* (worker, parameters, options) {
442
+ const service = yield* host;
443
+ const validated = yield* validateWorker(worker, "followUp");
444
+ const caller = yield* context;
445
+ const key = yield* validateKey(options.idempotencyKey, "followUp");
446
+ const prepared = yield* prepare(parameters, caller);
447
+ return yield* validateReceipt(validated, yield* service.followUp({
448
+ ...prepared,
449
+ worker: validated,
450
+ target: declaration.target,
451
+ idempotencyKey: key
452
+ }), "followUp");
453
+ }),
454
+ observe: Effect.fn("Subagent.observeWorker")(function* (operation, worker, receipt) {
455
+ const service = yield* host;
456
+ const validated = yield* validateWorker(worker, operation);
457
+ const requested = yield* validateReceipt(validated, receipt, operation);
458
+ const observed = yield* service[operation]({
459
+ worker: validated,
460
+ target: declaration.target,
461
+ receipt: requested
462
+ });
463
+ const returned = yield* validateReceipt(validated, observed.receipt, operation);
464
+ if (!receiptEqual(returned, requested)) return yield* WorkerError.make({
465
+ operation,
466
+ reason: "receipt-mismatch"
467
+ });
468
+ if (observed._tag === "Pending") {
469
+ if (operation === "await") return yield* WorkerError.make({
470
+ operation,
471
+ reason: "corrupt"
472
+ });
473
+ return {
474
+ _tag: "Pending",
475
+ receipt: returned
476
+ };
477
+ }
478
+ const base = {
479
+ _tag: "Settled",
480
+ receipt: returned,
481
+ ...observed.runId === void 0 ? {} : { runId: yield* Schema.decodeEffect(RunId)(observed.runId).pipe(Effect.mapError(() => WorkerError.make({
482
+ operation,
483
+ reason: "corrupt"
484
+ }))) },
485
+ settlementId: yield* Schema.decodeEffect(SettlementId)(observed.settlementId).pipe(Effect.mapError(() => WorkerError.make({
486
+ operation,
487
+ reason: "corrupt"
488
+ })))
489
+ };
490
+ if (observed.outcome === "failed" || observed.outcome === "aborted") return {
491
+ ...base,
492
+ outcome: observed.outcome,
493
+ failure: SubagentExecutionFailure.make({
494
+ delegationId: declaration.delegationId,
495
+ targetAgentId: declaration.target.id,
496
+ classification: observed.outcome === "failed" ? "child-failed" : "child-aborted",
497
+ childThreadId: worker.threadId,
498
+ childSubmissionId: returned.submissionId,
499
+ ...base.runId === void 0 ? {} : { childRunId: base.runId },
500
+ errorTag: observed.outcome === "failed" ? "WorkerFailed" : "WorkerAborted",
501
+ message: observed.outcome === "failed" ? "Worker input failed" : "Worker input was aborted"
502
+ })
503
+ };
504
+ if (observed.outcome !== "completed" || base.runId === void 0 || typeof observed.budgetExhausted !== "boolean") return yield* WorkerError.make({
505
+ operation,
506
+ reason: "corrupt"
507
+ });
508
+ const parameters = yield* Schema.decodeUnknownEffect(declaration.parameters)(observed.encodedParameters).pipe(Effect.mapError(() => projectionFailure("result")));
509
+ const output = yield* Schema.decodeUnknownEffect(declaration.target.output)(observed.encodedResult).pipe(Effect.mapError(() => projectionFailure("result")));
510
+ const result = yield* declaration.projectResult(output, { budgetExhausted: observed.budgetExhausted }, parameters);
511
+ const encoded = yield* Schema.encodeEffect(declaration.success)(result).pipe(Effect.mapError(() => projectionFailure("result")));
512
+ const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(Effect.mapError(() => projectionFailure("result")));
513
+ const caller = yield* context;
514
+ if (utf8ByteLength(JSON.stringify(json)) > (declaration.policy?.maxResultBytes ?? caller.policy.toolResultBounds.maxBytes)) return yield* projectionFailure("result");
515
+ return yield* Schema.decodeUnknownEffect(Schema.toType(WorkerObservation(declaration.success)))({
516
+ ...base,
517
+ outcome: "completed",
518
+ result
519
+ }).pipe(Effect.mapError(() => projectionFailure("result")));
520
+ }),
521
+ list: Effect.fn("Subagent.list")(function* (options = {}) {
522
+ const service = yield* host;
523
+ const limit = yield* Schema.decodeEffect(Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)))(options.limit ?? 20).pipe(Effect.mapError(() => WorkerError.make({
524
+ operation: "list",
525
+ reason: "capacity"
526
+ })));
527
+ const page = yield* service.list({
528
+ delegationId: declaration.delegationId,
529
+ target: declaration.target,
530
+ limit,
531
+ ...options.after === void 0 ? {} : { after: options.after }
532
+ });
533
+ const validated = yield* Schema.decodeEffect(WorkerPage)(page).pipe(Effect.mapError(() => WorkerError.make({
534
+ operation: "list",
535
+ reason: "corrupt"
536
+ })));
537
+ if (validated.items.length > limit) return yield* WorkerError.make({
538
+ operation: "list",
539
+ reason: "corrupt"
540
+ });
541
+ const items = [];
542
+ for (const item of validated.items) {
543
+ const worker = yield* validateWorker(item.worker, "list");
544
+ const latestReceipt = item.latestReceipt === null ? null : yield* validateReceipt(worker, item.latestReceipt, "list");
545
+ items.push({
546
+ ...item,
547
+ worker,
548
+ latestReceipt
549
+ });
550
+ }
551
+ return {
552
+ items,
553
+ next: validated.next
554
+ };
555
+ }),
556
+ cancel: Effect.fn("Subagent.cancel")(function* (worker, receipt) {
557
+ const service = yield* host;
558
+ const validated = yield* validateWorker(worker, "cancel");
559
+ const requested = yield* validateReceipt(validated, receipt, "cancel");
560
+ yield* service.cancel({
561
+ worker: validated,
562
+ target: declaration.target,
563
+ receipt: requested
564
+ });
565
+ })
566
+ };
567
+ };
568
+ /** Start a host-managed worker. Retrying the same explicit key reuses the accepted input. */
569
+ const start = (declaration, parameters, options) => operations(declaration).start(parameters, options);
570
+ /** Admit typed follow-up parameters to the same worker Thread. */
571
+ const followUp = (declaration, worker, parameters, options) => operations(declaration).followUp(worker, parameters, options);
572
+ /** Inspect a continuing worker with the same summary contract returned by list. */
573
+ const summary = (declaration, worker) => Effect.gen(function* () {
574
+ const service = yield* host;
575
+ const validated = yield* Schema.decodeEffect(Worker(declaration))(worker).pipe(Effect.mapError(() => WorkerError.make({
576
+ operation: "inspect",
577
+ reason: "worker-mismatch"
578
+ })));
579
+ const result = yield* service.summary({
580
+ worker: validated,
581
+ target: declaration.target
582
+ });
583
+ const value = yield* Schema.decodeEffect(WorkerSummary)(result).pipe(Effect.mapError(() => WorkerError.make({
584
+ operation: "inspect",
585
+ reason: "corrupt"
586
+ })));
587
+ if (value.worker.threadId !== validated.threadId || value.worker.delegationId !== validated.delegationId || value.worker.targetAgentId !== validated.targetAgentId || value.latestReceipt !== null && value.latestReceipt.threadId !== validated.threadId) return yield* WorkerError.make({
588
+ operation: "inspect",
589
+ reason: "worker-mismatch"
590
+ });
591
+ return {
592
+ ...value,
593
+ worker: validated
594
+ };
595
+ });
596
+ function inspect(declaration, worker, receipt) {
597
+ return receipt === void 0 ? summary(declaration, worker) : operations(declaration).observe("inspect", worker, receipt);
598
+ }
599
+ /** Read an authorized finite history snapshot; pass the last emitted sequence to resume. */
600
+ const observe = (declaration, worker, options = {}) => Stream.unwrap(Effect.gen(function* () {
601
+ const service = yield* host;
602
+ const validated = yield* Schema.decodeEffect(Worker(declaration))(worker).pipe(Effect.mapError(() => WorkerError.make({
603
+ operation: "observe",
604
+ reason: "worker-mismatch"
605
+ })));
606
+ const after = options.after === void 0 ? void 0 : yield* Schema.decodeEffect(Schema.Natural)(options.after).pipe(Effect.mapError(() => WorkerError.make({
607
+ operation: "observe",
608
+ reason: "corrupt"
609
+ })));
610
+ return service.observe({
611
+ worker: validated,
612
+ target: declaration.target,
613
+ ...after === void 0 ? {} : { after }
614
+ });
615
+ }));
616
+ /** Wait for the exact Receipt. Interrupting this Effect never cancels accepted work. */
617
+ const awaitWorker = (declaration, worker, receipt) => operations(declaration).observe("await", worker, receipt);
618
+ /** List only workers visible through the caller-bound host facet. */
619
+ const list = (declaration, options = {}) => operations(declaration).list(options);
620
+ /** Request cancellation of exactly one Receipt; JoinedToHost remains a typed conflict. */
621
+ const cancel = (declaration, worker, receipt) => operations(declaration).cancel(worker, receipt);
622
+ const ReceiptParameters = (declaration) => Schema.Struct({
623
+ worker: Worker(declaration),
624
+ receipt: Receipt
625
+ });
626
+ const WorkerParameters = (declaration) => Schema.Struct({ worker: Worker(declaration) });
627
+ const Summary = (declaration) => Schema.Struct({
628
+ worker: Worker(declaration),
629
+ latestReceipt: Schema.NullOr(Receipt),
630
+ state: Schema.Literals([
631
+ "starting",
632
+ "active",
633
+ "idle"
634
+ ])
635
+ });
636
+ const FollowUpParameters = (declaration, parameters) => Schema.Struct({
637
+ worker: Worker(declaration),
638
+ parameters
639
+ });
640
+ const ListParameters = Schema.Struct({
641
+ limit: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100))),
642
+ after: Schema.optionalKey(ThreadId)
643
+ });
644
+ const Started = (declaration) => Schema.Struct({
645
+ worker: Worker(declaration),
646
+ receipt: Receipt
647
+ }).check(Schema.makeFilter((value) => value.worker.threadId === value.receipt.threadId));
648
+ const Page = (declaration) => Schema.Struct({
649
+ items: Schema.Array(Schema.Struct({
650
+ worker: Worker(declaration),
651
+ latestReceipt: Schema.NullOr(Receipt),
652
+ state: Schema.Literals([
653
+ "starting",
654
+ "active",
655
+ "idle"
656
+ ])
657
+ })).check(Schema.isMaxLength(100)),
658
+ next: Schema.NullOr(ThreadId)
659
+ });
660
+ const preparationFailure = (failure) => Schema.Union([
661
+ failure,
662
+ SubagentProjectionFailure,
663
+ WorkerError
664
+ ]);
665
+ const startFailure = (failure) => Schema.Union([
666
+ failure,
667
+ SubagentProjectionFailure,
668
+ SubagentPrestartDenied,
669
+ WorkerError
670
+ ]);
671
+ const cancelFailure = Schema.Union([WorkerError, JoinedToHost]);
672
+ const modelKey = Effect.fn("Subagent.workerToolKey")(function* (operation) {
673
+ const caller = yield* (yield* host).context;
674
+ if (caller.source._tag !== "tool") return yield* WorkerError.make({
675
+ operation,
676
+ reason: "denied"
677
+ });
678
+ const source = caller.source;
679
+ const crypto = yield* Crypto.Crypto;
680
+ const bytes = utf8Bytes(JSON.stringify([
681
+ "worker-tool-v1",
682
+ operation,
683
+ source.agentId,
684
+ source.threadId,
685
+ source.runId,
686
+ source.toolCallId
687
+ ]));
688
+ const digest = yield* crypto.digest("SHA-256", bytes).pipe(Effect.mapError(() => WorkerError.make({
689
+ operation,
690
+ reason: "unavailable"
691
+ })));
692
+ return yield* Schema.decodeEffect(IdempotencyKey)(`worker:${Encoding.encodeHex(digest)}`).pipe(Effect.mapError(() => WorkerError.make({
693
+ operation,
694
+ reason: "unavailable"
695
+ })));
696
+ });
697
+ let reportingServiceId = 0;
698
+ /**
699
+ * Derive optional native AI Tools and their handler Layer from one immutable declaration.
700
+ * Projection services are captured by the Layer; the host and stable-key Crypto service remain
701
+ * invocation dependencies. The attached `.tool` and its suspension behavior are unchanged.
702
+ */
703
+ const background$1 = (declaration, selected) => {
704
+ const report = selected.reportToParent === true ? automaticReporting(declaration) : selected.reportToParent;
705
+ if (report !== void 0 && (report.delegationId !== declaration.delegationId || report.target !== declaration.target)) throw new TypeError("Background reporting must use the same subagent declaration and target");
706
+ const reportService = Context.Service(`@effect-agent/capabilities/BackgroundReport/${declaration.name}/${reportingServiceId++}`);
707
+ const descriptor = report === void 0 ? void 0 : {
708
+ ...report,
709
+ prepare: (value) => Effect.flatMap(Effect.serviceOption(reportService), (service) => Option.isSome(service) ? service.value.prepare(value) : WorkerReportPreparationFailure.make({ stage: "preparation" }))
710
+ };
711
+ const ops = operations(declaration);
712
+ const failure = preparationFailure(declaration.failure);
713
+ const receiptParameters = ReceiptParameters(declaration);
714
+ const startTool = Tool.make(`${declaration.name}_start`, {
715
+ description: `Start ${declaration.name} in the background and return its worker identity and Receipt.`,
716
+ parameters: declaration.parameters,
717
+ success: Started(declaration),
718
+ failure: startFailure(declaration.failure)
719
+ }).annotate(WorkerOperationTool, true).annotate(BackgroundSpawnTool, true).addDependency(SubagentHost).addDependency(Crypto.Crypto);
720
+ const followUpTool = Tool.make(`${declaration.name}_follow_up`, {
721
+ description: `Send typed follow-up input to an existing ${declaration.name} worker.`,
722
+ parameters: FollowUpParameters(declaration, declaration.parameters),
723
+ success: Receipt,
724
+ failure
725
+ }).annotate(WorkerOperationTool, true).addDependency(SubagentHost).addDependency(Crypto.Crypto);
726
+ const inspectTool = Tool.make(`${declaration.name}_inspect`, {
727
+ description: `Inspect one exact ${declaration.name} Receipt without waiting.`,
728
+ parameters: receiptParameters,
729
+ success: WorkerObservation(declaration.success),
730
+ failure
731
+ }).annotate(WorkerOperationTool, true).addDependency(SubagentHost);
732
+ const summaryTool = Tool.make(`${declaration.name}_summary`, {
733
+ description: `Inspect ${declaration.name}'s continuing worker state and latest accepted input.`,
734
+ parameters: WorkerParameters(declaration),
735
+ success: Summary(declaration),
736
+ failure: WorkerError
737
+ }).annotate(WorkerOperationTool, true).addDependency(SubagentHost);
738
+ const listTool = Tool.make(`${declaration.name}_list`, {
739
+ description: `List visible ${declaration.name} workers.`,
740
+ parameters: ListParameters,
741
+ success: Page(declaration),
742
+ failure: WorkerError
743
+ }).annotate(WorkerOperationTool, true).addDependency(SubagentHost);
744
+ const cancelTool = Tool.make(`${declaration.name}_cancel`, {
745
+ description: `Request cancellation of one exact ${declaration.name} Receipt.`,
746
+ parameters: receiptParameters,
747
+ success: Schema.Void,
748
+ failure: cancelFailure
749
+ }).annotate(WorkerOperationTool, true).addDependency(SubagentHost);
750
+ const chosen = Object.entries({
751
+ start: startTool,
752
+ followUp: followUpTool,
753
+ inspect: inspectTool,
754
+ summary: summaryTool,
755
+ list: listTool,
756
+ cancel: cancelTool
757
+ }).filter(([operation]) => selected[operation] === true).map(([, tool]) => tool.annotate(BackgroundReporting, descriptor));
758
+ const toolkit = Toolkit.make(...chosen);
759
+ const build = Effect.gen(function* () {
760
+ const captured = yield* Effect.context();
761
+ return {
762
+ [startTool.name]: (parameters) => Effect.gen(function* () {
763
+ const service = yield* host;
764
+ const idempotencyKey = yield* modelKey("start");
765
+ return yield* ops.start(parameters, {
766
+ idempotencyKey,
767
+ ...selected.budgetScope === void 0 ? {} : { budgetScope: selected.budgetScope }
768
+ }).pipe(Effect.provideService(SubagentHost, service), Effect.provide(captured));
769
+ }),
770
+ [followUpTool.name]: (parameters) => Effect.gen(function* () {
771
+ const service = yield* host;
772
+ const idempotencyKey = yield* modelKey("followUp");
773
+ return yield* ops.followUp(parameters.worker, parameters.parameters, { idempotencyKey }).pipe(Effect.provideService(SubagentHost, service), Effect.provide(captured));
774
+ }),
775
+ [inspectTool.name]: (parameters) => Effect.gen(function* () {
776
+ const service = yield* host;
777
+ return yield* ops.observe("inspect", parameters.worker, parameters.receipt).pipe(Effect.provideService(SubagentHost, service), Effect.provide(captured));
778
+ }),
779
+ [listTool.name]: (parameters) => ops.list(parameters),
780
+ [summaryTool.name]: (parameters) => summary(declaration, parameters.worker),
781
+ [cancelTool.name]: (parameters) => ops.cancel(parameters.worker, parameters.receipt)
782
+ };
783
+ });
784
+ const reportingLayer = report === void 0 ? Layer.empty : Layer.effect(reportService, Effect.map(Effect.context(), (context) => ({
785
+ ...report,
786
+ prepare: (value) => Effect.scoped(Effect.suspend(() => report.prepare(value))).pipe(Effect.provide(context), Effect.mapError((error) => Schema.is(WorkerReportPreparationFailure)(error) ? error : WorkerReportPreparationFailure.make({ stage: "preparation" })))
787
+ })));
788
+ const layer = Layer.merge(toolkit.toLayer(build), reportingLayer);
789
+ return Object.freeze({
790
+ tools: toolkit.tools,
791
+ toolkit,
792
+ layer
793
+ });
794
+ };
795
+ //#endregion
796
+ //#region src/capabilities/Subagent.ts
797
+ var Subagent_exports = /* @__PURE__ */ __exportAll({
798
+ SubagentDurableAccounting: () => SubagentDurableAccounting,
799
+ SubagentExecutionFailure: () => SubagentExecutionFailure,
800
+ SubagentExecutionFailureClassification: () => SubagentExecutionFailureClassification,
801
+ SubagentGrant: () => SubagentGrant,
802
+ SubagentPolicy: () => SubagentPolicy,
803
+ SubagentPrestartDenied: () => SubagentPrestartDenied,
804
+ SubagentProjectionFailure: () => SubagentProjectionFailure,
805
+ SubagentResult: () => SubagentResult,
806
+ Worker: () => Worker,
807
+ WorkerCompletion: () => WorkerCompletion,
808
+ WorkerObservation: () => WorkerObservation,
809
+ WorkerReport: () => WorkerReport,
810
+ await: () => awaitWorker,
811
+ background: () => background,
812
+ cancel: () => cancel,
813
+ define: () => define,
814
+ delegationAllocationFromPolicy: () => delegationAllocationFromPolicy,
815
+ delegationCapsFromPolicy: () => delegationCapsFromPolicy,
816
+ followUp: () => followUp,
817
+ inspect: () => inspect,
818
+ layer: () => layer,
819
+ list: () => list,
820
+ make: () => make,
821
+ observe: () => observe,
822
+ reporting: () => reporting,
823
+ reportingToWorker: () => reportingToWorker,
824
+ start: () => start
825
+ });
826
+ const decodeDelegationId = Schema.decodeSync(DelegationId);
827
+ /** Default delegation result, preserving partial-output information. */
828
+ const SubagentResult = (output) => Schema.Struct({
829
+ output,
830
+ budgetExhausted: Schema.Boolean
831
+ });
832
+ /**
833
+ * Declare one attached delegation as a pure value.
834
+ *
835
+ * The returned `.tool` is a native Effect AI Tool whose handler dependencies
836
+ * are exactly the engine-owned `AgentSpawner`, `RunEventSink`, and
837
+ * `SubagentDurability` (SUB-003); runtime IDs have an overridable default.
838
+ * The concrete child Binding arrives only through
839
+ * `Subagent.layer`. Throws on an invalid delegation name. Nested declarations remain inert unless the
840
+ * effective inherited grant and reserved subtree budget permit their lifetime and depth.
841
+ */
842
+ const makeExplicit = (name, options) => {
843
+ const delegationId = decodeDelegationId(name);
844
+ const grant = options.grant ?? SubagentGrant.make({
845
+ allowedToolNames: Object.keys(options.target.toolkit.tools),
846
+ maxDepth: 1
847
+ });
848
+ const failureMode = options.failureMode ?? "error";
849
+ const containedFailure = Schema.Union([
850
+ options.failure,
851
+ SubagentPrestartDenied,
852
+ SubagentBudgetExhausted,
853
+ SubagentProjectionFailure,
854
+ SubagentExecutionFailure
855
+ ]);
856
+ const returnModeTool = Tool.make(name, {
857
+ description: options.description,
858
+ parameters: options.parameters,
859
+ success: Schema.Union([options.success, containedFailure]),
860
+ failure: Schema.Union([ToolCallWaiting, SubagentDurabilityError]),
861
+ needsApproval: options.needsApproval
862
+ });
863
+ const errorModeTool = Tool.make(name, {
864
+ description: options.description,
865
+ parameters: options.parameters,
866
+ success: options.success,
867
+ failure: Schema.Union([
868
+ options.failure,
869
+ SubagentPrestartDenied,
870
+ SubagentBudgetExhausted,
871
+ SubagentProjectionFailure,
872
+ SubagentExecutionFailure,
873
+ ToolCallWaiting,
874
+ SubagentDurabilityError
875
+ ]),
876
+ needsApproval: options.needsApproval
877
+ });
878
+ const tool = (failureMode === "return" ? returnModeTool : errorModeTool).annotate(DelegationTool, true).addDependency(AgentSpawner).addDependency(RunEventSink).addDependency(SubagentDurability).addDependency(IdGenerator$1);
879
+ return Object.freeze({
880
+ ...options,
881
+ name,
882
+ delegationId,
883
+ grant,
884
+ failureMode,
885
+ containedFailure,
886
+ tool
887
+ });
888
+ };
889
+ function make(name, options) {
890
+ const success = options.success ?? SubagentResult(options.target.output);
891
+ const parameters = options.parameters ?? options.target.input;
892
+ const failure = options.failure ?? Schema.Never;
893
+ const inputValue = Schema.decodeUnknownEffect(Schema.toType(options.target.input));
894
+ const resultValue = Schema.decodeUnknownEffect(Schema.toType(success));
895
+ const needsApproval = options.needsApproval;
896
+ const prepareInput = options.prepareInput;
897
+ const projectResult = options.projectResult;
898
+ const projectionFailure = (stage) => SubagentProjectionFailure.make({
899
+ delegationId: decodeDelegationId(name),
900
+ stage,
901
+ message: stage === "input" ? "Delegation parameters did not satisfy the child input Schema" : "Child output did not satisfy the delegation success Schema"
902
+ });
903
+ const resolved = {
904
+ ...options,
905
+ needsApproval: typeof needsApproval === "function" ? (input, context) => needsApproval(input, context) : needsApproval,
906
+ description: options.description ?? options.target.description,
907
+ parameters,
908
+ success,
909
+ failure,
910
+ prepareInput: (input, context) => prepareInput === void 0 ? inputValue(input).pipe(Effect.mapError(() => projectionFailure("input"))) : prepareInput(input, context),
911
+ projectResult: (output, context, input) => projectResult === void 0 ? resultValue({
912
+ output,
913
+ budgetExhausted: context.budgetExhausted
914
+ }).pipe(Effect.mapError(() => projectionFailure("result"))) : projectResult(output, context, input)
915
+ };
916
+ return options.failureMode === "return" ? makeExplicit(name, {
917
+ ...resolved,
918
+ failureMode: "return"
919
+ }) : makeExplicit(name, {
920
+ ...resolved,
921
+ failureMode: "error"
922
+ });
923
+ }
924
+ /** @deprecated Use `Subagent.make`. */
925
+ const define = make;
926
+ /**
927
+ * The conservative final accounting summary the durable delegation handler
928
+ * attaches to every settlement join. The handler has no live child usage stream at durable join
929
+ * time, so every dimension conservatively consumes its full reservation and
930
+ * releases nothing — unreported usage never creates budget. The coordinator
931
+ * owns the canonical accounting decision on `SubagentJoined` and may replace
932
+ * structural dimensions from canonical child evidence; this value is opaque
933
+ * encoded policy math to the engine and to storage adapters (D8).
934
+ */
935
+ var SubagentDurableAccounting = class extends Schema.Class("@effect-agent/capabilities/SubagentDurableAccounting")({
936
+ /** The per-invocation allocation reserved at establishment. */
937
+ allocation: SubagentReservationAmounts,
938
+ /** Final consumed decision per dimension. */
939
+ consumed: SubagentReservationAmounts,
940
+ /** Amounts returned to the parent: `allocation - consumed` per dimension. */
941
+ released: SubagentReservationAmounts,
942
+ /** How the decision was computed; the handler only ever reports conservatively. */
943
+ basis: Schema.Literals(["reserved-conservative"])
944
+ }) {};
945
+ const maxEventTextLength = 4096;
946
+ const boundedEventText = (text) => text.length <= maxEventTextLength ? text : `${text.slice(0, 4095)}…`;
947
+ const ErrorMessage = Schema.Struct({ message: Schema.String });
948
+ const ErrorTag = Schema.Struct({ _tag: Schema.NonEmptyString });
949
+ const errorMessageOf = (error) => Option.match(Schema.decodeUnknownOption(ErrorMessage)(error), {
950
+ onNone: () => String(error),
951
+ onSome: ({ message }) => message
952
+ });
953
+ const errorTagOf = (error) => Option.match(Schema.decodeUnknownOption(ErrorTag)(error), {
954
+ onNone: () => "UnknownError",
955
+ onSome: ({ _tag }) => _tag
956
+ });
957
+ const boundedErrorTag = (tag) => {
958
+ const nonEmpty = tag.length === 0 ? "UnknownError" : tag;
959
+ return nonEmpty.length <= 256 ? nonEmpty : nonEmpty.slice(0, 256);
960
+ };
961
+ /**
962
+ * The coordinator's bounded projection of a failed/aborted child Settlement
963
+ * result (S2 plan §1.6, D5): `{errorTag, message}`, never a raw Cause. The
964
+ * fallback tolerates any other bounded shape without ever surfacing the raw
965
+ * value beyond a tag and message.
966
+ */
967
+ const ChildFailureProjection = Schema.Struct({
968
+ errorTag: Schema.NonEmptyString,
969
+ message: Schema.String
970
+ });
971
+ const childFailureProjectionOf = (encodedResult) => Option.match(Schema.decodeUnknownOption(ChildFailureProjection)(encodedResult), {
972
+ onNone: () => ({
973
+ errorTag: errorTagOf(encodedResult),
974
+ message: errorMessageOf(encodedResult)
975
+ }),
976
+ onSome: (projection) => projection
977
+ });
978
+ const zeroReservationAmounts = SubagentReservationAmounts.make({
979
+ turns: 0,
980
+ toolCalls: 0,
981
+ durationMillis: 0,
982
+ inputTokens: 0,
983
+ outputTokens: 0,
984
+ costMicrousd: 0,
985
+ resultBytes: 0
986
+ });
987
+ const encodeDurableAccounting = Schema.encodeEffect(SubagentDurableAccounting);
988
+ const encodeProjectionFailure = Schema.encodeEffect(SubagentProjectionFailure);
989
+ const encodeBudgetFailure = Schema.encodeEffect(SubagentBudgetExhausted);
990
+ const encodeExecutionFailure = Schema.encodeEffect(SubagentExecutionFailure);
991
+ const encodeGrant = Schema.encodeEffect(SubagentGrant);
992
+ const encodeAllocationAmounts = Schema.encodeEffect(SubagentReservationAmounts);
993
+ const toNatural = (value) => Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
994
+ const observedUsageFromDelta = (delta) => SubagentObservedUsage.make({
995
+ turns: delta.modelCalls,
996
+ toolCalls: toNatural(delta.toolCalls),
997
+ inputTokens: toNatural(delta.inputTokens),
998
+ outputTokens: toNatural(delta.outputTokens),
999
+ costMicrousd: toNatural(delta.costMicrousd)
1000
+ });
1001
+ /** A child that never started consumed nothing; observing zeros releases everything. */
1002
+ const neverStartedUsage = SubagentObservedUsage.make({
1003
+ turns: 0,
1004
+ toolCalls: 0,
1005
+ durationMillis: 0,
1006
+ inputTokens: 0,
1007
+ outputTokens: 0,
1008
+ costMicrousd: 0,
1009
+ resultBytes: 0
1010
+ });
1011
+ /**
1012
+ * Finalizer-driven settlement: observe honest final usage, then release the
1013
+ * unused allocation exactly once. Runs on every handler exit path — success,
1014
+ * declared failure, interruption, and defect — through the reservation's
1015
+ * `Effect.acquireRelease`; a missing reservation after a successful reserve
1016
+ * is a ledger invariant violation and therefore a defect.
1017
+ */
1018
+ const settleReservation = (reservations, reservationId, startedAt, conservative) => Effect.gen(function* () {
1019
+ const started = yield* Ref.get(startedAt);
1020
+ if (started === void 0) yield* reservations.observe(reservationId, neverStartedUsage);
1021
+ else {
1022
+ const now = yield* Clock.currentTimeMillis;
1023
+ yield* reservations.observe(reservationId, SubagentObservedUsage.make({ durationMillis: Math.max(0, Math.floor(now - started)) }));
1024
+ }
1025
+ if (started !== void 0 && conservative !== void 0) {
1026
+ const own = (yield* reservations.parentSnapshot(conservative.parentRunId)).reservations.find((entry) => entry.reservationId === reservationId);
1027
+ if (own === void 0) return yield* Effect.die("Missing subtree reservation during finalization");
1028
+ const additional = (key) => Math.max(0, conservative.allocation[key] - (own.observedConsumed[key] ?? 0));
1029
+ yield* reservations.observe(reservationId, SubagentObservedUsage.make({
1030
+ turns: additional("turns"),
1031
+ toolCalls: additional("toolCalls"),
1032
+ durationMillis: additional("durationMillis"),
1033
+ inputTokens: additional("inputTokens"),
1034
+ outputTokens: additional("outputTokens"),
1035
+ costMicrousd: additional("costMicrousd"),
1036
+ resultBytes: additional("resultBytes")
1037
+ }));
1038
+ }
1039
+ yield* reservations.release(reservationId);
1040
+ }).pipe(Effect.orDie);
1041
+ /**
1042
+ * Module-private provenance wrapper (SUB-033 hardening): ONLY the operations
1043
+ * that can genuinely produce the engine signals wrap them here, so
1044
+ * containment classification never trusts the runtime identity of classes an
1045
+ * author could declare in their own failure Schema — a spoofed
1046
+ * `ToolCallWaiting` in author data is contained as data, never rethrown as a
1047
+ * suspension signal.
1048
+ */
1049
+ var GenuineEngineSignal = class {
1050
+ signal;
1051
+ _tag = "GenuineEngineSignal";
1052
+ constructor(signal) {
1053
+ this.signal = signal;
1054
+ }
1055
+ };
1056
+ const wrapEngineSignal = (signal) => new GenuineEngineSignal(signal);
1057
+ /**
1058
+ * Build the Toolkit handler Layer for one delegation Tool from a model Layer or
1059
+ * an explicit child Agent Binding.
1060
+ *
1061
+ * Construction requirements carry the child Binding's full runtime needs and
1062
+ * both projections; they are captured once via `Effect.context` so the
1063
+ * per-call handler requirements stay exactly the Tool's declared engine
1064
+ * dependencies. The handler dispatches on the engine-provided per-batch
1065
+ * `SubagentDurability` service mode:
1066
+ *
1067
+ * - **ephemeral** (the explicit engine default when no durable coordinator
1068
+ * supplied `RunOptions.subagent`): the S1 path unchanged — preflight, an
1069
+ * in-process scoped child Run (SUB-011/012), stable lifecycle events,
1070
+ * total-mapped expected child failures, and Scope-finalizer reservation
1071
+ * settlement on every exit path.
1072
+ * - **durable** (S2): the same fail-closed preflight and input projection,
1073
+ * then idempotent establishment through the coordinator (spec §12 steps
1074
+ * 2-9) with construction-fixed child Binding digests, encoded grant, and
1075
+ * encoded allocation; the engine-owned waiting signal while the attached
1076
+ * child is nonterminal; and, on re-entry with a settled child, output
1077
+ * decoding, `projectResult`, and ONE atomic settlement join carrying the
1078
+ * conservative accounting summary. Failed children join as the bounded
1079
+ * `SubagentExecutionFailure`; no in-process child fiber ever starts.
1080
+ */
1081
+ const layer = (delegation, modelOrBinding, options = {}) => {
1082
+ const childBinding = "definition" in modelOrBinding ? modelOrBinding : {
1083
+ definition: delegation.target,
1084
+ model: modelOrBinding
1085
+ };
1086
+ if (childBinding.definition !== delegation.target) throw new Error("Subagent.layer requires the delegation's exact target Definition");
1087
+ const resolvePolicy = (spawner) => resolveSubagentPolicy(delegation, spawner.policy, options.parentCaps, spawner.depth === 0 && spawner.budget === void 0 ? "root-attached" : "conserved");
1088
+ const toolkit = Toolkit.make(delegation.tool);
1089
+ const contained = delegation.failureMode === "return";
1090
+ const encodeChildInput = Schema.encodeEffect(delegation.target.input);
1091
+ const encodeSuccess = Schema.encodeEffect(delegation.success);
1092
+ const decodeChildOutput = Schema.decodeUnknownEffect(delegation.target.output);
1093
+ const encodeResultProjectionFailure = Schema.encodeEffect(Schema.Union([delegation.failure, SubagentProjectionFailure]));
1094
+ const childToolCallAllowance = (parameters, policy, childPolicy) => resolveToolCallAllowance(delegation.toolCallAllowance, parameters, policy, childPolicy);
1095
+ const durableDeclaration = options.durable === void 0 ? void 0 : { targetDigests: {
1096
+ agent: options.durable.targetDigests.agent,
1097
+ model: options.durable.targetDigests.model,
1098
+ tools: options.durable.targetDigests.tools
1099
+ } };
1100
+ const executionFailure = (classification, errorTag, message, child) => SubagentExecutionFailure.make({
1101
+ delegationId: delegation.delegationId,
1102
+ targetAgentId: delegation.target.id,
1103
+ classification,
1104
+ errorTag: boundedErrorTag(errorTag),
1105
+ message: boundedEventText(message),
1106
+ ...child === void 0 ? {} : {
1107
+ childThreadId: child.childThreadId,
1108
+ childSubmissionId: child.childSubmissionId,
1109
+ childRunId: child.childRunId
1110
+ }
1111
+ });
1112
+ const prestartDenied = (reason, message) => SubagentPrestartDenied.make({
1113
+ delegationId: delegation.delegationId,
1114
+ targetAgentId: delegation.target.id,
1115
+ reason,
1116
+ message: boundedEventText(message)
1117
+ });
1118
+ const build = Effect.gen(function* () {
1119
+ const captured = yield* Effect.context();
1120
+ const invoke = Effect.fn(`SubagentRuntime.${delegation.name}`)(function* (parameters, handlerContext) {
1121
+ const spawner = yield* AgentSpawner;
1122
+ const resolved = resolvePolicy(spawner);
1123
+ const { policy, childPolicy, allocation } = resolved;
1124
+ const caps = spawner.budget === void 0 ? resolved.caps : residualSubagentCaps(resolved.caps, spawner.policy, spawner.budget, spawner.budgetScope === "worker-run");
1125
+ const sink = yield* RunEventSink;
1126
+ const reservations = yield* SubagentReservations;
1127
+ const toolCallId = yield* Schema.decodeUnknownEffect(ToolCallId)(handlerContext.toolCallId).pipe(Effect.orDie);
1128
+ const grant = narrowSubagentGrant(delegation.grant, spawner.grant);
1129
+ const depth = spawner.depth + 1;
1130
+ if (depth > grant.maxDepth) return yield* prestartDenied("nested-delegation", "Delegation exceeds the inherited depth ceiling");
1131
+ if (!(spawner.grant?.childLifetimes ?? ["attached", "background"]).includes("attached")) return yield* prestartDenied("grant-violation", "The inherited grant does not permit attached children");
1132
+ if (spawner.depth > 0 && spawner.budget === void 0) return yield* prestartDenied("budget-conflict", "Nested ephemeral delegation requires an inherited subtree reservation");
1133
+ const prepared = yield* delegation.prepareInput(parameters, {
1134
+ source: "tool",
1135
+ delegationId: delegation.delegationId,
1136
+ toolCallId,
1137
+ parent: spawner.parent
1138
+ });
1139
+ const encodedInput = yield* encodeChildInput(prepared).pipe(Effect.mapError(() => SubagentProjectionFailure.make({
1140
+ delegationId: delegation.delegationId,
1141
+ stage: "input",
1142
+ message: "Prepared child input did not satisfy the target Agent input Schema"
1143
+ })));
1144
+ const parentRunId = spawner.parent.runId;
1145
+ yield* reservations.registerParent(parentRunId, caps).pipe(Effect.catchTag("SubagentParentBudgetConflict", () => Effect.fail(prestartDenied("budget-conflict", "The parent Run is already registered with different delegation caps; supply shared parentCaps explicitly"))));
1146
+ const reservationId = makeBudgetReservationId(parentRunId, toolCallId);
1147
+ const startedAt = yield* Ref.make(void 0);
1148
+ yield* Effect.acquireRelease(reservations.reserve(SubagentReservationRequest.make({
1149
+ parentRunId,
1150
+ parentToolCallId: toolCallId,
1151
+ allocation,
1152
+ ...policy.descendantInvocations === void 0 ? {} : { descendantInvocations: policy.descendantInvocations }
1153
+ })).pipe(Effect.catchTags({
1154
+ SubagentReservationConflict: (conflict) => Effect.die(conflict),
1155
+ SubagentParentBudgetUnknown: (unknown) => Effect.die(unknown)
1156
+ })), () => settleReservation(reservations, reservationId, startedAt, (policy.descendantInvocations ?? 0) > 0 ? {
1157
+ parentRunId,
1158
+ allocation
1159
+ } : void 0));
1160
+ yield* reservations.acquireChildSlot(parentRunId, 1 + (policy.descendantInvocations ?? 0)).pipe(Effect.catchTag("SubagentParentBudgetUnknown", (unknown) => Effect.die(unknown)));
1161
+ const seededChild = options.child;
1162
+ const seededBudget = seededChild?.budget;
1163
+ const budget = {
1164
+ guard: seededBudget === void 0 ? (effect) => effect : (effect) => seededBudget.guard(effect),
1165
+ consume: (delta) => reservations.observe(reservationId, observedUsageFromDelta(delta)).pipe(Effect.orDie, Effect.andThen(seededBudget === void 0 ? Effect.void : seededBudget.consume(delta)))
1166
+ };
1167
+ const toolCallAllowance = childToolCallAllowance(parameters, policy, childPolicy);
1168
+ const childOptions = {
1169
+ ...seededChild,
1170
+ subagentGrant: grant,
1171
+ delegationDepth: depth,
1172
+ subagentBudget: SubagentBudgetReservation.make({
1173
+ caps,
1174
+ allocation,
1175
+ ...policy.descendantInvocations === void 0 ? {} : { descendantInvocations: policy.descendantInvocations }
1176
+ }),
1177
+ budget,
1178
+ ...toolCallAllowance === void 0 ? {} : { toolCallAllowance }
1179
+ };
1180
+ yield* Ref.set(startedAt, yield* Clock.currentTimeMillis);
1181
+ const childScope = yield* Scope.make();
1182
+ yield* Effect.addFinalizer((exit) => Scope.close(childScope, exit));
1183
+ const child = yield* spawner.spawn({
1184
+ ...childBinding,
1185
+ definition: {
1186
+ ...childBinding.definition,
1187
+ policy: childPolicy
1188
+ }
1189
+ }, encodedInput, {
1190
+ delegationId: delegation.delegationId,
1191
+ parentToolCallId: toolCallId
1192
+ }, childOptions).pipe(Scope.provide(childScope));
1193
+ const payload = {
1194
+ toolCallId,
1195
+ delegationId: delegation.delegationId,
1196
+ childThreadId: child.threadId,
1197
+ childRunId: child.runId,
1198
+ targetAgentId: delegation.target.id,
1199
+ depth: child.parentLink.depth
1200
+ };
1201
+ const emit = (event) => sink.emit(event).pipe(Effect.orDie);
1202
+ yield* emit({
1203
+ _tag: "SubagentRequested",
1204
+ ...payload
1205
+ });
1206
+ yield* emit({
1207
+ _tag: "SubagentStarted",
1208
+ ...payload
1209
+ });
1210
+ return yield* Effect.gen(function* () {
1211
+ const result = yield* child.await.pipe(Effect.catch((childFailure) => child.usageReport.pipe(Effect.flatMap((report) => emit({
1212
+ _tag: "SubagentFailed",
1213
+ ...payload,
1214
+ ...report,
1215
+ errorTag: errorTagOf(childFailure),
1216
+ message: boundedEventText(errorMessageOf(childFailure))
1217
+ })), Effect.andThen(Effect.fail(options.mapChildFailure === void 0 ? executionFailure("child-failed", errorTagOf(childFailure), "The child Run failed") : options.mapChildFailure(childFailure))))), Effect.timeoutOrElse({
1218
+ duration: Duration.millis(allocation.durationMillis),
1219
+ orElse: () => Effect.succeed(void 0)
1220
+ }), Effect.tapCause((cause) => Cause.hasDies(cause) ? child.usageReport.pipe(Effect.flatMap((report) => emit({
1221
+ _tag: "SubagentFailed",
1222
+ ...payload,
1223
+ ...report,
1224
+ errorTag: "Defect",
1225
+ message: "The child Run ended with a defect"
1226
+ })), Effect.ignore) : Effect.void));
1227
+ if (result === void 0) {
1228
+ yield* Scope.close(childScope, Exit.void);
1229
+ const report = yield* child.usageReport;
1230
+ yield* emit({
1231
+ _tag: "SubagentFailed",
1232
+ ...payload,
1233
+ ...report,
1234
+ errorTag: "SubagentBudgetExhausted",
1235
+ message: `Attached child exceeded its ${allocation.durationMillis}ms delegation duration budget`
1236
+ });
1237
+ return yield* SubagentBudgetExhausted.make({
1238
+ parentRunId,
1239
+ dimension: "duration",
1240
+ limitValue: allocation.durationMillis,
1241
+ observedValue: allocation.durationMillis
1242
+ });
1243
+ }
1244
+ const report = yield* child.usageReport;
1245
+ yield* emit({
1246
+ _tag: "SubagentCompleted",
1247
+ ...payload,
1248
+ ...report,
1249
+ turns: result.turns,
1250
+ finishReason: result.finishReason,
1251
+ ...result.exhausted !== void 0 ? { exhausted: result.exhausted } : {}
1252
+ });
1253
+ const projected = yield* delegation.projectResult(result.output, {
1254
+ budgetExhausted: result.finishReason === "budget-exhausted",
1255
+ ...report
1256
+ }, parameters);
1257
+ const encodedResult = yield* encodeSuccess(projected).pipe(Effect.mapError(() => SubagentProjectionFailure.make({
1258
+ delegationId: delegation.delegationId,
1259
+ stage: "result",
1260
+ message: "Projected child result did not satisfy the delegation success Schema"
1261
+ })));
1262
+ const resultBytes = utf8ByteLength(JSON.stringify(encodedResult) ?? "");
1263
+ yield* reservations.observe(reservationId, SubagentObservedUsage.make({ resultBytes })).pipe(Effect.orDie);
1264
+ if (policy.maxResultBytes !== void 0 && resultBytes > policy.maxResultBytes) {
1265
+ yield* emit({
1266
+ _tag: "SubagentFailed",
1267
+ ...payload,
1268
+ ...report,
1269
+ errorTag: "SubagentBudgetExhausted",
1270
+ message: `Projected child result of ${resultBytes} bytes exceeds the ${policy.maxResultBytes}-byte delegation budget`
1271
+ });
1272
+ return yield* SubagentBudgetExhausted.make({
1273
+ parentRunId,
1274
+ dimension: "result-bytes",
1275
+ limitValue: policy.maxResultBytes,
1276
+ observedValue: resultBytes
1277
+ });
1278
+ }
1279
+ yield* emit({
1280
+ _tag: "SubagentJoined",
1281
+ ...payload,
1282
+ ...report
1283
+ });
1284
+ return projected;
1285
+ }).pipe(Effect.onInterrupt(() => Scope.close(childScope, Exit.void).pipe(Effect.andThen(child.usageReport), Effect.flatMap((report) => sink.emit({
1286
+ _tag: "SubagentInterrupted",
1287
+ ...payload,
1288
+ ...report,
1289
+ reason: "Parent Run interrupted the attached child before it settled"
1290
+ })), Effect.ignore)));
1291
+ });
1292
+ /**
1293
+ * Durable branch: establishment through the
1294
+ * coordinator's idempotent protocol instead of an in-process spawn. No
1295
+ * child fiber ever starts here, and the S1 in-memory reservation service
1296
+ * is deliberately not consulted — its Scope-finalizer settlement
1297
+ * contradicts a handler that exits with the waiting signal while the
1298
+ * child keeps running; durable budget lives in the coordinator's fenced
1299
+ * ledger reservation built from `encodedAllocation`.
1300
+ */
1301
+ const invokeDurable = Effect.fn(`SubagentRuntime.${delegation.name}.durable`)(function* (parameters, handlerContext, durability) {
1302
+ const spawner = yield* AgentSpawner;
1303
+ const { policy, childPolicy, allocation, caps } = resolvePolicy(spawner);
1304
+ const encodedAllocation = yield* encodeAllocationAmounts(allocation).pipe(Effect.orDie);
1305
+ const conservativeAccounting = yield* encodeDurableAccounting(SubagentDurableAccounting.make({
1306
+ allocation,
1307
+ consumed: allocation,
1308
+ released: zeroReservationAmounts,
1309
+ basis: "reserved-conservative"
1310
+ })).pipe(Effect.orDie);
1311
+ const sink = yield* RunEventSink;
1312
+ const toolCallId = yield* Schema.decodeUnknownEffect(ToolCallId)(handlerContext.toolCallId).pipe(Effect.orDie);
1313
+ const emit = (event) => sink.emit(event).pipe(Effect.orDie);
1314
+ const grant = narrowSubagentGrant(delegation.grant, spawner.grant);
1315
+ const depth = spawner.depth + 1;
1316
+ if (depth > grant.maxDepth) return yield* prestartDenied("nested-delegation", "Delegation exceeds the inherited depth ceiling");
1317
+ if (!(spawner.grant?.childLifetimes ?? ["attached", "background"]).includes("attached")) return yield* prestartDenied("grant-violation", "The inherited grant does not permit attached children");
1318
+ const encodedGrant = yield* encodeGrant(grant).pipe(Effect.orDie);
1319
+ const prepared = yield* delegation.prepareInput(parameters, {
1320
+ source: "tool",
1321
+ delegationId: delegation.delegationId,
1322
+ toolCallId,
1323
+ parent: spawner.parent
1324
+ });
1325
+ const encodedInput = yield* encodeChildInput(prepared).pipe(Effect.mapError(() => SubagentProjectionFailure.make({
1326
+ delegationId: delegation.delegationId,
1327
+ stage: "input",
1328
+ message: "Prepared child input did not satisfy the target Agent input Schema"
1329
+ })));
1330
+ const status = yield* Effect.mapError(wrapEngineSignal)(durability.establish({
1331
+ toolCallId,
1332
+ delegationId: delegation.delegationId,
1333
+ target: delegation.target,
1334
+ targetAgentId: delegation.target.id,
1335
+ depth,
1336
+ ...durableDeclaration === void 0 ? {} : { targetDigests: durableDeclaration.targetDigests },
1337
+ encodedChildInput: encodedInput,
1338
+ encodedGrant,
1339
+ encodedAllocation,
1340
+ toolCallAllowance: childToolCallAllowance(parameters, policy, childPolicy),
1341
+ policy: childPolicy,
1342
+ budget: {
1343
+ caps,
1344
+ allocation,
1345
+ ...policy.descendantInvocations === void 0 ? {} : { descendantInvocations: policy.descendantInvocations }
1346
+ }
1347
+ }));
1348
+ switch (status._tag) {
1349
+ case "denied": return yield* executionFailure("establishment-denied", status.errorTag, status.message);
1350
+ case "waiting": {
1351
+ const payload = {
1352
+ toolCallId,
1353
+ delegationId: delegation.delegationId,
1354
+ childThreadId: status.childThreadId,
1355
+ childRunId: status.childRunId,
1356
+ targetAgentId: delegation.target.id,
1357
+ depth
1358
+ };
1359
+ yield* emit({
1360
+ _tag: "SubagentRequested",
1361
+ ...payload
1362
+ });
1363
+ yield* emit({
1364
+ _tag: "SubagentStarted",
1365
+ ...payload
1366
+ });
1367
+ return yield* Effect.mapError(wrapEngineSignal)(durability.waiting(toolCallId, status));
1368
+ }
1369
+ case "settled": {
1370
+ const payload = {
1371
+ toolCallId,
1372
+ delegationId: delegation.delegationId,
1373
+ childThreadId: status.childThreadId,
1374
+ childRunId: status.childRunId,
1375
+ targetAgentId: delegation.target.id,
1376
+ depth
1377
+ };
1378
+ const report = RunUsageReport.make({
1379
+ usage: status.usage ?? unknownRunTotals(),
1380
+ delegatedUsage: status.delegatedUsage ?? unknownRunTotals()
1381
+ });
1382
+ const settleFailure = (failure, encodedFailure) => emit({
1383
+ _tag: "SubagentFailed",
1384
+ ...payload,
1385
+ ...report,
1386
+ errorTag: errorTagOf(failure),
1387
+ message: boundedEventText(errorMessageOf(failure))
1388
+ }).pipe(Effect.andThen(Effect.mapError(wrapEngineSignal)(durability.join({
1389
+ toolCallId,
1390
+ encodedResult: encodedFailure,
1391
+ isFailure: !contained,
1392
+ encodedAccounting: conservativeAccounting
1393
+ }))), Effect.andThen(Effect.fail(failure)));
1394
+ if (status.outcome !== "completed") {
1395
+ const projection = childFailureProjectionOf(status.encodedResult);
1396
+ const failure = executionFailure(status.outcome === "aborted" ? "child-aborted" : projection.errorTag === "ChildCompatibilityFailure" ? "child-compatibility" : "child-failed", projection.errorTag, projection.message, status);
1397
+ return yield* settleFailure(failure, yield* encodeExecutionFailure(failure).pipe(Effect.orDie));
1398
+ }
1399
+ const decoded = yield* decodeChildOutput(status.encodedResult).pipe(Effect.catch(() => {
1400
+ const failure = SubagentProjectionFailure.make({
1401
+ delegationId: delegation.delegationId,
1402
+ stage: "result",
1403
+ message: "Settled child output did not satisfy the target Agent output Schema"
1404
+ });
1405
+ return encodeProjectionFailure(failure).pipe(Effect.orDie, Effect.flatMap((encodedFailure) => settleFailure(failure, encodedFailure)));
1406
+ }));
1407
+ const projected = yield* delegation.projectResult(decoded, {
1408
+ budgetExhausted: status.finishReason === "budget-exhausted",
1409
+ ...report
1410
+ }, parameters).pipe(Effect.catch((declared) => encodeResultProjectionFailure(declared).pipe(Effect.orDie, Effect.flatMap((encodedFailure) => settleFailure(declared, encodedFailure)))));
1411
+ const encodedResult = yield* encodeSuccess(projected).pipe(Effect.catch(() => {
1412
+ const failure = SubagentProjectionFailure.make({
1413
+ delegationId: delegation.delegationId,
1414
+ stage: "result",
1415
+ message: "Projected child result did not satisfy the delegation success Schema"
1416
+ });
1417
+ return encodeProjectionFailure(failure).pipe(Effect.orDie, Effect.flatMap((encodedFailure) => settleFailure(failure, encodedFailure)));
1418
+ }));
1419
+ const resultBytes = utf8ByteLength(JSON.stringify(encodedResult) ?? "");
1420
+ if (policy.maxResultBytes !== void 0 && resultBytes > policy.maxResultBytes) {
1421
+ const failure = SubagentBudgetExhausted.make({
1422
+ parentRunId: spawner.parent.runId,
1423
+ dimension: "result-bytes",
1424
+ limitValue: policy.maxResultBytes,
1425
+ observedValue: resultBytes
1426
+ });
1427
+ return yield* settleFailure(failure, yield* encodeBudgetFailure(failure).pipe(Effect.orDie));
1428
+ }
1429
+ yield* Effect.mapError(wrapEngineSignal)(durability.join({
1430
+ toolCallId,
1431
+ encodedResult,
1432
+ isFailure: false,
1433
+ encodedAccounting: conservativeAccounting
1434
+ }));
1435
+ yield* emit({
1436
+ _tag: "SubagentJoined",
1437
+ ...payload,
1438
+ ...report
1439
+ });
1440
+ return projected;
1441
+ }
1442
+ }
1443
+ });
1444
+ const containSignals = (failure) => failure instanceof GenuineEngineSignal ? Effect.fail(failure.signal) : Effect.succeed(failure);
1445
+ const unwrapSignals = (failure) => failure instanceof GenuineEngineSignal ? failure.signal : failure;
1446
+ const handlerImpl = (parameters, handlerContext) => Effect.gen(function* () {
1447
+ const spawner = yield* AgentSpawner;
1448
+ const sink = yield* RunEventSink;
1449
+ const durability = yield* SubagentDurability;
1450
+ if (durability.mode === "durable") {
1451
+ const durable = invokeDurable(parameters, handlerContext, durability).pipe(Effect.scoped, Effect.provideService(AgentSpawner, spawner), Effect.provideService(RunEventSink, sink), Effect.provideService(SubagentDurability, durability), Effect.provide(captured));
1452
+ return yield* contained ? durable.pipe(Effect.catch(containSignals)) : durable.pipe(Effect.mapError(unwrapSignals));
1453
+ }
1454
+ const ephemeral = invoke(parameters, handlerContext).pipe(Effect.scoped, Effect.provideService(AgentSpawner, spawner), Effect.provideService(RunEventSink, sink), Effect.provideService(SubagentDurability, durability), Effect.provide(captured));
1455
+ return yield* contained ? ephemeral.pipe(Effect.catch(containSignals)) : ephemeral.pipe(Effect.mapError(unwrapSignals));
1456
+ });
1457
+ const handler = handlerImpl;
1458
+ return { [delegation.name]: handler };
1459
+ });
1460
+ return toolkit.toLayer(build);
1461
+ };
1462
+ function background(targetOrDeclaration, selected) {
1463
+ const declaration = "target" in targetOrDeclaration ? targetOrDeclaration : make(targetOrDeclaration.id, { target: targetOrDeclaration });
1464
+ return background$1(declaration, selected);
1465
+ }
1466
+ //#endregion
1467
+ export { delegationCapsFromPolicy as C, delegationAllocationFromPolicy as S, reporting as _, define as a, SubagentPrestartDenied as b, Worker as c, cancel as d, followUp as f, start as g, observe as h, background as i, WorkerObservation as l, list as m, SubagentResult as n, layer as o, inspect as p, Subagent_exports as r, make as s, SubagentDurableAccounting as t, awaitWorker as u, reportingToWorker as v, SubagentProjectionFailure as x, SubagentPolicy as y };
1468
+
1469
+ //# sourceMappingURL=Subagent-Cy_hU1tv.mjs.map