@yielded/agent 0.1.0-beta.173 → 0.1.0-beta.175

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 (266) hide show
  1. package/dist/{Admin-BX9ns28E.d.mts → Admin-Qa3I1oA5.d.mts} +61 -21
  2. package/dist/{Agent-9aBoIi74.d.mts → Agent-B39jRnFv.d.mts} +2 -2
  3. package/dist/{Agent-0WvBWWbM.mjs → Agent-BiRbr73L.mjs} +7 -6
  4. package/dist/Agent-BiRbr73L.mjs.map +1 -0
  5. package/dist/{AgentRuntime-BfP14534.d.mts → AgentRuntime-CHDyRbSf.d.mts} +12 -12
  6. package/dist/{AgentRuntime-CQ-qcETl.mjs → AgentRuntime-DaDKMasp.mjs} +290 -273
  7. package/dist/AgentRuntime-DaDKMasp.mjs.map +1 -0
  8. package/dist/{Digest-DCuPlhNk.mjs → Digest-C3EODOee.mjs} +42 -15
  9. package/dist/Digest-C3EODOee.mjs.map +1 -0
  10. package/dist/{DurableAgentRuntime-BAmSkWYr.mjs → DurableAgentRuntime-CPlw5_7e.mjs} +1557 -1458
  11. package/dist/DurableAgentRuntime-CPlw5_7e.mjs.map +1 -0
  12. package/dist/{EventSource-BwliwQz9.d.mts → EventSource-BTu68yDW.d.mts} +2 -2
  13. package/dist/InMemory.d.mts +2 -2
  14. package/dist/{MessageDelivery-B943ebI_.d.mts → MessageDelivery-DjAZJ4Fd.d.mts} +42 -42
  15. package/dist/{Messaging-C_6OOg_s.d.mts → Messaging-SVu6rWV8.d.mts} +12 -6
  16. package/dist/{MessagingHost-B8oKM7AC.d.mts → MessagingHost-C6SOAcoG.d.mts} +2 -2
  17. package/dist/{MessagingHost-CRUK4JBi.mjs → MessagingHost-CZCyrnvJ.mjs} +27 -26
  18. package/dist/MessagingHost-CZCyrnvJ.mjs.map +1 -0
  19. package/dist/{Output-Dsx6k52t.d.mts → Output-CRamN1Fy.d.mts} +2 -2
  20. package/dist/{PreparedInputAdmission-CxSJSiTl.d.mts → PreparedInputAdmission-wgY4JMZY.d.mts} +3 -3
  21. package/dist/{Records-BiuJDWNe.mjs → Records-DzL4Kbtw.mjs} +2 -2
  22. package/dist/{Records-BiuJDWNe.mjs.map → Records-DzL4Kbtw.mjs.map} +1 -1
  23. package/dist/{RunContinuation-FHM7XPjq.d.mts → RunContinuation-3jB5pULC.d.mts} +13 -7
  24. package/dist/{RunContinuation-DHYNAQFi.mjs → RunContinuation-BiyKJK32.mjs} +173 -82
  25. package/dist/RunContinuation-BiyKJK32.mjs.map +1 -0
  26. package/dist/{RunJournal-kfKVxJj7.mjs → RunJournal-CPMKcfd0.mjs} +106 -73
  27. package/dist/RunJournal-CPMKcfd0.mjs.map +1 -0
  28. package/dist/{RunOptions-D8zxFIrZ.d.mts → RunOptions-Be77lKVZ.d.mts} +2 -2
  29. package/dist/{RunStorage-uqPxps09.mjs → RunStorage-CzutHJBE.mjs} +10 -6
  30. package/dist/RunStorage-CzutHJBE.mjs.map +1 -0
  31. package/dist/{Scheduling-CVyfXlBR.mjs → Scheduling-07_dsGED.mjs} +12 -12
  32. package/dist/Scheduling-07_dsGED.mjs.map +1 -0
  33. package/dist/{Subagent-vpffemql.mjs → Subagent-CexndZSp.mjs} +53 -40
  34. package/dist/Subagent-CexndZSp.mjs.map +1 -0
  35. package/dist/{Subagent-E6tvd7-k.d.mts → Subagent-xhN_aD1r.d.mts} +20 -9
  36. package/dist/{SubagentHost-B6w2m-SI.d.mts → SubagentHost-D1xBgn9g.d.mts} +2 -2
  37. package/dist/{Subscription-DONig54Q.d.mts → Subscription-DmIHlOJK.d.mts} +2 -2
  38. package/dist/{SubscriptionInput-mJIRxWJM.d.mts → SubscriptionInput-DgcQhvbe.d.mts} +2 -2
  39. package/dist/{Thread-dk-QiNml.d.mts → Thread-DzdJAY4J.d.mts} +4 -3
  40. package/dist/{ThreadHistory-ByxS8HU1.d.mts → ThreadHistory-KPPBJLJb.d.mts} +12 -2
  41. package/dist/{ThreadImport-DckUMEqJ.mjs → ThreadImport-CjlG57vH.mjs} +9 -9
  42. package/dist/ThreadImport-CjlG57vH.mjs.map +1 -0
  43. package/dist/{ThreadImport-DpHxjBrA.d.mts → ThreadImport-DP-vOk2F.d.mts} +5 -5
  44. package/dist/{ThreadStore-CEekRa80.mjs → ThreadStore-EuUilthA.mjs} +162 -85
  45. package/dist/ThreadStore-EuUilthA.mjs.map +1 -0
  46. package/dist/{ThreadTransfer-B4gTQLIl.mjs → ThreadTransfer-DB_zsrtJ.mjs} +4 -4
  47. package/dist/{ThreadTransfer-B4gTQLIl.mjs.map → ThreadTransfer-DB_zsrtJ.mjs.map} +1 -1
  48. package/dist/{WorkerAdmission-DFVbbVh2.mjs → WorkerAdmission-eBeXt_mu.mjs} +5 -5
  49. package/dist/{WorkerAdmission-DFVbbVh2.mjs.map → WorkerAdmission-eBeXt_mu.mjs.map} +1 -1
  50. package/dist/{agent-registration-ByMZ_cK5.mjs → agent-registration-a6QYaG3h.mjs} +70 -57
  51. package/dist/agent-registration-a6QYaG3h.mjs.map +1 -0
  52. package/dist/capabilities/Approval.mjs +2 -2
  53. package/dist/capabilities/Approval.mjs.map +1 -1
  54. package/dist/capabilities/BrowserUse.d.mts +102 -1867
  55. package/dist/capabilities/BrowserUse.mjs +74 -798
  56. package/dist/capabilities/BrowserUse.mjs.map +1 -1
  57. package/dist/capabilities/Budget.mjs +3 -1
  58. package/dist/capabilities/Budget.mjs.map +1 -1
  59. package/dist/capabilities/CodeMode.d.mts +1 -1
  60. package/dist/capabilities/CodeMode.mjs +16 -9
  61. package/dist/capabilities/CodeMode.mjs.map +1 -1
  62. package/dist/capabilities/Commands.d.mts +1 -1
  63. package/dist/capabilities/McpClient.mjs +1 -1
  64. package/dist/capabilities/McpClient.mjs.map +1 -1
  65. package/dist/capabilities/Messaging.d.mts +1 -1
  66. package/dist/capabilities/Messaging.mjs +5 -5
  67. package/dist/capabilities/Messaging.mjs.map +1 -1
  68. package/dist/capabilities/ModelContext.d.mts +1 -1
  69. package/dist/capabilities/ModelContext.mjs +7 -5
  70. package/dist/capabilities/ModelContext.mjs.map +1 -1
  71. package/dist/capabilities/Redaction.mjs +49 -19
  72. package/dist/capabilities/Redaction.mjs.map +1 -1
  73. package/dist/capabilities/RunHooks.d.mts +2 -2
  74. package/dist/capabilities/RunHooks.mjs +1 -1
  75. package/dist/capabilities/RunHooks.mjs.map +1 -1
  76. package/dist/capabilities/Subagent.d.mts +1 -1
  77. package/dist/capabilities/Subagent.mjs +1 -1
  78. package/dist/capabilities/SubagentReservations.mjs +3 -1
  79. package/dist/capabilities/SubagentReservations.mjs.map +1 -1
  80. package/dist/capabilities/WebCapture.mjs.map +1 -1
  81. package/dist/capabilities/WebSearch.mjs +7 -7
  82. package/dist/capabilities/WebSearch.mjs.map +1 -1
  83. package/dist/core/Agent.d.mts +1 -1
  84. package/dist/core/Agent.mjs +1 -1
  85. package/dist/core/AgentUpdates.mjs +8 -8
  86. package/dist/core/AgentUpdates.mjs.map +1 -1
  87. package/dist/core/Thread.d.mts +2 -2
  88. package/dist/core/Thread.mjs +6 -4
  89. package/dist/core/Thread.mjs.map +1 -1
  90. package/dist/core/Usage.mjs +2 -2
  91. package/dist/core/Usage.mjs.map +1 -1
  92. package/dist/durable/ActivityStore.mjs +1 -1
  93. package/dist/durable/Admin.d.mts +1 -1
  94. package/dist/durable/Admin.mjs +1 -1
  95. package/dist/durable/AgentRegistration.d.mts +1 -1
  96. package/dist/durable/AgentRegistration.mjs +1 -1
  97. package/dist/durable/Certification.d.mts +1 -1
  98. package/dist/durable/CommittedActivity.d.mts +1 -1
  99. package/dist/durable/CommittedActivity.mjs +3 -3
  100. package/dist/durable/Digest.mjs +1 -1
  101. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  102. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  103. package/dist/durable/EventSource.d.mts +1 -1
  104. package/dist/durable/EventSource.mjs +7 -7
  105. package/dist/durable/EventSource.mjs.map +1 -1
  106. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  107. package/dist/durable/LifecyclePublication.d.mts +1 -1
  108. package/dist/durable/LifecyclePublication.mjs +2 -2
  109. package/dist/durable/MessageDelivery.d.mts +1 -1
  110. package/dist/durable/MessageDelivery.mjs +2 -2
  111. package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
  112. package/dist/durable/MessageDeliveryStoreConformance.mjs +2 -2
  113. package/dist/durable/PersistentHistory.d.mts +2 -2
  114. package/dist/durable/PersistentHistory.mjs +4 -4
  115. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  116. package/dist/durable/RecordFormat.mjs +3 -3
  117. package/dist/durable/RecordFormat.mjs.map +1 -1
  118. package/dist/durable/Records.mjs +1 -1
  119. package/dist/durable/Recovery.d.mts +1 -1
  120. package/dist/durable/Recovery.mjs +1 -1
  121. package/dist/durable/RunContinuation.d.mts +2 -2
  122. package/dist/durable/RunContinuation.mjs +3 -3
  123. package/dist/durable/RunJournal.d.mts +2 -2
  124. package/dist/durable/RunJournal.mjs +2 -2
  125. package/dist/durable/RunStorage.d.mts +1 -1
  126. package/dist/durable/RunStorage.mjs +1 -1
  127. package/dist/durable/Schedule.mjs +1 -1
  128. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  129. package/dist/durable/ScheduleTransition.mjs +1 -1
  130. package/dist/durable/Scheduling.d.mts +1 -1
  131. package/dist/durable/Scheduling.mjs +1 -1
  132. package/dist/durable/SettlementPublisher.d.mts +1 -1
  133. package/dist/durable/SettlementPublisher.mjs +3 -3
  134. package/dist/durable/SqlMemoryStore.mjs +5 -3
  135. package/dist/durable/SqlMemoryStore.mjs.map +1 -1
  136. package/dist/durable/SubmissionLedger.d.mts +1 -1
  137. package/dist/durable/SubmissionLedger.mjs +11 -3
  138. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  139. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  140. package/dist/durable/SubmissionLedgerConformance.mjs +6 -6
  141. package/dist/durable/SubmissionStatus.d.mts +1 -1
  142. package/dist/durable/Subscription.d.mts +1 -1
  143. package/dist/durable/Subscription.mjs +2 -2
  144. package/dist/durable/SubscriptionInput.d.mts +1 -1
  145. package/dist/durable/SubscriptionInput.mjs +4 -4
  146. package/dist/durable/SubscriptionInput.mjs.map +1 -1
  147. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  148. package/dist/durable/SubscriptionStoreConformance.mjs +3 -3
  149. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -1
  150. package/dist/durable/SubscriptionTools.d.mts +2 -2
  151. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  152. package/dist/durable/SubscriptionTransition.mjs +1 -1
  153. package/dist/durable/Subscriptions.d.mts +5 -5
  154. package/dist/durable/Subscriptions.mjs +3 -3
  155. package/dist/durable/Subscriptions.mjs.map +1 -1
  156. package/dist/durable/ThreadArchiveRange.d.mts +1 -1
  157. package/dist/durable/ThreadArchiveRange.mjs +1 -1
  158. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  159. package/dist/durable/ThreadContextHistory.mjs +2 -2
  160. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  161. package/dist/durable/ThreadImport.d.mts +1 -1
  162. package/dist/durable/ThreadImport.mjs +1 -1
  163. package/dist/durable/ThreadInvariants.d.mts +3 -3
  164. package/dist/durable/ThreadInvariants.mjs +5 -5
  165. package/dist/durable/ThreadInvariants.mjs.map +1 -1
  166. package/dist/durable/ThreadProjection.mjs +1 -1
  167. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  168. package/dist/durable/ThreadReader.d.mts +1 -1
  169. package/dist/durable/ThreadReader.mjs +1 -1
  170. package/dist/durable/ThreadStore.d.mts +1 -1
  171. package/dist/durable/ThreadStore.mjs +2 -2
  172. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  173. package/dist/durable/ThreadStoreConformance.mjs +4 -4
  174. package/dist/durable/ThreadTransfer.d.mts +1 -1
  175. package/dist/durable/ThreadTransfer.mjs +1 -1
  176. package/dist/durable/ThreadWork.d.mts +2 -2
  177. package/dist/durable/ThreadWork.mjs +12 -6
  178. package/dist/durable/ThreadWork.mjs.map +1 -1
  179. package/dist/durable/ToolReconciler.mjs +1 -1
  180. package/dist/durable/WakeScheduler.mjs +23 -39
  181. package/dist/durable/WakeScheduler.mjs.map +1 -1
  182. package/dist/durable/WorkerAdmission.d.mts +1 -1
  183. package/dist/durable/WorkerAdmission.mjs +1 -1
  184. package/dist/durable/WorkerHost.d.mts +2 -2
  185. package/dist/engine/AgentRuntime.d.mts +1 -1
  186. package/dist/engine/AgentRuntime.mjs +1 -1
  187. package/dist/engine/MessagingHost.d.mts +1 -1
  188. package/dist/engine/MessagingHost.mjs +1 -1
  189. package/dist/engine/Output.d.mts +1 -1
  190. package/dist/engine/Output.mjs +1 -1
  191. package/dist/engine/RunOptions.d.mts +1 -1
  192. package/dist/engine/SubagentHost.d.mts +1 -1
  193. package/dist/engine/ThreadHistory.d.mts +1 -1
  194. package/dist/engine/ThreadHistory.mjs +3 -2
  195. package/dist/engine/ThreadHistory.mjs.map +1 -1
  196. package/dist/index.d.mts +21 -21
  197. package/dist/index.mjs +16 -16
  198. package/dist/{output-contract-CMIhu4Cw.mjs → output-contract-DCnLYCdp.mjs} +12 -15
  199. package/dist/{output-contract-CMIhu4Cw.mjs.map → output-contract-DCnLYCdp.mjs.map} +1 -1
  200. package/dist/{run-context-reader-OcsZr4bk.d.mts → run-context-reader-DVhJZ1Qe.d.mts} +2 -2
  201. package/package.json +1 -1
  202. package/src/capabilities/Approval.ts +58 -60
  203. package/src/capabilities/BrowserUse.ts +89 -944
  204. package/src/capabilities/Budget.ts +8 -1
  205. package/src/capabilities/CodeMode.ts +57 -33
  206. package/src/capabilities/McpClient.ts +2 -2
  207. package/src/capabilities/Messaging.ts +51 -55
  208. package/src/capabilities/ModelContext.ts +5 -2
  209. package/src/capabilities/Redaction.ts +64 -34
  210. package/src/capabilities/RunHooks.ts +52 -55
  211. package/src/capabilities/Subagent.ts +33 -33
  212. package/src/capabilities/SubagentReservations.ts +9 -1
  213. package/src/capabilities/WebCapture.ts +6 -0
  214. package/src/capabilities/WebSearch.ts +10 -7
  215. package/src/capabilities/internal/subagent-background.ts +202 -158
  216. package/src/core/Agent.ts +11 -6
  217. package/src/core/AgentUpdates.ts +8 -8
  218. package/src/core/Thread.ts +142 -146
  219. package/src/core/Usage.ts +7 -8
  220. package/src/core/internal/agent-updates.ts +1 -0
  221. package/src/durable/DurableAgentRuntime.ts +1024 -829
  222. package/src/durable/EventSource.ts +15 -9
  223. package/src/durable/RecordFormat.ts +5 -3
  224. package/src/durable/RunContinuation.ts +316 -113
  225. package/src/durable/RunJournal.ts +106 -114
  226. package/src/durable/RunStorage.ts +129 -124
  227. package/src/durable/Scheduling.ts +639 -651
  228. package/src/durable/SqlMemoryStore.ts +8 -6
  229. package/src/durable/SubmissionLedger.ts +11 -0
  230. package/src/durable/SubscriptionInput.ts +5 -3
  231. package/src/durable/SubscriptionStoreConformance.ts +23 -23
  232. package/src/durable/Subscriptions.ts +18 -19
  233. package/src/durable/ThreadImport.ts +18 -19
  234. package/src/durable/ThreadInvariants.ts +2 -1
  235. package/src/durable/ThreadStore.ts +217 -111
  236. package/src/durable/ThreadWork.ts +11 -2
  237. package/src/durable/WakeScheduler.ts +34 -66
  238. package/src/durable/internal/StorageOwner.ts +10 -4
  239. package/src/durable/internal/agent-registration.ts +96 -89
  240. package/src/durable/internal/canonical-json.ts +61 -20
  241. package/src/durable/internal/prompt-history-cache.ts +13 -4
  242. package/src/durable/internal/record-encoding.ts +120 -64
  243. package/src/durable/internal/schedule-time.ts +6 -6
  244. package/src/durable/internal/usage-totals.ts +35 -0
  245. package/src/durable/internal/worker-host.ts +69 -74
  246. package/src/engine/MessagingHost.ts +4 -2
  247. package/src/engine/ThreadHistory.ts +47 -48
  248. package/src/engine/internal/agent-runtime.ts +1298 -1217
  249. package/src/engine/internal/output-contract.ts +15 -15
  250. package/src/engine/internal/primitive-delta.ts +2 -3
  251. package/src/engine/internal/provisional-text.ts +12 -10
  252. package/src/engine/internal/tool-exposure.ts +22 -18
  253. package/src/engine/internal/tool-telemetry.ts +15 -12
  254. package/dist/Agent-0WvBWWbM.mjs.map +0 -1
  255. package/dist/AgentRuntime-CQ-qcETl.mjs.map +0 -1
  256. package/dist/Digest-DCuPlhNk.mjs.map +0 -1
  257. package/dist/DurableAgentRuntime-BAmSkWYr.mjs.map +0 -1
  258. package/dist/MessagingHost-CRUK4JBi.mjs.map +0 -1
  259. package/dist/RunContinuation-DHYNAQFi.mjs.map +0 -1
  260. package/dist/RunJournal-kfKVxJj7.mjs.map +0 -1
  261. package/dist/RunStorage-uqPxps09.mjs.map +0 -1
  262. package/dist/Scheduling-CVyfXlBR.mjs.map +0 -1
  263. package/dist/Subagent-vpffemql.mjs.map +0 -1
  264. package/dist/ThreadImport-DckUMEqJ.mjs.map +0 -1
  265. package/dist/ThreadStore-CEekRa80.mjs.map +0 -1
  266. package/dist/agent-registration-ByMZ_cK5.mjs.map +0 -1
@@ -4,7 +4,7 @@ import { n as utf8ByteLength } from "./utf8-B5pAmhTo.mjs";
4
4
  import { ToolParameterRejection, ToolResultBounds, TruncatedToolResult, applyToolResultBounds, unserializableToolResult } from "./core/ToolResult.mjs";
5
5
  import { IdempotencyKey } from "./core/Receipt.mjs";
6
6
  import { Emitter, Update, UpdateError } from "./core/AgentUpdates.mjs";
7
- import { i as isModelResolver } from "./Agent-0WvBWWbM.mjs";
7
+ import { i as isModelResolver } from "./Agent-BiRbr73L.mjs";
8
8
  import { AgentApprovalDenied, AgentApprovalPending, AgentInputDecodeError, AgentInputError, AgentOutputError, AgentPersistenceCapacityError, AgentPolicyError, AgentRunDispositionError, AgentToolAuthorizationDenied, ContextBudgetError, ContextOverflowError, ModelProtocolError } from "./core/AgentError.mjs";
9
9
  import { IdGenerator } from "./core/IdGenerator.mjs";
10
10
  import { t as copyJson } from "./json-BlJVQZxN.mjs";
@@ -13,11 +13,11 @@ import { a as PinnedTool, c as ToolNames, i as Limits, l as ToolNamespace, n as
13
13
  import { InputTokenUsage, ModelCallUsage, ModelResponseIdentity, OutputTokenUsage, RunTotals, RunUsageReport, emptyRunTotals, sumRunTotals, unknownRunTotals } from "./core/Usage.mjs";
14
14
  import { AgentUpdateEmitted, ApprovalRequested, BudgetWarning, CompactionPerformed, ModelRestarted, ModelStarted, ReasoningDelta, RunCompleted, RunFailed, RunStarted, RunSuspended, SubagentCompleted, SubagentFailed, SubagentInterrupted, SubagentJoined, SubagentProgress, SubagentRequested, SubagentStarted, TextDelta, ToolCallDeclared, ToolCallFailed, ToolCallStarted, ToolCallSucceeded, ToolProgress, TurnCompleted, TurnStarted } from "./core/RunEvent.mjs";
15
15
  import { r as FrameworkMessage, t as AssignmentDisposition } from "./Worker-DZjdMjZn.mjs";
16
- import { t as MessagingHost } from "./MessagingHost-CRUK4JBi.mjs";
16
+ import { t as MessagingHost } from "./MessagingHost-CZCyrnvJ.mjs";
17
17
  import { SubagentHost } from "./engine/SubagentHost.mjs";
18
18
  import { ThreadHistory, ThreadHistoryError } from "./engine/ThreadHistory.mjs";
19
19
  import { n as RunToolVisibility, t as CurrentToolCatalog } from "./ToolExposure-DBATXxmL.mjs";
20
- import { n as outputSchemaContract, r as prepareModelPrompt, t as isTextOutput } from "./output-contract-CMIhu4Cw.mjs";
20
+ import { n as outputSchemaContract, r as prepareModelPrompt, t as isTextOutput } from "./output-contract-DCnLYCdp.mjs";
21
21
  import { _ as initialCompactionState, b as boundedCanonicalJsonSnapshot, d as collectCoveredMessages, f as contextWindowId, g as evaluateMessageTokenEstimates, h as estimatePromptTokens, m as estimateMessageTokens, s as buildCompactedView, v as isContextOverflowMessage, x as boundedJsonSnapshot } from "./compaction-CgFMDiXL.mjs";
22
22
  import { Publisher, noopPublisher } from "./core/ProvisionalText.mjs";
23
23
  import { ContextRolloverRequest, ContextRolloverSelection, ContextRolloverTool, ContextWindow, ContextWindowStatus, ModelCallContext } from "./engine/ContextWindow.mjs";
@@ -301,7 +301,7 @@ const overheads = {
301
301
  "reasoning-end": boundaryOverhead("reasoning-end")
302
302
  };
303
303
  /**
304
- * Capture primitive text and reasoning encodings for the native Schema decoder.
304
+ * Capture complete primitive text and reasoning values for native Schema validation.
305
305
  * Descriptor checks select this optimization; they do not replace the native codec.
306
306
  * Extra fields, accessors, and nonempty metadata use the general ownership path.
307
307
  * No provider object survives, including an empty metadata object's hidden storage.
@@ -339,9 +339,8 @@ const capturePrimitiveTextPart = (part, maxBytes) => {
339
339
  const bytes = utf8ByteLength(id) + (typeof delta === "string" ? utf8ByteLength(delta) : 0);
340
340
  if (bytes + fixed.source > maxBytes || bytes + fixed.encoded > maxBytes) return void 0;
341
341
  snapshot.metadata = {};
342
- delete snapshot[brand];
343
342
  return {
344
- encodedPart: snapshot,
343
+ part: snapshot,
345
344
  retainedBytes: bytes + fixed.encoded
346
345
  };
347
346
  } catch {
@@ -359,9 +358,8 @@ const makeAttempt = Effect.fnUntraced(function* (threadId, submissionId, attempt
359
358
  submissionId,
360
359
  attemptId
361
360
  };
362
- const active = /* @__PURE__ */ new Set();
363
361
  let closed = false;
364
- let generation = 0;
362
+ let nextGeneration = 0;
365
363
  const offerUnsafe = (event) => {
366
364
  try {
367
365
  return publisher.offerUnsafe(event);
@@ -373,12 +371,7 @@ const makeAttempt = Effect.fnUntraced(function* (threadId, submissionId, attempt
373
371
  threadId,
374
372
  openModel: (runId, turnId) => {
375
373
  if (closed) return void 0;
376
- const model = {
377
- ...identity,
378
- runId,
379
- turnId,
380
- generation: ++generation
381
- };
374
+ const generation = ++nextGeneration;
382
375
  let open = true;
383
376
  const handle = {
384
377
  offerUnsafe: (part) => {
@@ -389,31 +382,34 @@ const makeAttempt = Effect.fnUntraced(function* (threadId, submissionId, attempt
389
382
  }) : Response.makePart(part.type, { id: part.id });
390
383
  return offerUnsafe({
391
384
  _tag: "Text",
392
- ...model,
385
+ ...identity,
386
+ runId,
387
+ turnId,
388
+ generation,
393
389
  part: detached
394
390
  });
395
391
  },
396
392
  discard: () => {
397
- if (!open) return;
393
+ if (!open || closed) return;
398
394
  handle.close();
399
395
  offerUnsafe({
400
396
  _tag: "Discard",
401
- ...model
397
+ ...identity,
398
+ runId,
399
+ turnId,
400
+ generation
402
401
  });
403
402
  },
404
403
  close: () => {
405
404
  if (!open) return;
406
405
  open = false;
407
- active.delete(handle);
408
406
  }
409
407
  };
410
- active.add(handle);
411
408
  return handle;
412
409
  },
413
410
  close: () => {
414
411
  if (closed) return;
415
412
  closed = true;
416
- for (const handle of active) handle.close();
417
413
  offerUnsafe({
418
414
  _tag: "AttemptEnded",
419
415
  ...identity
@@ -508,19 +504,24 @@ const exposureSnapshot = Effect.fnUntraced(function* (definition, selection, ent
508
504
  maxSchemaBytes: definition.toolExposure?.maxSchemaBytes ?? 262144
509
505
  }).pipe(Effect.mapError(() => invalid("Invalid Tool exposure bounds")));
510
506
  if (names.length > limits.maxTools) return yield* invalid("Tool exposure exceeds the configured Tool count bound");
511
- if ((yield* Effect.try({
512
- try: () => utf8ByteLength(JSON.stringify(names.map((name) => {
513
- const tool = definition.toolkit.tools[name];
514
- if (tool === void 0) throw new Error("Selected Tool is unavailable");
515
- return Tool.isProviderDefined(tool) ? {
507
+ const declarations = [];
508
+ for (const name of names) {
509
+ const tool = definition.toolkit.tools[name];
510
+ if (tool === void 0) return yield* invalid("A selected Tool schema cannot be rendered");
511
+ declarations.push(yield* Effect.try({
512
+ try: () => Tool.isProviderDefined(tool) ? {
516
513
  type: tool.providerName,
517
514
  args: tool.args
518
515
  } : {
519
516
  name,
520
517
  description: Tool.getDescription(tool),
521
518
  parameters: Tool.getJsonSchema(tool, { transformer })
522
- };
523
- }))),
519
+ },
520
+ catch: () => invalid("A selected Tool schema cannot be rendered")
521
+ }));
522
+ }
523
+ if ((yield* Effect.try({
524
+ try: () => utf8ByteLength(JSON.stringify(declarations)),
524
525
  catch: () => invalid("A selected Tool schema cannot be rendered")
525
526
  })) > limits.maxSchemaBytes) return yield* invalid("Tool exposure exceeds the configured schema byte bound");
526
527
  }
@@ -590,11 +591,9 @@ const restoreToolSpanFailureCause = (cause, marker, original) => {
590
591
  };
591
592
  const MAX_REPORTED_SPAN_LIFECYCLE_DEFECTS = 16;
592
593
  /** Content-free marker used only to close a delegate that cannot be wrapped safely. */
593
- var ToolSpanLifecycleFailure = class extends Error {
594
+ var ToolSpanLifecycleFailure = class extends Schema.TaggedError()("ToolSpanLifecycleFailure", {}) {
594
595
  name = "ToolSpanLifecycleFailure";
595
- constructor() {
596
- super("Tool span lifecycle failed");
597
- }
596
+ message = "Tool span lifecycle failed";
598
597
  };
599
598
  /**
600
599
  * @internal Guard one host span so synchronous exporter defects cannot alter Tool execution.
@@ -636,7 +635,7 @@ var IsolatedToolSpan = class {
636
635
  }
637
636
  end(endTime, exit) {
638
637
  if (this.status._tag === "Ended") return;
639
- const exportedExit = this.#terminalOutcome === "failure" ? Exit.fail(this.#terminalFailure ?? new ToolSpanLifecycleFailure()) : this.#terminalOutcome === "success" ? Exit.succeed(void 0) : exit;
638
+ const exportedExit = this.#terminalOutcome === "failure" ? Exit.fail(this.#terminalFailure ?? ToolSpanLifecycleFailure.make({})) : this.#terminalOutcome === "success" ? Exit.succeed(void 0) : exit;
640
639
  this.status = {
641
640
  _tag: "Ended",
642
641
  startTime: this.status.startTime,
@@ -780,7 +779,7 @@ const makeIsolatedToolTracer = (delegate) => {
780
779
  } catch (defect) {
781
780
  recordDefect(defect);
782
781
  try {
783
- delegateSpan.end(options.startTime, Exit.fail(new ToolSpanLifecycleFailure()));
782
+ delegateSpan.end(options.startTime, Exit.fail(ToolSpanLifecycleFailure.make({})));
784
783
  } catch (closeDefect) {
785
784
  recordDefect(closeDefect);
786
785
  }
@@ -800,7 +799,7 @@ const makeIsolatedToolTracer = (delegate) => {
800
799
  * decorating, or locally providing a Tracer implementation.
801
800
  */
802
801
  var ToolSpanTelemetry = class ToolSpanTelemetry extends Context.Service()("@effect-agent/engine/ToolSpanTelemetry") {
803
- static layer = Layer.effect(ToolSpanTelemetry, Effect.map(Tracer.Tracer, (delegate) => ToolSpanTelemetry.of({
802
+ static make = Effect.map(Tracer.Tracer, (delegate) => ToolSpanTelemetry.of({
804
803
  isolateEffectSpanLifecycle: (effect) => Effect.suspend(() => {
805
804
  const isolated = makeIsolatedToolTracer(delegate);
806
805
  return effect.pipe(Effect.provideService(Tracer.Tracer, isolated.tracer), Effect.ensuring(isolated.reportLifecycleDefects));
@@ -825,7 +824,7 @@ var ToolSpanTelemetry = class ToolSpanTelemetry extends Context.Service()("@effe
825
824
  const isolated = makeIsolatedToolTracer(delegate);
826
825
  return stream.pipe(Stream.provideService(Tracer.Tracer, isolated.tracer), Stream.ensuring(isolated.reportLifecycleDefects));
827
826
  }))
828
- })));
827
+ }));
829
828
  };
830
829
  //#endregion
831
830
  //#region src/engine/internal/error-diagnostic.ts
@@ -917,20 +916,20 @@ const toolCounter = Metric.counter("effect_agent_tool_calls_total", { descriptio
917
916
  /** Publish from the Turn owner; failed storage acceptance is never retried by failure cleanup. */
918
917
  const acceptTurnCommit = (context, trace, durability, commit) => Effect.suspend(() => {
919
918
  if (trace.commitFailed) return Effect.void;
920
- return checkpointExecution(context, durability).pipe(Effect.andThen(() => durability?.commitTurn(commit) ?? Effect.succeed("committed"))).pipe(Effect.flatMap((receipt) => {
919
+ const accepted = checkpointExecution(context, durability).pipe(Effect.andThen(() => durability?.commitTurn(commit) ?? Effect.succeed("committed")));
920
+ return Effect.onExitPrimitive(Effect.flatMap(accepted, (receipt) => {
921
921
  if (receipt === "deferred") return commit._tag === "Response" && commit.defer === true ? Effect.void : Effect.fail(ModelProtocolError.make({ message: "Durability deferred an ineligible Turn commit" }));
922
- return Effect.sync(() => {
923
- if (commit._tag !== "Partial") {
924
- if (commit.response !== void 0) {
925
- context.pendingCommitInputs.splice(0, trace.commitInputCount ?? 0);
926
- trace.responseCommitted = true;
927
- }
928
- if (commit._tag === "Settled") trace.resultsCommitted = true;
922
+ if (commit._tag !== "Partial") {
923
+ if (commit.response !== void 0) {
924
+ context.pendingCommitInputs.splice(0, trace.commitInputCount ?? 0);
925
+ trace.responseCommitted = true;
929
926
  }
930
- });
931
- }), Effect.onExit((exit) => Effect.sync(() => {
927
+ if (commit._tag === "Settled") trace.resultsCommitted = true;
928
+ }
929
+ return Effect.void;
930
+ }), (exit) => {
932
931
  if (Exit.isFailure(exit)) trace.commitFailed = true;
933
- })));
932
+ });
934
933
  });
935
934
  /** Only stream-closed application outcomes enter the trace; provider results stay in response. */
936
935
  const turnToolResults = (trace) => Effect.forEach(trace.applicationToolResults.filter((result) => result !== void 0), (result) => Effect.map(decodeToolCallId(result.id), (toolCallId) => ({
@@ -990,15 +989,14 @@ const schemaClassToolPartPreflight = (part, toolkit) => {
990
989
  if (part === null || typeof part !== "object") return void 0;
991
990
  const read = (key) => {
992
991
  const descriptor = Object.getOwnPropertyDescriptor(part, key);
993
- if (descriptor === void 0 || !("value" in descriptor)) throw new TypeError(`response part ${key} must be an own data property`);
994
- return descriptor.value;
992
+ return descriptor !== void 0 && "value" in descriptor ? descriptor : void 0;
995
993
  };
996
- const type = read("type");
994
+ const type = read("type")?.value;
997
995
  if (type !== "tool-call" && type !== "tool-result") return void 0;
998
- const name = read("name");
996
+ const name = read("name")?.value;
999
997
  if (typeof name !== "string" || !hasTool(toolkit.tools, name)) return void 0;
1000
998
  const tool = toolkit.tools[name];
1001
- const payload = read(type === "tool-call" ? "params" : "result");
999
+ const payload = read(type === "tool-call" ? "params" : "result")?.value;
1002
1000
  if (payload === null || typeof payload !== "object") return void 0;
1003
1001
  const payloadPrototype = Object.getPrototypeOf(payload);
1004
1002
  if (!(type === "tool-call" ? [tool.parametersSchema] : [tool.successSchema, tool.failureSchema]).some((schema) => schemaClassPrototype(schema) === payloadPrototype)) return;
@@ -1019,7 +1017,11 @@ const schemaClassToolPartPreflight = (part, toolkit) => {
1019
1017
  "metadata",
1020
1018
  "encodedResult"
1021
1019
  ];
1022
- for (const key of retainedKeys) preflight[key] = read(key);
1020
+ for (const key of retainedKeys) {
1021
+ const descriptor = read(key);
1022
+ if (descriptor === void 0) return void 0;
1023
+ preflight[key] = descriptor.value;
1024
+ }
1023
1025
  return preflight;
1024
1026
  } catch {
1025
1027
  return;
@@ -1072,10 +1074,10 @@ const captureModelResponsePartGeneral = Effect.fnUntraced(function* (part, toolk
1072
1074
  }
1073
1075
  const encoded = yield* modelResponseParsersFor(toolkit).encode(part).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Model response part failed canonical encoding" })));
1074
1076
  const retainedBytes = yield* inspectModelResponsePartCapacity(usage, encoded, limits);
1077
+ if (typeof structuredCloneFunction !== "function") return yield* ModelProtocolError.make({ message: "Model response part could not be converted into engine-owned data" });
1075
1078
  return {
1076
1079
  encodedPart: yield* Effect.try({
1077
1080
  try: () => {
1078
- if (typeof structuredCloneFunction !== "function") throw new TypeError("structuredClone is unavailable");
1079
1081
  return Reflect.apply(structuredCloneFunction, globalThis, [encoded]);
1080
1082
  },
1081
1083
  catch: () => ModelProtocolError.make({ message: "Model response part could not be converted into engine-owned data" })
@@ -1083,18 +1085,32 @@ const captureModelResponsePartGeneral = Effect.fnUntraced(function* (part, toolk
1083
1085
  retainedBytes
1084
1086
  };
1085
1087
  });
1086
- const captureModelResponsePart = (part, toolkit, usage, limits) => Effect.suspend(() => {
1087
- const primitive = usage.responsePartCount < limits.maxModelResponseParts ? capturePrimitiveTextPart(part, limits.maxModelResponseBytes - usage.responsePartBytes) : void 0;
1088
- return primitive === void 0 ? captureModelResponsePartGeneral(part, toolkit, usage, limits) : Effect.succeed(primitive);
1089
- });
1088
+ const decodePrimitiveModelResponsePart = Schema.decodeUnknownEffect(Schema.toType(Schema.Union([
1089
+ Response.TextStartPart,
1090
+ Response.TextDeltaPart,
1091
+ Response.TextEndPart,
1092
+ Response.ReasoningStartPart,
1093
+ Response.ReasoningDeltaPart,
1094
+ Response.ReasoningEndPart
1095
+ ])));
1090
1096
  /** Reject trailing content before its capture can run an application codec or suspend. */
1091
- const ownModelResponsePart = Effect.fnUntraced(function* (part, toolkit, usage, limits, finished) {
1092
- if (finished) return yield* ModelProtocolError.make({ message: "Model response emitted content after its finish part" });
1093
- const captured = yield* captureModelResponsePart(part, toolkit, usage, limits);
1094
- return {
1095
- ownedPart: yield* modelResponseParsersFor(toolkit).decode(captured.encodedPart).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Model response part failed canonical decoding" }))),
1096
- retainedBytes: captured.retainedBytes
1097
- };
1097
+ const ownModelResponsePart = (part, toolkit, usage, limits, finished) => Effect.suspend(() => {
1098
+ if (finished) return Effect.fail(ModelProtocolError.make({ message: "Model response emitted content after its finish part" }));
1099
+ const primitive = usage.responsePartCount < limits.maxModelResponseParts ? capturePrimitiveTextPart(part, limits.maxModelResponseBytes - usage.responsePartBytes) : void 0;
1100
+ if (primitive !== void 0) return Effect.mapBothEager(decodePrimitiveModelResponsePart(primitive.part), {
1101
+ onFailure: () => ModelProtocolError.make({ message: "Model response part failed canonical decoding" }),
1102
+ onSuccess: (ownedPart) => ({
1103
+ ownedPart,
1104
+ retainedBytes: primitive.retainedBytes
1105
+ })
1106
+ });
1107
+ return Effect.flatMapEager(captureModelResponsePartGeneral(part, toolkit, usage, limits), (captured) => Effect.mapBothEager(modelResponseParsersFor(toolkit).decode(captured.encodedPart), {
1108
+ onFailure: () => ModelProtocolError.make({ message: "Model response part failed canonical decoding" }),
1109
+ onSuccess: (ownedPart) => ({
1110
+ ownedPart,
1111
+ retainedBytes: captured.retainedBytes
1112
+ })
1113
+ }));
1098
1114
  });
1099
1115
  const hasTool = (tools, name) => Object.hasOwn(tools, name);
1100
1116
  const startPart = (parts, id, description) => {
@@ -1121,25 +1137,29 @@ const encodeToolCallParameters = (tool, toolName, decodedParams) => {
1121
1137
  const decodeToolCallParameters = (tool, toolName, encodedParams, boundary = "execution") => {
1122
1138
  return Schema.decodeUnknownEffect(tool.parametersSchema)(encodedParams).pipe(Effect.mapError((cause) => ModelProtocolError.make({ message: boundary === "model" ? `Invalid parameters for Tool ${toolName}: ${cause.message}` : `Recorded parameters for Tool ${toolName} failed validation${boundary === "resume" ? " on resume" : ""}: ${cause.message}` })));
1123
1139
  };
1140
+ /** Native identity proves encoding does not transform the already validated parameters. */
1141
+ const reusesValidatedToolParameters = (tool) => (tool.needsApproval === void 0 || tool.needsApproval === false) && SchemaAST.toEncoded(tool.parametersSchema.ast) === tool.parametersSchema.ast;
1124
1142
  /**
1125
- * Decode executable parameters for approval while retaining their encoded form for
1126
- * Toolkit.handle. A recorded rejection is a terminal failure, never an executable call.
1143
+ * Fresh responses and resumed batches validate every call before reaching this boundary.
1144
+ * Identity encodings with no approval need no second decoded value. Other codecs retain the
1145
+ * complete batch preflight, including validation of their canonical round trip, before dispatch.
1127
1146
  */
1128
1147
  const prepareToolCall = (toolkit, call, declarationIndex, rejection) => {
1129
1148
  const name = call.name;
1130
1149
  if (!hasTool(toolkit.tools, name)) return Effect.fail(ModelProtocolError.make({ message: `Model requested unknown Tool ${call.name}` }));
1131
1150
  const tool = toolkit.tools[name];
1132
- return Effect.gen(function* () {
1133
- const toolCallId = yield* decodeToolCallId(call.id);
1134
- const validation = rejection === void 0 ? Result.succeed(yield* decodeToolCallParameters(tool, call.name, copyJson(call.params))) : Result.fail(rejection);
1135
- return {
1151
+ return Effect.flatMap(decodeToolCallId(call.id), (toolCallId) => {
1152
+ const prepared = (validation) => ({
1136
1153
  call,
1137
1154
  name,
1138
1155
  toolCallId,
1139
1156
  validation,
1140
1157
  tool,
1141
1158
  declarationIndex
1142
- };
1159
+ });
1160
+ if (rejection !== void 0) return Effect.succeed(prepared(Result.fail(rejection)));
1161
+ if (reusesValidatedToolParameters(tool)) return Effect.succeed(prepared(Result.succeed(Option.none())));
1162
+ return Effect.map(decodeToolCallParameters(tool, call.name, copyJson(call.params)), (parameters) => prepared(Result.succeed(Option.some(parameters))));
1143
1163
  });
1144
1164
  };
1145
1165
  /**
@@ -1166,29 +1186,36 @@ const effectiveRunBounds = (policy, options) => ({
1166
1186
  maxTurns: boundedAllowance(policy.maxTurns, options.turnAllowance),
1167
1187
  maxToolCalls: boundedAllowance(policy.maxToolCalls, options.toolCallAllowance)
1168
1188
  });
1189
+ const readSnapshotProperty = Effect.fnUntraced(function* (input, key, invalid, optional = false) {
1190
+ const descriptor = yield* Effect.try({
1191
+ try: () => Object.getOwnPropertyDescriptor(input, key),
1192
+ catch: invalid
1193
+ });
1194
+ if (descriptor === void 0 && optional) return void 0;
1195
+ if (descriptor === void 0 || !("value" in descriptor)) return yield* invalid();
1196
+ return descriptor.value;
1197
+ });
1169
1198
  const decodeResumedSettledCall = Effect.fnUntraced(function* (input) {
1170
- const raw = yield* Effect.try({
1171
- try: () => {
1172
- if (input === null || typeof input !== "object") throw new TypeError("settled Tool Call must be an object");
1173
- const readOwnDataProperty = (key) => {
1174
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
1175
- if (descriptor === void 0 || !("value" in descriptor)) throw new TypeError(`settled Tool Call ${key} must be an own data property`);
1176
- return descriptor.value;
1177
- };
1178
- const selection = Object.getOwnPropertyDescriptor(input, "toolSelection");
1179
- if (selection !== void 0 && !("value" in selection)) throw new TypeError("settled Tool selection must be an own data property");
1180
- const rejected = Object.getOwnPropertyDescriptor(input, "budgetRejected");
1181
- if (rejected !== void 0 && !("value" in rejected)) throw new TypeError("settled Tool Call budgetRejected must be an own data property");
1182
- return {
1183
- id: readOwnDataProperty("id"),
1184
- result: readOwnDataProperty("result"),
1185
- isFailure: readOwnDataProperty("isFailure"),
1186
- ...rejected === void 0 ? {} : { budgetRejected: rejected.value },
1187
- ...selection === void 0 ? {} : { toolSelection: selection.value }
1188
- };
1189
- },
1190
- catch: () => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call" })
1199
+ const invalid = () => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call" });
1200
+ if (input === null || typeof input !== "object") return yield* invalid();
1201
+ const id = yield* readSnapshotProperty(input, "id", invalid);
1202
+ const resultValue = yield* readSnapshotProperty(input, "result", invalid);
1203
+ const isFailure = yield* readSnapshotProperty(input, "isFailure", invalid);
1204
+ const { selection, rejected } = yield* Effect.try({
1205
+ try: () => ({
1206
+ selection: Object.getOwnPropertyDescriptor(input, "toolSelection"),
1207
+ rejected: Object.getOwnPropertyDescriptor(input, "budgetRejected")
1208
+ }),
1209
+ catch: invalid
1191
1210
  });
1211
+ if (selection !== void 0 && !("value" in selection) || rejected !== void 0 && !("value" in rejected)) return yield* invalid();
1212
+ const raw = {
1213
+ id,
1214
+ result: resultValue,
1215
+ isFailure,
1216
+ ...rejected === void 0 ? {} : { budgetRejected: rejected.value },
1217
+ ...selection === void 0 ? {} : { toolSelection: selection.value }
1218
+ };
1192
1219
  const result = boundedCanonicalJsonSnapshot(raw.result, MAX_RESUMED_RESULT_BYTES);
1193
1220
  if (result === void 0) return yield* ModelProtocolError.make({ message: "Turn resume settled Tool result is not bounded canonical JSON" });
1194
1221
  return yield* Schema.decodeUnknownEffect(RunTurnResumeSettledCallSchema)({
@@ -1196,59 +1223,48 @@ const decodeResumedSettledCall = Effect.fnUntraced(function* (input) {
1196
1223
  result: result.value
1197
1224
  }).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call" })));
1198
1225
  });
1199
- const snapshotResumedSettledCalls = (resume, maximum) => Effect.try({
1200
- try: () => {
1201
- if (resume === null || typeof resume !== "object") throw new TypeError("Turn resume must be an object");
1202
- const settledDescriptor = Object.getOwnPropertyDescriptor(resume, "settled");
1203
- if (settledDescriptor === void 0 || !("value" in settledDescriptor)) throw new TypeError("Turn resume settled must be an own data property");
1204
- const settled = settledDescriptor.value;
1205
- if (!Array.isArray(settled)) throw new TypeError("Turn resume settled must be an array");
1206
- const lengthDescriptor = Object.getOwnPropertyDescriptor(settled, "length");
1207
- if (lengthDescriptor === void 0 || !("value" in lengthDescriptor) || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0 || lengthDescriptor.value > maximum) throw new TypeError("Turn resume settled has an invalid length");
1208
- const snapshot = [];
1209
- for (let index = 0; index < lengthDescriptor.value; index += 1) {
1210
- const entryDescriptor = Object.getOwnPropertyDescriptor(settled, String(index));
1211
- if (entryDescriptor === void 0 || !("value" in entryDescriptor)) throw new TypeError("Turn resume settled entries must be own data properties");
1212
- snapshot.push(entryDescriptor.value);
1213
- }
1214
- return snapshot;
1215
- },
1216
- catch: () => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call collection" })
1226
+ const snapshotResumedSettledCalls = Effect.fnUntraced(function* (resume, maximum) {
1227
+ const invalid = () => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call collection" });
1228
+ if (resume === null || typeof resume !== "object") return yield* invalid();
1229
+ const settled = yield* readSnapshotProperty(resume, "settled", invalid);
1230
+ if (!(yield* Effect.try({
1231
+ try: () => Array.isArray(settled),
1232
+ catch: invalid
1233
+ })) || settled === null || typeof settled !== "object") return yield* invalid();
1234
+ const length = yield* readSnapshotProperty(settled, "length", invalid);
1235
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maximum) return yield* invalid();
1236
+ const snapshot = [];
1237
+ for (let index = 0; index < length; index += 1) snapshot.push(yield* readSnapshotProperty(settled, String(index), invalid));
1238
+ return snapshot;
1217
1239
  });
1218
1240
  const decodeResumeUsage = Effect.fnUntraced(function* (input) {
1219
- const snapshot = yield* Effect.try({
1220
- try: () => {
1221
- if (input === null || typeof input !== "object") throw new TypeError("Run resume usage must be an object");
1222
- const read = (key, optional = false) => {
1223
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
1224
- if (descriptor === void 0 && optional) return void 0;
1225
- if (descriptor === void 0 || !("value" in descriptor)) throw new TypeError(`Run resume usage ${key} must be an own data property`);
1226
- return descriptor.value;
1227
- };
1228
- return {
1229
- ...Object.fromEntries([
1230
- "usageStatus",
1231
- "pricingStatus",
1232
- "unobservedModelCalls",
1233
- "children",
1234
- "modelRestarts",
1235
- "webSearchCalls"
1236
- ].map((key) => [key, read(key, true)]).filter(([, value]) => value !== void 0)),
1237
- modelCalls: read("modelCalls"),
1238
- inputTokens: read("inputTokens"),
1239
- outputTokens: read("outputTokens"),
1240
- lastInputTokens: read("lastInputTokens"),
1241
- lastOutputTokens: read("lastOutputTokens"),
1242
- costMicrousd: read("costMicrousd"),
1243
- committedTurns: read("committedTurns"),
1244
- toolCalls: read("toolCalls"),
1245
- programmaticToolCalls: read("programmaticToolCalls"),
1246
- consecutiveToolFailures: read("consecutiveToolFailures"),
1247
- finalizationUsed: read("finalizationUsed")
1248
- };
1249
- },
1250
- catch: () => ModelProtocolError.make({ message: "Run resume usage requires own data properties with non-negative safe-integer totals and last-call tokens no greater than their cumulative totals" })
1251
- });
1241
+ const invalid = () => ModelProtocolError.make({ message: "Run resume usage requires own data properties with non-negative safe-integer totals and last-call tokens no greater than their cumulative totals" });
1242
+ if (input === null || typeof input !== "object") return yield* invalid();
1243
+ const snapshot = {};
1244
+ for (const key of [
1245
+ "usageStatus",
1246
+ "pricingStatus",
1247
+ "unobservedModelCalls",
1248
+ "children",
1249
+ "modelRestarts",
1250
+ "webSearchCalls"
1251
+ ]) {
1252
+ const value = yield* readSnapshotProperty(input, key, invalid, true);
1253
+ if (value !== void 0) snapshot[key] = value;
1254
+ }
1255
+ for (const key of [
1256
+ "modelCalls",
1257
+ "inputTokens",
1258
+ "outputTokens",
1259
+ "lastInputTokens",
1260
+ "lastOutputTokens",
1261
+ "costMicrousd",
1262
+ "committedTurns",
1263
+ "toolCalls",
1264
+ "programmaticToolCalls",
1265
+ "consecutiveToolFailures",
1266
+ "finalizationUsed"
1267
+ ]) snapshot[key] = yield* readSnapshotProperty(input, key, invalid);
1252
1268
  return yield* Schema.decodeUnknownEffect(RunResumeUsageSchema)(snapshot).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Run resume usage requires own data properties with non-negative safe-integer totals and last-call tokens no greater than their cumulative totals" })));
1253
1269
  });
1254
1270
  const makeToolFailedEvent = Effect.fnUntraced(function* (context, turnId, call, error, failureHandling, budgetRejected) {
@@ -1354,7 +1370,8 @@ const stampSubagentEvent = Effect.fnUntraced(function* (context, turnId, payload
1354
1370
  });
1355
1371
  const prepareApprovalRequest = (context, turnId, prepared) => prepareWithinDeadline(context, Effect.gen(function* () {
1356
1372
  if (Result.isFailure(prepared.validation)) return void 0;
1357
- const decodedParams = prepared.validation.success;
1373
+ if (Option.isNone(prepared.validation.success)) return void 0;
1374
+ const decodedParams = prepared.validation.success.value;
1358
1375
  const approval = prepared.tool.needsApproval;
1359
1376
  if (!(typeof approval === "function" ? yield* Effect.suspend(() => {
1360
1377
  const result = approval(decodedParams, {
@@ -1551,6 +1568,7 @@ const toolFailureMessage = (message) => {
1551
1568
  };
1552
1569
  const executePreparedToolCall = Effect.fnUntraced(function* (context, turnId, toolkit, prepared, trace, resultBounds, onWaiting) {
1553
1570
  const call = prepared.call;
1571
+ const toolCallId = prepared.toolCallId;
1554
1572
  const observer = context.toolFailureObserver;
1555
1573
  const telemetryToolCallId = isTelemetryToolCallId(call.id) ? call.id : void 0;
1556
1574
  const executionClass = getToolExecutionClass(prepared.tool);
@@ -1571,7 +1589,6 @@ const executePreparedToolCall = Effect.fnUntraced(function* (context, turnId, to
1571
1589
  let propagatedFailure;
1572
1590
  const terminalTelemetry = (outcome, handling) => isolateToolDerivative(terminalToolTelemetry(telemetryDescriptor, outcome, outcome === "failure" ? failureMarker() : void 0, handling));
1573
1591
  const started = Result.isFailure(prepared.validation) ? Effect.void : Effect.gen(function* () {
1574
- const toolCallId = yield* decodeToolCallId(call.id);
1575
1592
  yield* Effect.logDebug("agent tool handler started").pipe(Effect.annotateLogs({
1576
1593
  agentId: context.agentId,
1577
1594
  runId: context.runId,
@@ -1597,7 +1614,6 @@ const executePreparedToolCall = Effect.fnUntraced(function* (context, turnId, to
1597
1614
  }))));
1598
1615
  const results = prepareWithinDeadline(context, Stream.runForEach(handlerResults, (result) => Effect.gen(function* () {
1599
1616
  if (terminal || trace.finalToolResultIds.has(call.id)) return yield* ModelProtocolError.make({ message: `Tool Call ${call.id} produced more than one terminal result` });
1600
- const toolCallId = yield* decodeToolCallId(call.id);
1601
1617
  const encodedResult = toolResultForJson(prepared.tool, result);
1602
1618
  if (result.preliminary) {
1603
1619
  const owned = yield* ownApplicationToolProgress(context, encodedResult);
@@ -1622,13 +1638,12 @@ const executePreparedToolCall = Effect.fnUntraced(function* (context, turnId, to
1622
1638
  yield* checkpointExecution(context);
1623
1639
  if (!terminal || terminalResult === void 0) return yield* ModelProtocolError.make({ message: `Tool Call ${call.id} completed without a terminal result` });
1624
1640
  const result = terminalResult;
1625
- const toolCallId = yield* decodeToolCallId(call.id);
1626
1641
  let toolSelection;
1627
1642
  if (!result.isFailure && Context.get(prepared.tool.annotations, DiscoveryTool)) {
1628
1643
  toolSelection = yield* validateSelection(result.result, context.definition, context.toolCatalog);
1629
1644
  yield* exposureSnapshot(context.definition, toolSelection, context.toolCatalog, context.toolSchemaTransformer);
1630
1645
  }
1631
- const encodedResult = boundEncodedToolResult(result.encodedResult, resultBounds);
1646
+ const encodedResult = yield* boundEncodedToolResult(result.encodedResult, resultBounds);
1632
1647
  const successResult = result.isFailure ? void 0 : yield* decodeEventJson(encodedResult, "Tool result");
1633
1648
  trace.finalToolResultIds.add(call.id);
1634
1649
  trace.applicationToolResults[prepared.declarationIndex] = {
@@ -1678,7 +1693,7 @@ const executePreparedToolCall = Effect.fnUntraced(function* (context, turnId, to
1678
1693
  }));
1679
1694
  if (result.isFailure) return yield* failureMarker();
1680
1695
  });
1681
- const failTerminalResult = (cause) => Effect.gen(function* () {
1696
+ const failTerminalResult = Effect.fnUntraced(function* (cause) {
1682
1697
  terminal = true;
1683
1698
  terminalResult = void 0;
1684
1699
  propagatedFailure = cause;
@@ -1716,10 +1731,11 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1716
1731
  const visibility = yield* RunToolVisibility;
1717
1732
  const eligible = new Set(context.toolCatalog.filter((entry) => entry.kind === "native").map((entry) => entry.nativeToolName));
1718
1733
  if (calls.some((call) => exposed !== void 0 && !exposed.includes(call.name) || visibility !== void 0 && !settledCallIds?.has(call.id) && !eligible.has(call.name))) return yield* ModelProtocolError.make({ message: "Tool batch calls a Tool outside its request exposure or current visibility" });
1719
- const prepared = yield* prepareWithinDeadline(context, Effect.forEach(calls.flatMap((call, declarationIndex) => settledCallIds?.has(call.id) ? [] : [{
1734
+ const prepareCalls = Effect.forEach(calls.flatMap((call, declarationIndex) => settledCallIds?.has(call.id) ? [] : [{
1720
1735
  call,
1721
1736
  declarationIndex
1722
- }]), ({ call, declarationIndex }) => prepareToolCall(toolkit, call, declarationIndex, trace.toolParameterRejections.get(call.id))));
1737
+ }]), ({ call, declarationIndex }) => prepareToolCall(toolkit, call, declarationIndex, trace.toolParameterRejections.get(call.id)));
1738
+ const prepared = yield* calls.some((call) => !settledCallIds?.has(call.id) && !trace.toolParameterRejections.has(call.id) && hasTool(toolkit.tools, call.name) && !reusesValidatedToolParameters(toolkit.tools[call.name])) ? prepareWithinDeadline(context, prepareCalls) : Effect.flatMap(Clock.currentTimeMillis, (now) => context.durationDeadlineMillis - now <= 0 ? Effect.fail(context.durationFailure) : prepareCalls);
1723
1739
  if (prepared.some((call) => Context.get(call.tool.annotations, ContextRolloverTool)) && calls.length !== 1) return yield* ModelProtocolError.make({ message: "A context rollover Tool must be the only Tool Call in its batch" });
1724
1740
  const descriptors = trace.applicationCallDescriptors.filter((call) => !trace.toolParameterRejections.has(call.toolCallId));
1725
1741
  const executable = settledCallIds === void 0 ? prepared : prepared.filter((call) => !settledCallIds.has(call.call.id));
@@ -1792,25 +1808,25 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1792
1808
  "SubagentFailed",
1793
1809
  "SubagentInterrupted",
1794
1810
  "SubagentJoined"
1795
- ].includes(payload._tag) ? Effect.fail(new RunEventSinkClosedError({ message: "Unsupported Tool event payload" })) : emitPayload(payload) };
1811
+ ].includes(payload._tag) ? Effect.fail(RunEventSinkClosedError.make({ message: "Unsupported Tool event payload" })) : emitPayload(payload) };
1796
1812
  const updateAcceptance = yield* AgentUpdateAcceptance;
1797
1813
  const updateEmitter = { emit: (request) => context.updatePermits.withPermit(Effect.gen(function* () {
1798
- if (!updatesOpen) return yield* new UpdateError({ reason: "unavailable" });
1799
- if (request.target.id !== context.agentId || request.target.updates !== context.definition.updates || context.definition.updates === void 0) return yield* new UpdateError({ reason: "identity" });
1800
- const updateId = yield* Schema.decodeEffect(IdempotencyKey)(request.updateId).pipe(Effect.mapError(() => new UpdateError({ reason: "validation" })));
1801
- const value = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(JSON.stringify(request.value)).pipe(Effect.mapError(() => new UpdateError({ reason: "validation" })));
1814
+ if (!updatesOpen) return yield* UpdateError.make({ reason: "unavailable" });
1815
+ if (request.target.id !== context.agentId || request.target.updates !== context.definition.updates || context.definition.updates === void 0) return yield* UpdateError.make({ reason: "identity" });
1816
+ const updateId = yield* Schema.decodeEffect(IdempotencyKey)(request.updateId).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
1817
+ const value = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(JSON.stringify(request.value)).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
1802
1818
  yield* context.validateUpdate(value);
1803
1819
  const existing = context.updates.get(updateId);
1804
1820
  if (existing !== void 0) {
1805
- if (!Schema.toEquivalence(Schema.Json)(existing.value, value)) return yield* new UpdateError({ reason: "conflict" });
1821
+ if (!Schema.toEquivalence(Schema.Json)(existing.value, value)) return yield* UpdateError.make({ reason: "conflict" });
1806
1822
  return existing;
1807
1823
  }
1808
1824
  const bytes = utf8ByteLength(JSON.stringify(value));
1809
1825
  const maxCount = options.updates?.maxCount ?? 32;
1810
1826
  const maxBytes = options.updates?.maxBytes ?? 16384;
1811
- if (!Number.isSafeInteger(maxCount) || maxCount < 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || context.updates.size >= maxCount || context.updateBytes + bytes > maxBytes) return yield* new UpdateError({ reason: "capacity" });
1827
+ if (!Number.isSafeInteger(maxCount) || maxCount < 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || context.updates.size >= maxCount || context.updateBytes + bytes > maxBytes) return yield* UpdateError.make({ reason: "capacity" });
1812
1828
  const snapshot = boundedCanonicalJsonSnapshot(value, bytes);
1813
- if (snapshot === void 0) return yield* new UpdateError({ reason: "validation" });
1829
+ if (snapshot === void 0) return yield* UpdateError.make({ reason: "validation" });
1814
1830
  const accepted = yield* updateAcceptance.accept(Object.freeze(Update.make({
1815
1831
  schemaVersion: 1,
1816
1832
  agentId: context.agentId,
@@ -1820,8 +1836,8 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1820
1836
  sequence: context.updates.size + 1,
1821
1837
  value: snapshot.value
1822
1838
  })));
1823
- const validated = yield* Schema.decodeEffect(Update)(accepted).pipe(Effect.mapError(() => new UpdateError({ reason: "validation" })));
1824
- if (validated.agentId !== context.agentId || validated.threadId !== context.threadId || validated.runId !== context.runId || validated.updateId !== request.updateId || !Schema.toEquivalence(Schema.Json)(validated.value, value)) return yield* new UpdateError({ reason: "identity" });
1839
+ const validated = yield* Schema.decodeEffect(Update)(accepted).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
1840
+ if (validated.agentId !== context.agentId || validated.threadId !== context.threadId || validated.runId !== context.runId || validated.updateId !== request.updateId || !Schema.toEquivalence(Schema.Json)(validated.value, value)) return yield* UpdateError.make({ reason: "identity" });
1825
1841
  const update = Object.freeze(Update.make({
1826
1842
  ...validated,
1827
1843
  value: snapshot.value
@@ -1831,48 +1847,45 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1831
1847
  yield* emitPayload({
1832
1848
  _tag: "AgentUpdateEmitted",
1833
1849
  update
1834
- }).pipe(Effect.mapError(() => new UpdateError({ reason: "unavailable" })));
1850
+ }).pipe(Effect.mapError(() => UpdateError.make({ reason: "unavailable" })));
1835
1851
  return update;
1836
1852
  })) };
1837
1853
  const permits = yield* Semaphore.make(concurrency);
1838
1854
  const handlers = Effect.gen(function* () {
1839
- for (const group of groups) {
1840
- yield* Effect.forEach(group, (call) => permits.withPermit(Effect.scoped(Effect.gen(function* () {
1841
- const callBody = Effect.scoped(Effect.gen(function* () {
1842
- yield* checkpointExecution(context, durability);
1843
- const subagentHost = yield* SubagentHost.forTool;
1844
- const messagingHost = yield* MessagingHost.forTool;
1845
- const source = {
1846
- _tag: "tool",
1847
- agentId: context.agentId,
1848
- threadId: context.threadId,
1849
- runId: context.runId,
1850
- toolCallId: call.toolCallId
1851
- };
1852
- const broker = yield* makeToolBrokerService({
1853
- context,
1854
- turnId,
1855
- outerToolCallId: call.toolCallId,
1856
- turn,
1857
- maxToolCalls: brokerAccounting.maxToolCalls,
1858
- declaredToolCalls: brokerAccounting.declaredToolCalls,
1859
- budget: options.budget,
1860
- reservePolicyUsage: durability?.reservePolicyUsage,
1861
- hookServices
1862
- });
1863
- return yield* executePreparedToolCall(context, turnId, toolkit, call, trace, resultBounds, (waiting) => {
1864
- waitingByDeclaration.set(call.declarationIndex, waiting);
1865
- }).pipe(Effect.provideService(DurableStep, stepServiceFor(call)), Effect.provideService(SubagentHost, subagentHost(source)), Effect.provideService(MessagingHost, messagingHost(source)), Effect.provideService(ToolBroker, broker.service), Effect.provideService(CurrentToolCatalog, { entries: context.toolCatalog }), Effect.ensuring(Effect.sync(() => broker.close())));
1866
- }));
1867
- const fiber = yield* Effect.forkScoped(callBody);
1868
- return yield* Fiber.join(fiber);
1869
- }))), {
1870
- concurrency: "unbounded",
1871
- discard: true
1872
- });
1855
+ for (const group of groups) yield* Effect.forEach(group, (call) => permits.withPermit(Effect.acquireUseRelease(Effect.forkScoped(Effect.scoped(Effect.gen(function* () {
1873
1856
  yield* checkpointExecution(context, durability);
1874
- }
1875
- }).pipe(Effect.provideService(RunEventSink, batchSink), Effect.provideService(Emitter, updateEmitter), Effect.provideService(SubagentDurability, batchSubagentDurability), Effect.ensuring(Effect.sync(() => {
1857
+ const subagentHost = yield* SubagentHost.forTool;
1858
+ const messagingHost = yield* MessagingHost.forTool;
1859
+ const source = {
1860
+ _tag: "tool",
1861
+ agentId: context.agentId,
1862
+ threadId: context.threadId,
1863
+ runId: context.runId,
1864
+ toolCallId: call.toolCallId
1865
+ };
1866
+ const broker = yield* makeToolBrokerService({
1867
+ context,
1868
+ turnId,
1869
+ outerToolCallId: call.toolCallId,
1870
+ turn,
1871
+ maxToolCalls: brokerAccounting.maxToolCalls,
1872
+ declaredToolCalls: brokerAccounting.declaredToolCalls,
1873
+ budget: options.budget,
1874
+ reservePolicyUsage: durability?.reservePolicyUsage,
1875
+ hookServices
1876
+ });
1877
+ const step = stepServiceFor(call);
1878
+ const subagent = subagentHost(source);
1879
+ const messaging = messagingHost(source);
1880
+ const catalog = { entries: context.toolCatalog };
1881
+ return yield* executePreparedToolCall(context, turnId, toolkit, call, trace, resultBounds, (waiting) => {
1882
+ waitingByDeclaration.set(call.declarationIndex, waiting);
1883
+ }).pipe(Effect.updateContext((services) => services.pipe(Context.add(CurrentToolCatalog, catalog), Context.add(ToolBroker, broker.service), Context.add(MessagingHost, messaging), Context.add(SubagentHost, subagent), Context.add(DurableStep, step))), Effect.ensuring(Effect.sync(() => broker.close())));
1884
+ }))), Fiber.join, Fiber.interrupt)), {
1885
+ concurrency: group.length === 1 ? 1 : "unbounded",
1886
+ discard: true
1887
+ });
1888
+ }).pipe(Effect.updateContext((services) => services.pipe(Context.add(SubagentDurability, batchSubagentDurability), Context.add(Emitter, updateEmitter), Context.add(RunEventSink, batchSink))), Effect.ensuring(Effect.sync(() => {
1876
1889
  updatesOpen = false;
1877
1890
  })));
1878
1891
  yield* guardBudgetEffect(handlers, options.budget);
@@ -1996,26 +2009,22 @@ const toolResultForJson = (tool, result) => {
1996
2009
  if (!result.isFailure && result.encodedResult === void 0 && SchemaAST.isVoid(SchemaAST.toEncoded(tool.successSchema.ast))) return Schema.encodeSync(Schema.toCodecJson(Schema.Void))(void 0);
1997
2010
  return result.encodedResult;
1998
2011
  };
2012
+ const decodeBoundedToolResult = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
1999
2013
  /**
2000
2014
  * RUN-022: bound one application Tool result at the settle seam. The bounded
2001
2015
  * value is what official history, the settled record, and the success event
2002
- * all carry, so every downstream surface agrees; a within-bounds result
2003
- * passes through with its identity preserved.
2016
+ * all carry, so every downstream surface agrees on the measured representation.
2004
2017
  */
2005
2018
  const boundEncodedToolResult = (encodedResult, bounds) => {
2006
2019
  let text;
2007
2020
  try {
2008
2021
  text = JSON.stringify(encodedResult);
2009
2022
  } catch (cause) {
2010
- return unserializableToolResult(cause);
2023
+ return Effect.succeed(unserializableToolResult(cause));
2011
2024
  }
2012
- if (text === void 0) return unserializableToolResult("the encoded result is not a JSON value");
2025
+ if (text === void 0) return Effect.succeed(unserializableToolResult("the encoded result is not a JSON value"));
2013
2026
  const bounded = applyToolResultBounds(text, bounds);
2014
- try {
2015
- return Schema.decodeSync(Schema.fromJsonString(Schema.Unknown))(bounded);
2016
- } catch (cause) {
2017
- return unserializableToolResult(cause);
2018
- }
2027
+ return decodeBoundedToolResult(bounded).pipe(Effect.orElseSucceed(unserializableToolResult));
2019
2028
  };
2020
2029
  const durableResultBounds = (bounds, options, turn) => ToolResultBounds.make({ maxBytes: Math.min(bounds.maxBytes, options.durability?.toolResultMaxBytes ?? bounds.maxBytes, options.resume?.turn === turn ? options.resume.toolResultMaxBytes ?? bounds.maxBytes : bounds.maxBytes) });
2021
2030
  const RUN_STATUS_WARNING = " · WARNING: approaching limits — converge and deliver your final result now.";
@@ -2086,13 +2095,13 @@ const consumeUsage = (agent, context, usage, toolCallCount, turn, options, respo
2086
2095
  const reportedText = providerUsage.outputTokens.text ?? 0;
2087
2096
  const reasoning = providerUsage.outputTokens.reasoning ?? 0;
2088
2097
  const reportedInputTotal = providerUsage.inputTokens.total;
2089
- const reportedInputWithoutWrite = yield* decodeProviderUsageTotal(reportedUncached + cacheRead);
2098
+ const reportedInputWithoutWrite = reportedUncached + cacheRead;
2090
2099
  const disjointReportedUncached = reportedUncached - (reportedInputTotal !== void 0 && providerUsage.inputTokens.uncached !== void 0 && providerUsage.inputTokens.cacheWrite !== void 0 && cacheWrite <= reportedUncached && reportedInputWithoutWrite <= reportedInputTotal && cacheWrite > reportedInputTotal - reportedInputWithoutWrite ? cacheWrite : 0);
2091
- const reportedInputComponents = yield* decodeProviderUsageTotal(disjointReportedUncached + cacheRead + cacheWrite);
2100
+ const reportedInputComponents = disjointReportedUncached + cacheRead + cacheWrite;
2092
2101
  const allInputComponentsReported = providerUsage.inputTokens.uncached !== void 0 && providerUsage.inputTokens.cacheRead !== void 0 && providerUsage.inputTokens.cacheWrite !== void 0;
2093
2102
  if (reportedInputTotal !== void 0 && (reportedInputTotal < reportedInputComponents || allInputComponentsReported && reportedInputTotal !== reportedInputComponents)) return yield* invalidProviderUsage();
2094
2103
  const inputTokens = reportedInputTotal ?? reportedInputComponents;
2095
- const reportedOutputComponents = yield* decodeProviderUsageTotal(reportedText + reasoning);
2104
+ const reportedOutputComponents = reportedText + reasoning;
2096
2105
  const reportedOutputTotal = providerUsage.outputTokens.total;
2097
2106
  const allOutputComponentsReported = providerUsage.outputTokens.text !== void 0 && providerUsage.outputTokens.reasoning !== void 0;
2098
2107
  if (reportedOutputTotal !== void 0 && (reportedOutputTotal < reportedOutputComponents || allOutputComponentsReported && reportedOutputTotal !== reportedOutputComponents)) return yield* invalidProviderUsage();
@@ -2104,6 +2113,17 @@ const consumeUsage = (agent, context, usage, toolCallCount, turn, options, respo
2104
2113
  const normalizedCacheWrite = cacheWrite + (providerUsage.inputTokens.uncached !== void 0 && providerUsage.inputTokens.cacheRead !== void 0 && providerUsage.inputTokens.cacheWrite === void 0 ? inputRemainder : 0);
2105
2114
  const text = reportedText + (providerUsage.outputTokens.text === void 0 ? outputRemainder : 0);
2106
2115
  const normalizedReasoning = reasoning + (providerUsage.outputTokens.text !== void 0 && providerUsage.outputTokens.reasoning === void 0 ? outputRemainder : 0);
2116
+ const inputUsage = yield* InputTokenUsage.makeEffect({
2117
+ total: inputTokens,
2118
+ uncached,
2119
+ cacheRead: normalizedCacheRead,
2120
+ cacheWrite: normalizedCacheWrite
2121
+ }).pipe(Effect.mapError(() => invalidProviderUsage()));
2122
+ const outputUsage = yield* OutputTokenUsage.makeEffect({
2123
+ total: outputTokens,
2124
+ text,
2125
+ reasoning: normalizedReasoning
2126
+ }).pipe(Effect.mapError(() => invalidProviderUsage()));
2107
2127
  const totalTokens = yield* decodeProviderUsageTotal(inputTokens + outputTokens);
2108
2128
  const provider = yield* Model.ProviderName;
2109
2129
  const model = yield* Model.ModelName;
@@ -2143,17 +2163,8 @@ const consumeUsage = (agent, context, usage, toolCallCount, turn, options, respo
2143
2163
  pricingStatus,
2144
2164
  ...serviceTier === void 0 ? {} : { serviceTier },
2145
2165
  ...pricingVersion === void 0 ? {} : { pricingVersion },
2146
- inputTokens: InputTokenUsage.make({
2147
- total: inputTokens,
2148
- uncached,
2149
- cacheRead: normalizedCacheRead,
2150
- cacheWrite: normalizedCacheWrite
2151
- }),
2152
- outputTokens: OutputTokenUsage.make({
2153
- total: outputTokens,
2154
- text,
2155
- reasoning: normalizedReasoning
2156
- }),
2166
+ inputTokens: inputUsage,
2167
+ outputTokens: outputUsage,
2157
2168
  costMicrousd
2158
2169
  });
2159
2170
  const modelCalls = yield* decodeProviderUsageTotal(context.modelCalls + 1);
@@ -2451,7 +2462,7 @@ const compactContext = (agent, context, source, turn, options, resolvedModelInpu
2451
2462
  let summaryFailure;
2452
2463
  const textParts = /* @__PURE__ */ new Map();
2453
2464
  const reasoningParts = /* @__PURE__ */ new Map();
2454
- const consumeSummaryPart = (owned) => Effect.gen(function* () {
2465
+ const consumeSummaryPart = Effect.fnUntraced(function* (owned) {
2455
2466
  responseUsage.responsePartCount++;
2456
2467
  responseUsage.responsePartBytes += owned.retainedBytes;
2457
2468
  const ownedPart = owned.ownedPart;
@@ -2604,13 +2615,13 @@ const evaluateInstructions = (instructions, input) => Effect.suspend(() => {
2604
2615
  return Effect.isEffect(result) ? result : Effect.succeed(result);
2605
2616
  });
2606
2617
  const encodeInput = (agent, input) => Schema.encodeEffect(agent.definition.input)(input).pipe(Effect.mapError((cause) => AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` })));
2607
- const renderInputPromptEffect = (inputPrompt, decodedInput, encodedInput) => inputPrompt === void 0 ? Effect.try({
2608
- try: () => {
2609
- const encoded = JSON.stringify(encodedInput);
2610
- if (encoded === void 0) throw new Error("Agent input cannot be represented as JSON");
2611
- return encoded;
2612
- },
2613
- catch: (cause) => AgentInputError.make({ message: `Unable to materialize Agent input: ${errorMessage(cause)}` })
2618
+ const renderInputPromptEffect = (inputPrompt, decodedInput, encodedInput) => inputPrompt === void 0 ? Effect.gen(function* () {
2619
+ const encoded = yield* Effect.try({
2620
+ try: () => JSON.stringify(encodedInput),
2621
+ catch: (cause) => AgentInputError.make({ message: `Unable to materialize Agent input: ${errorMessage(cause)}` })
2622
+ });
2623
+ if (encoded === void 0) return yield* AgentInputError.make({ message: "Unable to materialize Agent input: Agent input cannot be represented as JSON" });
2624
+ return encoded;
2614
2625
  }) : Effect.suspend(() => {
2615
2626
  const result = inputPrompt(decodedInput);
2616
2627
  return Effect.isEffect(result) ? result : Effect.succeed(result);
@@ -2634,9 +2645,9 @@ const decodeProviderToolCallIdValue = Schema.decodeEffect(ProviderToolCallId);
2634
2645
  const decodeProviderResponsePartIdValue = Schema.decodeEffect(ProviderResponsePartId);
2635
2646
  const decodeJson = Schema.decodeUnknownEffect(Schema.Json);
2636
2647
  const decodeToolCallId = (id) => Effect.suspend(() => decodeToolCallIdValue(id).pipe(Effect.mapError((cause) => ModelProtocolError.make({ message: `Invalid Tool Call ID: ${cause.message}` }))));
2637
- const decodeProviderToolCallId = (id) => Effect.suspend(() => decodeProviderToolCallIdValue(id).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Model supplied an invalid Tool Call ID; expected 1-128 ASCII letters, digits, dots, underscores, colons, or hyphens" }))));
2638
- const decodeProviderResponsePartId = (id) => Effect.suspend(() => decodeProviderResponsePartIdValue(id).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Model supplied an invalid response part ID; expected 1-128 ASCII letters, digits, dots, underscores, colons, or hyphens" }))));
2639
- const validateProviderPartIdentifiers = Effect.fnUntraced(function* (part) {
2648
+ const decodeProviderToolCallId = (id) => decodeProviderToolCallIdValue(id).pipe(Effect.mapErrorEager(() => ModelProtocolError.make({ message: "Model supplied an invalid Tool Call ID; expected 1-128 ASCII letters, digits, dots, underscores, colons, or hyphens" })));
2649
+ const decodeProviderResponsePartId = (id) => decodeProviderResponsePartIdValue(id).pipe(Effect.mapErrorEager(() => ModelProtocolError.make({ message: "Model supplied an invalid response part ID; expected 1-128 ASCII letters, digits, dots, underscores, colons, or hyphens" })));
2650
+ const validateProviderPartIdentifiers = Effect.fnUntracedEager(function* (part) {
2640
2651
  switch (part.type) {
2641
2652
  case "text-start":
2642
2653
  case "text-delta":
@@ -2706,7 +2717,7 @@ const promptFromTurnParts = (trace) => {
2706
2717
  if (!attachedProviderResults) messages.push(Prompt.makeMessage("assistant", { content: providerResults }));
2707
2718
  return Prompt.fromMessages(messages);
2708
2719
  };
2709
- const processModelPart = Effect.fnUntraced(function* (context, turnId, turn, tools, trace, part, retainedBytes, events) {
2720
+ const processModelPart = Effect.fnUntracedEager(function* (context, turnId, turn, tools, trace, part, retainedBytes, events) {
2710
2721
  trace.responsePartCount++;
2711
2722
  trace.responsePartBytes += retainedBytes;
2712
2723
  if (part.type === "finish" && trace.usage === void 0) {
@@ -2782,7 +2793,7 @@ const processModelPart = Effect.fnUntraced(function* (context, turnId, turn, too
2782
2793
  const error = AiError.make({
2783
2794
  module: "Toolkit",
2784
2795
  method: `${part.name}.handle`,
2785
- reason: new AiError.ToolParameterValidationError({
2796
+ reason: AiError.ToolParameterValidationError.make({
2786
2797
  toolName: part.name,
2787
2798
  description: decoded.failure.message
2788
2799
  })
@@ -3030,10 +3041,10 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3030
3041
  ...outputContractMessage === void 0 ? {} : { outputContract: outputContractMessage }
3031
3042
  };
3032
3043
  const modelContext = options.context === void 0 ? { prompt } : yield* prepareWithinDeadline(context, options.context.prepare(contextRequest));
3033
- if (context.resolvedModel && modelContext.modelCall !== void 0) return yield* new AiError.AiError({
3044
+ if (context.resolvedModel && modelContext.modelCall !== void 0) return yield* AiError.AiError.make({
3034
3045
  module: "AgentRuntime",
3035
3046
  method: "resolveModel",
3036
- reason: new AiError.InvalidRequestError({ description: "Context preparation cannot replace a thread-resolved model" })
3047
+ reason: AiError.InvalidRequestError.make({ description: "Context preparation cannot replace a thread-resolved model" })
3037
3048
  });
3038
3049
  const callContext = modelContext.modelCall === void 0 ? void 0 : yield* Schema.decodeEffect(ModelCallContext)(modelContext.modelCall.context).pipe(Effect.mapError((cause) => CompactionError.make({
3039
3050
  message: "Invalid resolved model context bounds",
@@ -3330,7 +3341,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3330
3341
  const exit = yield* consumeTurnUsage(0).pipe(Effect.exit);
3331
3342
  if (Exit.isFailure(exit)) failedUsageCause = exit.cause;
3332
3343
  });
3333
- const attempt = (basis) => Effect.flatten(outgoingModelPrompt(policy, context, prepareModelPrompt(Prompt.fromMessages([...basis.content, ...transientContext.content]), outputContract._tag === "rendered" ? outputContract.part : void 0, systemMessagesInHistory, staticInstructions), turn, priorToolCalls, systemMessagesInHistory).pipe(withCallModel, Effect.flatMap((providerPrompt) => Effect.gen(function* () {
3344
+ const attempt = (basis) => Effect.flatten(outgoingModelPrompt(policy, context, prepareModelPrompt(Prompt.concat(basis, transientContext), outputContract._tag === "rendered" ? outputContract.part : void 0, systemMessagesInHistory, staticInstructions), turn, priorToolCalls, systemMessagesInHistory).pipe(withCallModel, Effect.flatMap((providerPrompt) => Effect.gen(function* () {
3334
3345
  yield* checkpointExecution(context, options.durability);
3335
3346
  const toolChoice = modelToolChoice();
3336
3347
  let requestToolkit = modelToolkit;
@@ -3367,27 +3378,31 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3367
3378
  trace.usageConsumed = false;
3368
3379
  provisionalText = !restartRequested && attempt?.threadId === context.threadId ? attempt.openModel(context.runId, turnId) : void 0;
3369
3380
  activeProvisionalText = provisionalText;
3370
- })), Stream.runForEach((part) => Effect.gen(function* () {
3371
- const owned = yield* ownModelResponsePart(part, agent.definition.toolkit, trace, context.bufferLimits, trace.finished);
3372
- const events = context.publish === void 0 ? void 0 : [];
3373
- yield* processModelPart(context, turnId, turn, agent.definition.toolkit.tools, trace, owned.ownedPart, owned.retainedBytes, events);
3374
- if (provisionalText !== void 0) {
3375
- const part = owned.ownedPart;
3376
- if (part.type === "text-start" || part.type === "text-delta" || part.type === "text-end") provisionalText.offerUnsafe(part);
3381
+ })), Stream.runForEachArray((parts) => Effect.gen(function* () {
3382
+ for (const part of parts) {
3383
+ const owned = yield* ownModelResponsePart(part, agent.definition.toolkit, trace, context.bufferLimits, trace.finished);
3384
+ const events = context.publish === void 0 ? void 0 : [];
3385
+ yield* processModelPart(context, turnId, turn, agent.definition.toolkit.tools, trace, owned.ownedPart, owned.retainedBytes, events);
3386
+ if (provisionalText !== void 0) {
3387
+ const part = owned.ownedPart;
3388
+ if (part.type === "text-start" || part.type === "text-delta" || part.type === "text-end") provisionalText.offerUnsafe(part);
3389
+ }
3390
+ if (events !== void 0) yield* publishEvents(context, events);
3377
3391
  }
3378
- if (events !== void 0) yield* publishEvents(context, events);
3379
3392
  })), (effect) => prepareWithinDeadline(context, effect), Effect.onExit((exit) => {
3380
3393
  if (Exit.isSuccess(exit)) return Effect.void;
3381
3394
  provisionalText?.discard();
3382
3395
  return retainFailedUsage();
3383
3396
  }))));
3384
3397
  }))));
3385
- const attemptWithRetries = Effect.suspend(() => attempt(compactedOutgoing())).pipe(Effect.retry(($) => $(Schedule.exponential(MODEL_RETRY_BASE)).pipe(Schedule.upTo({ times: policy.modelRetries ?? 0 }), Schedule.while(({ input: error }) => {
3398
+ const attemptWithRetries = Effect.suspend(() => attempt(compactedOutgoing())).pipe((operation) => (policy.modelRetries ?? 0) === 0 ? operation : Effect.retry(operation, ($) => $(Schedule.exponential(MODEL_RETRY_BASE)).pipe(Schedule.upTo({ times: policy.modelRetries ?? 0 }), Schedule.while(({ input: error }) => {
3386
3399
  const lastPart = trace.parts.at(-1);
3387
- return canRepeatModelCall && !hasStreamedContent(trace) && (lastPart?.type === "error" && isTransientErrorPayload(lastPart.error) || AiError.isAiError(error) && error.isRetryable);
3400
+ const providerError = error;
3401
+ return canRepeatModelCall && !hasStreamedContent(trace) && (lastPart?.type === "error" && isTransientErrorPayload(lastPart.error) || AiError.isAiError(providerError) && providerError.isRetryable);
3388
3402
  }), Schedule.modifyDelay(({ input: error, duration }) => Effect.gen(function* () {
3389
3403
  const backoff = Duration.min(duration, MODEL_RETRY_MAX_DELAY);
3390
- const retryAfter = AiError.isAiError(error) ? error.retryAfter : void 0;
3404
+ const providerError = error;
3405
+ const retryAfter = AiError.isAiError(providerError) ? providerError.retryAfter : void 0;
3391
3406
  const requested = retryAfter === void 0 ? backoff : Duration.max(backoff, retryAfter);
3392
3407
  const remaining = Math.max(0, context.durationDeadlineMillis - (yield* Clock.currentTimeMillis));
3393
3408
  return Duration.min(requested, Duration.millis(remaining));
@@ -3551,7 +3566,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3551
3566
  * steering at the safe seam, and start the next Turn. The `maxTurns`
3552
3567
  * guard already ran for these Tool Call sites.
3553
3568
  */
3554
- const continueTurn = (history) => Effect.gen(function* () {
3569
+ const continueTurn = Effect.fnUntraced(function* (history) {
3555
3570
  trace.historyAccepted = true;
3556
3571
  yield* advanceHistory(context, history, options);
3557
3572
  yield* settleTurn(context, trace, turn, turnId, options);
@@ -3565,7 +3580,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3565
3580
  * under the `maxTurns` and repeated-failure Stop Policy bounds or
3566
3581
  * complete the Run with the Turn's decoded final output.
3567
3582
  */
3568
- const settleOrFollowUp = (history) => Effect.gen(function* () {
3583
+ const settleOrFollowUp = Effect.fnUntraced(function* (history) {
3569
3584
  trace.historyAccepted = true;
3570
3585
  yield* advanceHistory(context, history, options);
3571
3586
  const turnsBlocked = policy.onExhaustion === "fail" ? turn >= bounds.maxTurns : turn > bounds.maxTurns;
@@ -3845,7 +3860,7 @@ const makeResumeTurn = (agent, context, prompt, resume, countedToolCalls, option
3845
3860
  settledCalls.push({
3846
3861
  id: call.id,
3847
3862
  isFailure: true,
3848
- result: yield* decodeEventJson(boundEncodedToolResult(rejection.error, durableResultBounds(agent.definition.policy.toolResultBounds, options, turn)), "Rejected Tool result")
3863
+ result: yield* decodeEventJson(yield* boundEncodedToolResult(rejection.error, durableResultBounds(agent.definition.policy.toolResultBounds, options, turn)), "Rejected Tool result")
3849
3864
  });
3850
3865
  recordedSettledIds.add(call.id);
3851
3866
  }
@@ -4062,11 +4077,10 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4062
4077
  const attemptDeadlineMillis = attemptStartedAtMillis + Duration.toMillis(agent.definition.policy.maxDuration);
4063
4078
  const durationDeadlineMillis = options.durationDeadline === void 0 ? attemptDeadlineMillis : Math.min(attemptDeadlineMillis, DateTime.toEpochMillis(options.durationDeadline));
4064
4079
  const startedAtMillis = options.runStartedAt === void 0 ? attemptStartedAtMillis : DateTime.toEpochMillis(options.runStartedAt);
4065
- const programmaticAuthorization = Layer.effect(ProgrammaticToolAuthorization, Effect.gen(function* () {
4066
- const services = yield* Effect.context();
4080
+ const programmaticAuthorization = Effect.map(Effect.context(), (services) => {
4067
4081
  const selected = options.toolAuthorization;
4068
4082
  return ProgrammaticToolAuthorization.of({ authorize: (request) => selected === void 0 ? Effect.succeed({ _tag: "allowed" }) : provideHookServices(selected.authorize(request), services).pipe(Effect.catchCauseFilter(Cause.findError, (error, cause) => Effect.fail(new BrokerCallFailure(error, cause)))) });
4069
- }));
4083
+ });
4070
4084
  const interpreted = Effect.flatten(Effect.gen(function* () {
4071
4085
  const resumed = options.resume === void 0 ? void 0 : {
4072
4086
  batch: options.resume,
@@ -4081,7 +4095,7 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4081
4095
  const initialToolSelection = options.toolSelection ?? (agent.definition.toolExposure === void 0 ? void 0 : { toolNames: agent.definition.toolExposure.initialToolNames ?? [] });
4082
4096
  const updateSchema = agent.definition.updates;
4083
4097
  const updateContext = yield* Effect.context();
4084
- const validateUpdate = updateSchema === void 0 ? () => Effect.fail(new UpdateError({ reason: "unavailable" })) : (value) => Schema.decodeEffect(updateSchema)(value).pipe(Effect.provide(updateContext), Effect.asVoid, Effect.mapError(() => new UpdateError({ reason: "validation" })));
4098
+ const validateUpdate = updateSchema === void 0 ? () => Effect.fail(UpdateError.make({ reason: "unavailable" })) : (value) => Schema.decodeEffect(updateSchema)(value).pipe(Effect.provide(updateContext), Effect.asVoid, Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4085
4099
  const languageModel = yield* LanguageModel.LanguageModel;
4086
4100
  const resolver = isModelResolver(languageModel) ? languageModel : void 0;
4087
4101
  const context = {
@@ -4257,8 +4271,10 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4257
4271
  let request = pending;
4258
4272
  while (request !== void 0) {
4259
4273
  const output = yield* Effect.scoped(request.resume === void 0 ? makeTurn(agent, context, request.prompt, request.turn, request.toolCalls, options, request.restarting) : makeResumeTurn(agent, context, request.prompt, request.resume, request.toolCalls, options));
4260
- yield* checkpointExecution(context, options.durability);
4261
- if (output._tag !== "NextTurn") return output;
4274
+ if (output._tag !== "NextTurn") {
4275
+ yield* checkpointExecution(context, options.durability);
4276
+ return output;
4277
+ }
4262
4278
  request = output;
4263
4279
  }
4264
4280
  return yield* ModelProtocolError.make({ message: "Agent execution ended without RunCompleted" });
@@ -4270,10 +4286,10 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4270
4286
  turn: pending.turn,
4271
4287
  input: context.input
4272
4288
  }, options.subagentGrant, options.delegationDepth ?? options.parentLink?.depth ?? 0);
4273
- const selectionPrompt = yield* Schema.encodeEffect(Schema.fromJsonString(Prompt.Prompt))(pending.prompt).pipe(Effect.mapError((cause) => new AiError.AiError({
4289
+ const selectionPrompt = yield* Schema.encodeEffect(Schema.fromJsonString(Prompt.Prompt))(pending.prompt).pipe(Effect.mapError((cause) => AiError.AiError.make({
4274
4290
  module: "AgentRuntime",
4275
4291
  method: "resolveModel",
4276
- reason: new AiError.InvalidRequestError({ description: `Cannot encode model selection context: ${cause.message}` })
4292
+ reason: AiError.InvalidRequestError.make({ description: `Cannot encode model selection context: ${cause.message}` })
4277
4293
  })));
4278
4294
  const selected = yield* prepareWithinDeadline(context, resolver.resolve({
4279
4295
  threadId,
@@ -4289,11 +4305,11 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4289
4305
  return Effect.provide(turns, services);
4290
4306
  }));
4291
4307
  const nativeUpdateTool = agent.definition.toolkit.tools.emit_update;
4292
- const updateHandlers = agent.definition.updates === void 0 || nativeUpdateTool === void 0 ? Context.empty() : yield* Toolkit.make(nativeUpdateTool).toHandlers({ emit_update: (parameters, call) => Effect.gen(function* () {
4293
- if (call.toolCallId === void 0) return yield* new UpdateError({ reason: "unavailable" });
4294
- const decoded = yield* Schema.decodeUnknownEffect(Schema.Struct({ value: Schema.Unknown }))(parameters).pipe(Effect.mapError(() => new UpdateError({ reason: "validation" })));
4295
- const value = yield* Schema.encodeUnknownEffect(agent.definition.updates)(decoded.value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Json)), Effect.mapError(() => new UpdateError({ reason: "validation" })));
4296
- const updateId = yield* Schema.decodeEffect(IdempotencyKey)(`tool:${context.runId}:${call.toolCallId}`).pipe(Effect.mapError(() => new UpdateError({ reason: "validation" })));
4308
+ const updateHandlers = agent.definition.updates === void 0 || nativeUpdateTool === void 0 ? Context.empty() : yield* Toolkit.make(nativeUpdateTool).toHandlers({ emit_update: Effect.fnUntraced(function* (parameters, call) {
4309
+ if (call.toolCallId === void 0) return yield* UpdateError.make({ reason: "unavailable" });
4310
+ const decoded = yield* Schema.decodeUnknownEffect(Schema.Struct({ value: Schema.Unknown }))(parameters).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4311
+ const value = yield* Schema.encodeUnknownEffect(agent.definition.updates)(decoded.value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Json)), Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4312
+ const updateId = yield* Schema.decodeEffect(IdempotencyKey)(`tool:${context.runId}:${call.toolCallId}`).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4297
4313
  yield* (yield* Emitter).emit({
4298
4314
  target: agent.definition,
4299
4315
  updateId,
@@ -4323,7 +4339,7 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4323
4339
  contextTokenLimit,
4324
4340
  remainingTokens: contextTokenLimit === null ? null : Math.max(0, contextTokenLimit - estimatedTokens)
4325
4341
  });
4326
- }) }), Context.merge(updateHandlers), Context.add(Emitter, { emit: () => Effect.fail(new UpdateError({ reason: "unavailable" })) }), Context.add(CurrentToolCatalog, { entries: [] }), Context.add(RunToolVisibility, visibility), Context.add(RunEventSink, closedRunEventSink), Context.add(DurableStep, closedDurableStep), Context.add(SubagentDurability, closedSubagentDurability), Context.add(SubagentHost, SubagentHost.unavailable), Context.add(MessagingHost, MessagingHost.unavailable), Context.add(CurrentSubagentAuthority, options.subagentGrant === void 0 ? void 0 : {
4342
+ }) }), Context.merge(updateHandlers), Context.add(Emitter, { emit: () => Effect.fail(UpdateError.make({ reason: "unavailable" })) }), Context.add(CurrentToolCatalog, { entries: [] }), Context.add(RunToolVisibility, visibility), Context.add(RunEventSink, closedRunEventSink), Context.add(DurableStep, closedDurableStep), Context.add(SubagentDurability, closedSubagentDurability), Context.add(SubagentHost, SubagentHost.unavailable), Context.add(MessagingHost, MessagingHost.unavailable), Context.add(CurrentSubagentAuthority, options.subagentGrant === void 0 ? void 0 : {
4327
4343
  grant: options.subagentGrant,
4328
4344
  depth: options.delegationDepth ?? options.parentLink?.depth ?? 0
4329
4345
  }), Context.add(ToolBroker, closedToolBroker));
@@ -4351,7 +4367,7 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4351
4367
  const events = (model === void 0 ? finalized : Effect.gen(function* () {
4352
4368
  const services = yield* beforeExecutionDeadline(Layer.build(Layer.fresh(model)), durationDeadlineMillis, durationFailure);
4353
4369
  return yield* Effect.provide(finalized, services);
4354
- })).pipe(Effect.provide(ToolSpanTelemetry.layer.pipe(Layer.provideMerge(programmaticAuthorization))));
4370
+ })).pipe(Effect.provideServiceEffect(ToolSpanTelemetry, ToolSpanTelemetry.make), Effect.provideServiceEffect(ProgrammaticToolAuthorization, programmaticAuthorization));
4355
4371
  return Effect.scoped(events).pipe(Effect.flatMap((terminal) => Effect.gen(function* () {
4356
4372
  if (onCompleted !== void 0) yield* onCompleted(terminal);
4357
4373
  if (retained !== void 0) yield* retained.commit(terminal);
@@ -4470,13 +4486,13 @@ const executeWithUsageAccountingUnknown = (agent, input, options) => executeWith
4470
4486
  /** Accept schema-encoded input, retaining runtime validation. Use streamUnknown for external data. */
4471
4487
  const stream = (agent, input, options) => streamUnknown(agent, input, options);
4472
4488
  function runUnknown(agent, input, options = {}) {
4473
- const program = "definition" in agent ? agent : { definition: agent };
4489
+ const program = { definition: "definition" in agent ? agent.definition : agent };
4474
4490
  return runProgram(program, (onCompleted) => executeWithCompletion(agent, input, options, onCompleted).pipe(Effect.provide(Layer.mergeAll(ModelUsageAccounting.layerEphemeral, AgentUpdateAcceptance.layerEphemeral))));
4475
4491
  }
4476
4492
  /** Accept schema-encoded input, retaining runtime validation. Use runUnknown for external data. */
4477
4493
  const run = (agent, input, options) => runUnknown(agent, input, options);
4478
4494
  function startUnknown(agent, input, options = {}) {
4479
- const program = "definition" in agent ? agent : { definition: agent };
4495
+ const program = { definition: "definition" in agent ? agent.definition : agent };
4480
4496
  return startProgram(program, (executionOptions, onCompleted, onUsage, publish) => executeWithCompletion(agent, input, executionOptions, onCompleted, onUsage, publish).pipe(Effect.provide(Layer.mergeAll(ModelUsageAccounting.layerEphemeral, AgentUpdateAcceptance.layerEphemeral))), options);
4481
4497
  }
4482
4498
  /** Accept schema-encoded input, retaining runtime validation. Use startUnknown for external data. */
@@ -4607,11 +4623,12 @@ const makeToolBrokerService = Effect.fnUntraced(function* (binding) {
4607
4623
  permits: Semaphore.makeUnsafe(1)
4608
4624
  };
4609
4625
  return {
4610
- service: { openPass: (toolkit, passOptions) => Effect.gen(function* () {
4626
+ service: { openPass: Effect.fnUntraced(function* (toolkit, passOptions) {
4611
4627
  const inheritedAuthority = yield* CurrentSubagentAuthority;
4612
4628
  if (lifecycle.closed) return yield* ToolBrokerUnavailableError.make({ message: "The outer Tool Call for this broker has already settled" });
4613
4629
  if (passOptions === void 0 || !Number.isSafeInteger(passOptions.maxResultBytes) || passOptions.maxResultBytes <= 0) return yield* ToolBrokerConfigurationError.make({ message: `maxResultBytes must be a positive safe integer; received ${String(passOptions?.maxResultBytes)}` });
4614
4630
  const handlerServices = yield* Effect.context();
4631
+ const handle = toolkit.handle;
4615
4632
  const concurrency = passOptions.concurrency ?? 4;
4616
4633
  if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64) return yield* ToolBrokerConfigurationError.make({ message: "concurrency must be an integer between 1 and 64" });
4617
4634
  const permits = yield* Semaphore.make(concurrency);
@@ -4740,7 +4757,7 @@ const makeToolBrokerService = Effect.fnUntraced(function* (binding) {
4740
4757
  yield* Metric.update(toolCounter, 1);
4741
4758
  let terminal;
4742
4759
  let resultAfterTerminal = false;
4743
- const handlerFailed = yield* Stream.unwrap(toolSpanTelemetry.isolateToolkitHandle(toolkit.handle(input.toolName, input.encodedArguments, handleId))).pipe(Stream.runForEach((result) => Effect.sync(() => {
4760
+ const handlerFailed = yield* Stream.unwrap(toolSpanTelemetry.isolateToolkitHandle(handle(input.toolName, input.encodedArguments, handleId))).pipe(Stream.runForEach((result) => Effect.sync(() => {
4744
4761
  if (terminal !== void 0) {
4745
4762
  resultAfterTerminal = true;
4746
4763
  return;
@@ -4818,7 +4835,7 @@ const makeToolBrokerService = Effect.fnUntraced(function* (binding) {
4818
4835
  };
4819
4836
  })));
4820
4837
  return yield* observer === void 0 ? recorded : recorded.pipe(Effect.tap(() => failureObservation === void 0 ? Effect.void : deliverToolFailure(observer, failureObservation)));
4821
- }).pipe(Effect.provideContext(handlerServices));
4838
+ }).pipe(Effect.updateContext((current) => Context.merge(current, handlerServices)));
4822
4839
  return {
4823
4840
  snapshot: Effect.sync(() => records.map((record) => ({ ...record }))),
4824
4841
  invoke: (input) => Effect.suspend(() => {
@@ -4890,7 +4907,7 @@ const passthroughDurableStep = () => {
4890
4907
  const provideHookServices = (effect, services) => effect.pipe(Effect.provideContext(services));
4891
4908
  const makeDurableStepService = (toolCallId, hook, hookServices) => {
4892
4909
  const usedNames = /* @__PURE__ */ new Set();
4893
- return { do: (name, output, execute) => Effect.gen(function* () {
4910
+ return { do: Effect.fnUntraced(function* (name, output, execute) {
4894
4911
  if (usedNames.has(name)) return yield* DurableStepError.make({
4895
4912
  toolCallId,
4896
4913
  stepName: name,
@@ -5199,4 +5216,4 @@ var AgentRuntime_exports = /* @__PURE__ */ __exportAll({
5199
5216
  //#endregion
5200
5217
  export { boundedValueFootprint as C, withAttempt as S, startUnknown as _, SubagentDurability as a, streamWithUsageAccountingUnknown as b, decodeFinalOutput as c, projectCompletionFromToolOutput as d, projectCompletionOutput as f, start as g, runUnknown as h, AgentSpawner as i, encodeRunDisposition as l, run as m, AgentChildPending as n, SubagentDurabilityError as o, renderInputPrompt as p, AgentResultSchema as r, ToolCallWaiting as s, AgentRuntime_exports as t, executeWithUsageAccountingUnknown as u, stream as v, withTerminalDefectEvent as x, streamUnknown as y };
5201
5218
 
5202
- //# sourceMappingURL=AgentRuntime-CQ-qcETl.mjs.map
5219
+ //# sourceMappingURL=AgentRuntime-DaDKMasp.mjs.map