@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
@@ -169,6 +169,7 @@ export const prepareModelPrompt = (
169
169
  ): Prompt.Prompt => {
170
170
  if (systemMessagesInHistory) {
171
171
  const content: Array<Prompt.Message> = [];
172
+ let pendingContract = contract;
172
173
  let lastSystem: Prompt.SystemMessage | undefined;
173
174
  let ordered = prompt.content;
174
175
 
@@ -212,29 +213,25 @@ export const prepareModelPrompt = (
212
213
  if (lastSystem !== undefined && sameSystemMessage(lastSystem, message)) continue;
213
214
  lastSystem = message;
214
215
  }
216
+ if (message.role !== "system" && pendingContract !== undefined) {
217
+ content.push(pendingContract);
218
+ pendingContract = undefined;
219
+ }
215
220
  content.push(message);
216
221
  }
217
- if (contract !== undefined) {
218
- const firstConversation = content.findIndex((message) => message.role !== "system");
219
-
220
- content.splice(firstConversation === -1 ? content.length : firstConversation, 0, contract);
221
- }
222
+ if (pendingContract !== undefined) content.push(pendingContract);
222
223
 
223
224
  return Prompt.fromMessages(content);
224
225
  }
225
226
 
226
227
  const systems: Array<Prompt.SystemMessage> = [];
227
- const conversation: Array<Prompt.Message> = [];
228
228
  const seen = new Map<string, Array<Prompt.SystemMessage>>();
229
229
 
230
230
  for (let index = prompt.content.length - 1; index >= 0; index -= 1) {
231
231
  const message = prompt.content[index];
232
232
 
233
233
  if (message === undefined) continue;
234
- if (message.role !== "system") {
235
- conversation.push(message);
236
- continue;
237
- }
234
+ if (message.role !== "system") continue;
238
235
  const variants = seen.get(message.content);
239
236
 
240
237
  if (variants?.some((previous) => sameSystemMessage(previous, message))) continue;
@@ -243,9 +240,12 @@ export const prepareModelPrompt = (
243
240
  systems.push(message);
244
241
  }
245
242
 
246
- return Prompt.fromMessages([
247
- ...systems.reverse(),
248
- ...(contract === undefined ? [] : [contract]),
249
- ...conversation.reverse(),
250
- ]);
243
+ const content: Array<Prompt.Message> = systems.reverse();
244
+
245
+ if (contract !== undefined) content.push(contract);
246
+ for (const message of prompt.content) {
247
+ if (message !== undefined && message.role !== "system") content.push(message);
248
+ }
249
+
250
+ return Prompt.fromMessages(content);
251
251
  };
@@ -35,7 +35,7 @@ const overheads = {
35
35
  };
36
36
 
37
37
  /**
38
- * Capture primitive text and reasoning encodings for the native Schema decoder.
38
+ * Capture complete primitive text and reasoning values for native Schema validation.
39
39
  * Descriptor checks select this optimization; they do not replace the native codec.
40
40
  * Extra fields, accessors, and nonempty metadata use the general ownership path.
41
41
  * No provider object survives, including an empty metadata object's hidden storage.
@@ -95,9 +95,8 @@ export const capturePrimitiveTextPart = (part: unknown, maxBytes: number) => {
95
95
  if (bytes + fixed.source > maxBytes || bytes + fixed.encoded > maxBytes) return undefined;
96
96
  // Never pass the provider's metadata object (or any other object) to the decoder.
97
97
  snapshot.metadata = {};
98
- delete snapshot[brand];
99
98
 
100
- return { encodedPart: snapshot, retainedBytes: bytes + fixed.encoded };
99
+ return { part: snapshot, retainedBytes: bytes + fixed.encoded };
101
100
  } catch {
102
101
  // Reflection may throw for proxies. The general path owns the typed failure.
103
102
  return undefined;
@@ -30,9 +30,8 @@ const makeAttempt = Effect.fnUntraced(function* (
30
30
  ): Effect.fn.Return<Attempt> {
31
31
  const publisher = yield* ProvisionalText.Publisher;
32
32
  const identity = { threadId, submissionId, attemptId };
33
- const active = new Set<ModelHandle>();
34
33
  let closed = false;
35
- let generation = 0;
34
+ let nextGeneration = 0;
36
35
 
37
36
  const offerUnsafe = (event: ProvisionalText.Event): boolean => {
38
37
  try {
@@ -47,7 +46,7 @@ const makeAttempt = Effect.fnUntraced(function* (
47
46
  openModel: (runId, turnId) => {
48
47
  if (closed) return undefined;
49
48
 
50
- const model = { ...identity, runId, turnId, generation: ++generation };
49
+ const generation = ++nextGeneration;
51
50
  let open = true;
52
51
 
53
52
  const handle: ModelHandle = {
@@ -61,28 +60,31 @@ const makeAttempt = Effect.fnUntraced(function* (
61
60
  ? Response.makePart("text-delta", { id: part.id, delta: part.delta })
62
61
  : Response.makePart(part.type, { id: part.id });
63
62
 
64
- return offerUnsafe({ _tag: "Text", ...model, part: detached });
63
+ return offerUnsafe({
64
+ _tag: "Text",
65
+ ...identity,
66
+ runId,
67
+ turnId,
68
+ generation,
69
+ part: detached,
70
+ });
65
71
  },
66
72
  discard: () => {
67
- if (!open) return;
73
+ if (!open || closed) return;
68
74
  handle.close();
69
- offerUnsafe({ _tag: "Discard", ...model });
75
+ offerUnsafe({ _tag: "Discard", ...identity, runId, turnId, generation });
70
76
  },
71
77
  close: () => {
72
78
  if (!open) return;
73
79
  open = false;
74
- active.delete(handle);
75
80
  },
76
81
  };
77
82
 
78
- active.add(handle);
79
-
80
83
  return handle;
81
84
  },
82
85
  close: () => {
83
86
  if (closed) return;
84
87
  closed = true;
85
- for (const handle of active) handle.close();
86
88
  offerUnsafe({ _tag: "AttemptEnded", ...identity });
87
89
  },
88
90
  };
@@ -194,25 +194,29 @@ export const exposureSnapshot = Effect.fnUntraced(function* (
194
194
  if (names.length > limits.maxTools)
195
195
  return yield* invalid("Tool exposure exceeds the configured Tool count bound");
196
196
 
197
+ const declarations: Array<unknown> = [];
198
+
199
+ for (const name of names) {
200
+ const tool = definition.toolkit.tools[name];
201
+
202
+ if (tool === undefined) return yield* invalid("A selected Tool schema cannot be rendered");
203
+ declarations.push(
204
+ yield* Effect.try({
205
+ try: () =>
206
+ Tool.isProviderDefined(tool)
207
+ ? { type: tool.providerName, args: tool.args }
208
+ : {
209
+ name,
210
+ description: Tool.getDescription(tool),
211
+ parameters: Tool.getJsonSchema(tool, { transformer }),
212
+ },
213
+ catch: () => invalid("A selected Tool schema cannot be rendered"),
214
+ }),
215
+ );
216
+ }
217
+
197
218
  const bytes = yield* Effect.try({
198
- try: () =>
199
- utf8ByteLength(
200
- JSON.stringify(
201
- names.map((name) => {
202
- const tool = definition.toolkit.tools[name];
203
-
204
- if (tool === undefined) throw new Error("Selected Tool is unavailable");
205
-
206
- return Tool.isProviderDefined(tool)
207
- ? { type: tool.providerName, args: tool.args }
208
- : {
209
- name,
210
- description: Tool.getDescription(tool),
211
- parameters: Tool.getJsonSchema(tool, { transformer }),
212
- };
213
- }),
214
- ),
215
- ),
219
+ try: () => utf8ByteLength(JSON.stringify(declarations)),
216
220
  catch: () => invalid("A selected Tool schema cannot be rendered"),
217
221
  });
218
222
 
@@ -6,8 +6,8 @@ import * as Context from "effect/Context";
6
6
  import * as Effect from "effect/Effect";
7
7
  import * as ErrorReporter from "effect/ErrorReporter";
8
8
  import * as Exit from "effect/Exit";
9
- import * as Layer from "effect/Layer";
10
9
  import * as Option from "effect/Option";
10
+ import * as Schema from "effect/Schema";
11
11
  import * as Stream from "effect/Stream";
12
12
  import * as Tracer from "effect/Tracer";
13
13
 
@@ -112,12 +112,12 @@ export const restoreToolSpanFailureCause = <E, Original>(
112
112
  const MAX_REPORTED_SPAN_LIFECYCLE_DEFECTS = 16;
113
113
 
114
114
  /** Content-free marker used only to close a delegate that cannot be wrapped safely. */
115
- class ToolSpanLifecycleFailure extends Error {
115
+ class ToolSpanLifecycleFailure extends Schema.TaggedError<ToolSpanLifecycleFailure>()(
116
+ "ToolSpanLifecycleFailure",
117
+ {},
118
+ ) {
116
119
  override readonly name = "ToolSpanLifecycleFailure";
117
-
118
- constructor() {
119
- super("Tool span lifecycle failed");
120
- }
120
+ override readonly message = "Tool span lifecycle failed";
121
121
  }
122
122
 
123
123
  /**
@@ -173,7 +173,7 @@ class IsolatedToolSpan implements Tracer.Span {
173
173
  // attempt even if downstream cancellation or telemetry interruption determines the channel Exit.
174
174
  const exportedExit =
175
175
  this.#terminalOutcome === "failure"
176
- ? Exit.fail(this.#terminalFailure ?? new ToolSpanLifecycleFailure())
176
+ ? Exit.fail(this.#terminalFailure ?? ToolSpanLifecycleFailure.make({}))
177
177
  : this.#terminalOutcome === "success"
178
178
  ? Exit.succeed(undefined)
179
179
  : exit;
@@ -302,6 +302,7 @@ export const makeIsolatedToolTracer = (delegate: Tracer.Tracer): IsolatedToolTra
302
302
  case "Succeeded":
303
303
  return evaluation.value;
304
304
  case "Failed":
305
+ // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.
305
306
  throw evaluation.error;
306
307
  case "Pending": {
307
308
  try {
@@ -312,6 +313,7 @@ export const makeIsolatedToolTracer = (delegate: Tracer.Tracer): IsolatedToolTra
312
313
  return value;
313
314
  } catch (error) {
314
315
  evaluation = { _tag: "Failed", error };
316
+ // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.
315
317
  throw error;
316
318
  }
317
319
  }
@@ -329,6 +331,7 @@ export const makeIsolatedToolTracer = (delegate: Tracer.Tracer): IsolatedToolTra
329
331
 
330
332
  switch (observed._tag) {
331
333
  case "Failed":
334
+ // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.
332
335
  throw observed.error;
333
336
  case "Succeeded":
334
337
  recordDefect(defect);
@@ -344,6 +347,7 @@ export const makeIsolatedToolTracer = (delegate: Tracer.Tracer): IsolatedToolTra
344
347
 
345
348
  switch (observed._tag) {
346
349
  case "Failed":
350
+ // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.
347
351
  throw observed.error;
348
352
  case "Succeeded":
349
353
  return observed.value;
@@ -373,7 +377,7 @@ export const makeIsolatedToolTracer = (delegate: Tracer.Tracer): IsolatedToolTra
373
377
  try {
374
378
  // Allocation succeeded, so best-effort close the host span without attaching the raw
375
379
  // wrapper defect. The start time gives this abandoned measurement a bounded duration.
376
- delegateSpan.end(options.startTime, Exit.fail(new ToolSpanLifecycleFailure()));
380
+ delegateSpan.end(options.startTime, Exit.fail(ToolSpanLifecycleFailure.make({})));
377
381
  } catch (closeDefect) {
378
382
  recordDefect(closeDefect);
379
383
  }
@@ -420,9 +424,9 @@ export class ToolSpanTelemetry extends Context.Service<
420
424
  ToolSpanTelemetry,
421
425
  ToolSpanTelemetryService
422
426
  >()("@effect-agent/engine/ToolSpanTelemetry") {
423
- static readonly layer: Layer.Layer<ToolSpanTelemetry> = Layer.effect(
424
- ToolSpanTelemetry,
425
- Effect.map(Tracer.Tracer, (delegate) =>
427
+ static readonly make: Effect.Effect<ToolSpanTelemetryService> = Effect.map(
428
+ Tracer.Tracer,
429
+ (delegate) =>
426
430
  ToolSpanTelemetry.of({
427
431
  isolateEffectSpanLifecycle: (effect) =>
428
432
  Effect.suspend(() => {
@@ -480,6 +484,5 @@ export class ToolSpanTelemetry extends Context.Service<
480
484
  }),
481
485
  ),
482
486
  }),
483
- ),
484
487
  );
485
488
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"Agent-0WvBWWbM.mjs","names":["S"],"sources":["../src/core/internal/agent-updates.ts","../src/core/Agent.ts"],"sourcesContent":["import * as Tool from \"effect/ai/Tool\";\nimport * as Toolkit from \"effect/ai/Toolkit\";\nimport * as Schema from \"effect/Schema\";\n\nimport { Emitter, UpdateError } from \"../AgentUpdates.ts\";\n\n/** Definition-owned native Tool. Runtime supplies its handler under the same identity. */\nexport const updateTool = <S extends Schema.Top>(schema: S) =>\n Tool.make(\"emit_update\", {\n description:\n \"Emit a structured intermediate update. Success acknowledges acceptance by this Run; \" +\n \"parent delivery and processing are separate. This does not complete the task.\",\n parameters: Schema.Struct({ value: schema }),\n success: Schema.Struct({ emitted: Schema.Literal(true) }),\n failure: UpdateError,\n failureMode: \"return\",\n }).addDependency(Emitter);\n\nexport type UpdateToolkit<\n T extends Toolkit.Any,\n S extends Schema.Top | undefined,\n> = S extends Schema.Top\n ? Toolkit.Toolkit<T[\"tools\"] & { readonly emit_update: ReturnType<typeof updateTool<S>> }>\n : T;\n\nexport const withUpdateTool = (\n toolkit: Toolkit.Any,\n schema: Schema.Top | undefined,\n): Toolkit.Any => {\n if (schema === undefined) return toolkit;\n if (Object.hasOwn(toolkit.tools, \"emit_update\"))\n throw new TypeError(\"emit_update is reserved for Agent updates\");\n\n return Toolkit.make(...Object.values(toolkit.tools), updateTool(schema));\n};\n","import type { Effect, Layer, Option, Schema } from \"effect\";\nimport type { AiError, LanguageModel, Model, Prompt } from \"effect/ai\";\nimport * as Tool from \"effect/ai/Tool\";\nimport * as Toolkit from \"effect/ai/Toolkit\";\nimport * as S from \"effect/Schema\";\n\nimport type {\n AgentInputDecodeError,\n AgentInputError,\n AgentOutputError,\n AgentRunDispositionError,\n} from \"./AgentError.ts\";\nimport { AgentPolicy, type AgentPolicyInput } from \"./AgentPolicy.ts\";\nimport { AgentId } from \"./Identifiers.ts\";\nimport { type UpdateToolkit, withUpdateTool } from \"./internal/agent-updates.ts\";\nimport type { Configuration } from \"./ToolExposure.ts\";\n\n/** Prompt input produced directly or by an Effect that preserves its failure and requirements. */\nexport type InstructionResult<E = never, R = never> =\n | Prompt.RawInput\n | Effect.Effect<Prompt.RawInput, E, R>;\n\n/** Static prompt input or an input-dependent source evaluated once while preparing a run. */\nexport type InstructionSource<Input, E = never, R = never> =\n | Prompt.RawInput\n | ((input: Input) => InstructionResult<E, R>);\n\n/** Definition-owned projection from decoded Agent input to model-visible prompt content. */\nexport type InputPromptSource<Input, E = never, R = never> = (\n input: Input,\n) => InstructionResult<E, R>;\n\n/** Native services needed to execute and identify model calls. */\nexport type ModelServices = LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName;\n\n/**\n * An optional capability on a provided LanguageModel service. The runtime supplies\n * only model-visible task context and eligible Tool descriptions after validating input.\n * The resolver owns retaining one choice per Thread, including across Runs and\n * recovery; it captures client requirements and returns a closed native Layer\n * that the interpreter acquires for the Run. Context hooks may prepare prompts\n * but cannot replace this model through a per-Turn modelCall.\n * Selection failures remain AiError values and all selector/client services stay in R.\n */\nexport interface ModelResolver extends LanguageModel.LanguageModel {\n readonly resolve: (request: {\n readonly threadId: string;\n readonly state: Schema.JsonObject;\n }) => Effect.Effect<Layer.Layer<ModelServices>, AiError.AiError>;\n}\n\n/** Detect the deferred resolver capability on a trusted, host-provided model service. */\nexport const isModelResolver = (model: LanguageModel.LanguageModel): model is ModelResolver =>\n \"resolve\" in model && typeof model.resolve === \"function\";\n\n/** Accepts native model Layers that provide generation and model identity. */\nexport type NativeModel<ModelValue> =\n ModelValue extends Layer.Layer<infer Provides, never, infer _Requires>\n ? ModelServices extends Provides\n ? ModelValue\n : never\n : never;\n\n/** Definition-owned boundary for selecting and validating an application run disposition. */\nexport interface RunDispositionDeclaration<Output, DispositionSchema extends Schema.Top> {\n /**\n * Opt background workers into one retained assignment. The encoded disposition must be\n * Worker.AssignmentDisposition: completed seals the worker, waiting leaves it steerable.\n * Failures and exhausted Runs seal as failed; aborting an active Run seals as cancelled.\n * The worker origin retains this choice. Omission preserves reusable workers.\n */\n readonly workerLifecycle?: \"assignment\" | undefined;\n /** Canonical Schema used to validate and encode the selected disposition. */\n readonly schema: DispositionSchema;\n /** Pure selection from decoded output. `undefined` declares none, except for assignments. */\n readonly fromOutput: (output: Output) => unknown;\n}\n\n/** Values available to a Definition-owned completion Tool projector after canonical decoding. */\nexport interface CompletionProjectionInput<Parameters = unknown, Result = unknown> {\n readonly parameters: Parameters;\n readonly result: Result;\n}\n\n/**\n * One application Tool whose successful result can complete its owning Agent when it is the\n * only application call. Provider-executed calls may accompany it only with terminal results.\n * Mixed, wholly unexecuted application batches are rejected with failed Tool results so the\n * model can correct them within ordinary Run budgets; completed provider results are retained.\n * Missing provider results and invalid pending resumed batches fail closed. The completion\n * designation never permits side-effect replay.\n */\nexport interface CompletionToolDeclaration<\n Parameters = unknown,\n Result = unknown,\n Output = unknown,\n> {\n readonly tool: string;\n /** Require native Tool use on every model Turn and this Tool for final completion. */\n readonly required?: boolean | undefined;\n /**\n * Pure, deterministic projection: recovery may reevaluate a recorded Tool result before\n * RunCompleted commits. Once committed, that stored output wins across later code changes.\n */\n readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Output;\n}\n\ntype CompletionToolFor<ToolkitValue extends Toolkit.Any, Output> = {\n readonly [Name in keyof ToolkitValue[\"tools\"] & string]: CompletionToolDeclaration<\n Tool.Parameters<ToolkitValue[\"tools\"][Name]>,\n Tool.Success<ToolkitValue[\"tools\"][Name]>,\n Output\n > & { readonly tool: Name };\n}[keyof ToolkitValue[\"tools\"] & string];\n\n/**\n * An ordinary action Tool whose canonical success may satisfy the whole request.\n * Projectors must be pure and deterministic: recovery re-evaluates them. None preserves\n * ordinary continuation; Some is validated as the Agent output. These Tools must be the sole\n * application call; terminal provider results may accompany them. They never receive the\n * required completion Tool's exhaustion allowance.\n */\nexport interface CompletionFromToolDeclaration<\n Parameters = unknown,\n Result = unknown,\n Output = unknown,\n> {\n readonly tool: string;\n readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Option.Option<Output>;\n}\n\ntype CompletionFromToolFor<ToolkitValue extends Toolkit.Any, Output> = {\n readonly [Name in keyof ToolkitValue[\"tools\"] & string]: CompletionFromToolDeclaration<\n Tool.Parameters<ToolkitValue[\"tools\"][Name]>,\n Tool.Success<ToolkitValue[\"tools\"][Name]>,\n Output\n > & { readonly tool: Name };\n}[keyof ToolkitValue[\"tools\"] & string];\n\n/** Immutable, model-agnostic schemas, behavior, tools, and bounds for an agent. */\nexport interface Definition<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n ToolkitValue extends Toolkit.Any,\n RunDispositionValue = undefined,\n InputPromptValue = undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n> {\n /** Stable agent identity; changing it creates a distinct definition identity. */\n readonly id: AgentId;\n /** Canonical Schema for intermediate updates emitted by this Agent. */\n readonly updates?: UpdatesSchema;\n /** Canonical schema used to decode and encode run input. */\n readonly input: InputSchema;\n /** Canonical schema used to decode the final model output. */\n readonly output: OutputSchema;\n /**\n * Evaluated once while preparing each Run. OpenAI, xAI and native adapters advertising support\n * preserve chronological system messages, omitting exact repeats only when no distinct system\n * instruction intervenes. The actual selected model determines support on each call. Other\n * adapters group systems first and keep the last exact repeat, including provider options;\n * Anthropic requires an upstream adapter with mid-conversation system-message support.\n * Stored history is unchanged.\n */\n readonly instructions: Instructions;\n /**\n * Optional projection from decoded input to model-visible native Effect AI prompt content.\n * This controls disclosure only: durable admission retains the complete input and Tool\n * authorization receives it. A projection failure never falls back to sending full input.\n */\n readonly inputPrompt?: InputPromptValue | undefined;\n /** Native Effect AI toolkit whose failures and requirements remain visible. */\n readonly toolkit: ToolkitValue;\n readonly toolExposure?: Configuration | undefined;\n /** Finite execution bounds enforced by the runtime. */\n readonly policy: AgentPolicy;\n /** Explicit policy fields, retained so delegated runs can inherit omitted fields. */\n readonly policyOverrides?: Partial<AgentPolicyInput> | undefined;\n /** Optional successful Tool result that projects directly to the Agent output and settles. */\n readonly completion?: CompletionToolDeclaration | undefined;\n readonly completionFromTools?: ReadonlyArray<CompletionFromToolDeclaration> | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\n/** Options for a model-agnostic agent definition. */\nexport interface DefinitionOptions<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n RunDispositionValue extends\n | RunDispositionDeclaration<OutputSchema[\"Type\"], Schema.Top>\n | undefined = undefined,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined =\n undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n> {\n readonly updates?: UpdatesSchema;\n readonly input: InputSchema;\n readonly output: OutputSchema;\n readonly instructions: Instructions;\n readonly inputPrompt?: InputPromptValue | undefined;\n readonly toolkit: ToolkitValue;\n readonly toolExposure?: Configuration | undefined;\n readonly policy?: Partial<AgentPolicyInput> | undefined;\n readonly completion?: CompletionToolFor<ToolkitValue, OutputSchema[\"Type\"]> | undefined;\n readonly completionFromTools?:\n | ReadonlyArray<CompletionFromToolFor<ToolkitValue, OutputSchema[\"Type\"]>>\n | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\ntype AnyDefinitionShape = Definition<\n Schema.Top,\n Schema.Top,\n unknown,\n Toolkit.Any,\n RunDispositionDeclaration<never, Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n>;\n\n/** Immutable pairing of an agent definition with a native model Layer or thread resolver. */\nexport interface Binding<DefinitionValue extends AnyDefinitionShape, ModelValue> {\n readonly definition: DefinitionValue;\n readonly model: NativeModel<ModelValue>;\n}\n\ntype InstructionEffect<Instructions, Input> = Instructions extends (input: Input) => infer Result\n ? Result\n : Instructions;\n\ntype InputPromptEffect<InputPrompt, Input> = InputPrompt extends (input: Input) => infer Result\n ? Result\n : never;\n\ntype EffectError<Value> =\n Value extends Effect.Effect<infer _Success, infer Error, infer _Services> ? Error : never;\n\ntype EffectServices<Value> =\n Value extends Effect.Effect<infer _Success, infer _Error, infer Services> ? Services : never;\n\ntype ModelRequirements<Value> =\n Value extends Layer.Layer<infer _Provides, infer _Error, infer Services> ? Services : never;\n\n/** Constructors and type projections for definitions and runnable model bindings. */\n\n/** Type-erased definition used at generic framework boundaries. */\nexport type AnyDefinition = AnyDefinitionShape;\n\n/** Read-only interpreter program or binding used at inspection and projection boundaries. */\nexport interface Any {\n readonly definition: AnyDefinition;\n readonly model?: unknown;\n}\n\n/** Native Tool configuration for inspection; it does not predict an invocation's outcome. */\nexport const ToolInspection = S.Struct({\n name: S.String,\n failureMode: S.Literals([\"error\", \"return\"]),\n /** False for provider-executed Tools, whose results do not pass through local handlers. */\n requiresHandler: S.Boolean,\n});\n\nexport type ToolInspection = typeof ToolInspection.Type;\n\n/**\n * Inspect registered native Tools in declaration order without acquiring handlers or a Model.\n * This is the full Definition toolkit, before run-specific visibility or exposure filtering.\n * `failureMode` is Effect AI's configured mode, including its `\"error\"` default. Handler-level\n * recovery, programmatic invocation and Subagent containment can change where failures go;\n * consult execution diagnostics for the actual route. No arguments, results or services are read.\n */\nexport const inspectTools = (agent: AnyDefinition | Any): ReadonlyArray<ToolInspection> => {\n const definition = \"definition\" in agent ? agent.definition : agent;\n\n return Object.values(definition.toolkit.tools).map((tool) =>\n ToolInspection.make({\n name: tool.name,\n failureMode: tool.failureMode,\n requiresHandler: !Tool.isProviderDefined(tool) || tool.requiresHandler,\n }),\n );\n};\n\ntype DefinitionOf<AgentValue extends AnyDefinition | Any> = AgentValue extends {\n readonly definition: infer DefinitionValue extends AnyDefinition;\n}\n ? DefinitionValue\n : AgentValue;\n\ntype RunDispositionSchemaOf<DefinitionValue extends AnyDefinition> = [\n Exclude<DefinitionValue[\"runDisposition\"], undefined>,\n] extends [never]\n ? never\n : Exclude<DefinitionValue[\"runDisposition\"], undefined> extends RunDispositionDeclaration<\n never,\n infer DispositionSchema\n >\n ? DispositionSchema\n : never;\n\n/** Literal Agent ID, retained by Agent.make. */\nexport type Name<A extends AnyDefinition | Any> = DefinitionOf<A>[\"id\"] extends AgentId &\n (infer N extends string)\n ? N\n : string;\n\n/** Declared update Schema, or never for Agents without updates. */\nexport type UpdatesSchema<A extends AnyDefinition | Any> = Exclude<\n DefinitionOf<A>[\"updates\"],\n undefined\n>;\n\n/** Decoded intermediate update value. */\nexport type Update<A extends AnyDefinition | Any> = UpdatesSchema<A>[\"Type\"];\n\n/** Decoded input type of a definition or binding. */\nexport type Input<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"input\"][\"Type\"];\n\n/** Encoded input accepted by the primary execution operations. */\nexport type EncodedInput<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"input\"][\"Encoded\"];\n\n/** Decoded output type of a definition or binding. */\nexport type Output<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"output\"][\"Type\"];\n\n/** Input Schema carried by a definition or binding. */\nexport type InputSchema<AgentValue extends AnyDefinition | Any> = DefinitionOf<AgentValue>[\"input\"];\n\n/** Output Schema carried by a definition or binding. */\nexport type OutputSchema<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"output\"];\n\n/** Application run-disposition Schema carried by a definition or binding, or `never`. */\nexport type RunDispositionSchema<AgentValue extends AnyDefinition | Any> = RunDispositionSchemaOf<\n DefinitionOf<AgentValue>\n>;\n\n/** Decoded application run disposition declared by a definition or binding. */\nexport type RunDisposition<AgentValue extends AnyDefinition | Any> = [\n RunDispositionSchema<AgentValue>,\n] extends [never]\n ? never\n : RunDispositionSchema<AgentValue>[\"Type\"];\n\n/** Validation failure admitted only by definitions that declare a run disposition. */\nexport type RunDispositionFailure<AgentValue extends AnyDefinition | Any> = [\n RunDispositionSchemaOf<DefinitionOf<AgentValue>>,\n] extends [never]\n ? never\n : AgentRunDispositionError;\n\n/** Effect AI tool map carried by a definition or binding. */\nexport type Tools<AgentValue extends AnyDefinition | Any> = Toolkit.Tools<\n DefinitionOf<AgentValue>[\"toolkit\"]\n>;\n\ntype ApplicationTools<A extends AnyDefinition> = [UpdatesSchema<A>] extends [never]\n ? Tools<A>\n : Omit<Tools<A>, \"emit_update\">;\n\ntype ToolMapValues<ToolMap extends Record<string, Tool.Any>> = ToolMap extends unknown\n ? ToolMap[keyof ToolMap]\n : never;\n\n/** All possible tools, including keys present in only one definition or binding branch. */\nexport type ToolUnion<AgentValue extends AnyDefinition | Any> = ToolMapValues<Tools<AgentValue>>;\n\n/** Instruction, tool-handler, and Schema services required before a Model is bound. */\nexport type DefinitionRequirements<DefinitionValue extends AnyDefinition> =\n DefinitionValue extends unknown\n ?\n | EffectServices<InstructionEffect<DefinitionValue[\"instructions\"], Input<DefinitionValue>>>\n | EffectServices<InputPromptEffect<DefinitionValue[\"inputPrompt\"], Input<DefinitionValue>>>\n | Tool.HandlersFor<ApplicationTools<DefinitionValue>>\n | Tool.HandlerServices<ToolMapValues<ApplicationTools<DefinitionValue>>>\n // The interpreter canonically re-encodes decoded Tool parameters before recording them.\n | Tool.ParametersSchema<ToolUnion<DefinitionValue>>[\"EncodingServices\"]\n | Tool.SuccessSchema<ToolUnion<DefinitionValue>>[\"DecodingServices\"]\n | DefinitionValue[\"input\"][\"DecodingServices\"]\n | DefinitionValue[\"input\"][\"EncodingServices\"]\n | DefinitionValue[\"output\"][\"DecodingServices\"]\n | DefinitionValue[\"output\"][\"EncodingServices\"]\n | UpdatesSchema<DefinitionValue>[\"DecodingServices\"]\n | UpdatesSchema<DefinitionValue>[\"EncodingServices\"]\n | RunDispositionSchemaOf<DefinitionValue>[\"DecodingServices\"]\n | RunDispositionSchemaOf<DefinitionValue>[\"EncodingServices\"]\n : never;\n\n/** Definition services plus native model services, or a binding's model Layer requirements. */\nexport type Requirements<AgentValue extends AnyDefinition | Any> =\n | DefinitionRequirements<DefinitionOf<AgentValue>>\n | (AgentValue extends { readonly model: infer ModelValue }\n ? ModelRequirements<ModelValue>\n : ModelServices);\n\n// Distribute after unwrapping bindings too: withModel may itself contain a definition union.\ntype DefinitionFailure<DefinitionValue extends AnyDefinition> = DefinitionValue extends unknown\n ?\n | EffectError<InstructionEffect<DefinitionValue[\"instructions\"], Input<DefinitionValue>>>\n | EffectError<InputPromptEffect<DefinitionValue[\"inputPrompt\"], Input<DefinitionValue>>>\n | Tool.HandlerError<ToolUnion<DefinitionValue>>\n : never;\n\n/** Failures from every possible definition, preserving each branch's instruction input type. */\nexport type Failure<AgentValue extends AnyDefinition | Any> =\n | DefinitionFailure<DefinitionOf<AgentValue>>\n | AiError.AiError\n | AgentInputDecodeError\n | AgentInputError\n | AgentOutputError\n | RunDispositionFailure<AgentValue>;\n\n/** Validate an agent ID and return a shallowly frozen, model-agnostic definition. */\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n DispositionSchema extends Schema.Top,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly runDisposition: RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>;\n readonly inputPrompt: InputPromptValue;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n InputPromptValue,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n DispositionSchema extends Schema.Top,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n undefined,\n UpdatesSchema\n > & {\n readonly runDisposition: RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>;\n readonly inputPrompt?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n undefined,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n undefined,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly inputPrompt: InputPromptValue;\n readonly runDisposition?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n undefined,\n InputPromptValue,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n undefined,\n undefined,\n UpdatesSchema\n > & {\n readonly inputPrompt?: undefined;\n readonly runDisposition?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n undefined,\n undefined,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make(\n id: string,\n options: {\n readonly updates?: Schema.Top | undefined;\n readonly input: Schema.Top;\n readonly output: Schema.Top;\n readonly instructions: unknown;\n readonly inputPrompt?: unknown;\n readonly toolkit: Toolkit.Any;\n readonly toolExposure?: Configuration | undefined;\n readonly policy?: Partial<AgentPolicyInput> | undefined;\n readonly completion?: CompletionToolDeclaration | undefined;\n readonly completionFromTools?: ReadonlyArray<CompletionFromToolDeclaration> | undefined;\n readonly runDisposition?: RunDispositionDeclaration<never, Schema.Top> | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n },\n): AnyDefinition {\n const completionNames = new Set<string>();\n\n for (const declaration of options.completionFromTools ?? []) {\n if (declaration.tool === options.completion?.tool || completionNames.has(declaration.tool)) {\n throw new Error(`Tool ${declaration.tool} has more than one completion declaration`);\n }\n if (!Object.hasOwn(options.toolkit.tools, declaration.tool)) {\n throw new Error(`Unknown completion Tool ${declaration.tool}`);\n }\n completionNames.add(declaration.tool);\n }\n\n const tools = Object.values(options.toolkit.tools);\n\n const readonlyTools = tools.map((tool) =>\n Tool.isProviderDefined(tool) &&\n !tool.requiresHandler &&\n [\"web_search\", \"web_search_preview\", \"file_search\"].includes(tool.providerName)\n ? tool.annotate(Tool.Readonly, true)\n : tool,\n );\n\n const toolkit = readonlyTools.some((tool, index) => tool !== tools[index])\n ? Toolkit.make(...readonlyTools)\n : options.toolkit;\n\n return Object.freeze({\n ...options,\n toolkit: withUpdateTool(toolkit, options.updates),\n policy: AgentPolicy.resolve(options.policy),\n policyOverrides: Object.freeze({ ...options.policy }),\n toolExposure:\n options.toolExposure === undefined\n ? undefined\n : Object.freeze({\n ...options.toolExposure,\n initialToolNames: Object.freeze([...(options.toolExposure.initialToolNames ?? [])]),\n }),\n id: S.decodeSync(AgentId)(id),\n metadata: options.metadata === undefined ? undefined : Object.freeze({ ...options.metadata }),\n completion:\n options.completion === undefined ? undefined : Object.freeze({ ...options.completion }),\n completionFromTools:\n options.completionFromTools === undefined\n ? undefined\n : Object.freeze(\n options.completionFromTools.map((declaration) => Object.freeze({ ...declaration })),\n ),\n runDisposition:\n options.runDisposition === undefined\n ? undefined\n : Object.freeze({ ...options.runDisposition }),\n });\n}\n\n/** Bind a native model or thread resolver without acquiring or hiding its requirements. */\nexport const withModel = <DefinitionValue extends AnyDefinition, ModelValue>(\n definition: DefinitionValue,\n model: NativeModel<ModelValue>,\n): Binding<DefinitionValue, ModelValue> =>\n Object.freeze({\n definition,\n model,\n });\n"],"mappings":";;;;;;;;;AAOA,MAAa,cAAoC,WAC/C,KAAK,KAAK,eAAe;CACvB,aACE;CAEF,YAAY,OAAO,OAAO,EAAE,OAAO,OAAO,CAAC;CAC3C,SAAS,OAAO,OAAO,EAAE,SAAS,OAAO,QAAQ,IAAI,EAAE,CAAC;CACxD,SAAS;CACT,aAAa;AACf,CAAC,CAAC,CAAC,cAAc,OAAO;AAS1B,MAAa,kBACX,SACA,WACgB;CAChB,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,IAAI,OAAO,OAAO,QAAQ,OAAO,aAAa,GAC5C,MAAM,IAAI,UAAU,2CAA2C;CAEjE,OAAO,QAAQ,KAAK,GAAG,OAAO,OAAO,QAAQ,KAAK,GAAG,WAAW,MAAM,CAAC;AACzE;;;;;;;;;;;ACkBA,MAAa,mBAAmB,UAC9B,aAAa,SAAS,OAAO,MAAM,YAAY;;AAiNjD,MAAa,iBAAiBA,OAAE,OAAO;CACrC,MAAMA,OAAE;CACR,aAAaA,OAAE,SAAS,CAAC,SAAS,QAAQ,CAAC;;CAE3C,iBAAiBA,OAAE;AACrB,CAAC;;;;;;;;AAWD,MAAa,gBAAgB,UAA8D;CACzF,MAAM,aAAa,gBAAgB,QAAQ,MAAM,aAAa;CAE9D,OAAO,OAAO,OAAO,WAAW,QAAQ,KAAK,CAAC,CAAC,KAAK,SAClD,eAAe,KAAK;EAClB,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,iBAAiB,CAAC,KAAK,kBAAkB,IAAI,KAAK,KAAK;CACzD,CAAC,CACH;AACF;AAsQA,SAAgB,KACd,IACA,SAee;CACf,MAAM,kCAAkB,IAAI,IAAY;CAExC,KAAK,MAAM,eAAe,QAAQ,uBAAuB,CAAC,GAAG;EAC3D,IAAI,YAAY,SAAS,QAAQ,YAAY,QAAQ,gBAAgB,IAAI,YAAY,IAAI,GACvF,MAAM,IAAI,MAAM,QAAQ,YAAY,KAAK,0CAA0C;EAErF,IAAI,CAAC,OAAO,OAAO,QAAQ,QAAQ,OAAO,YAAY,IAAI,GACxD,MAAM,IAAI,MAAM,2BAA2B,YAAY,MAAM;EAE/D,gBAAgB,IAAI,YAAY,IAAI;CACtC;CAEA,MAAM,QAAQ,OAAO,OAAO,QAAQ,QAAQ,KAAK;CAEjD,MAAM,gBAAgB,MAAM,KAAK,SAC/B,KAAK,kBAAkB,IAAI,KAC3B,CAAC,KAAK,mBACN;EAAC;EAAc;EAAsB;CAAa,CAAC,CAAC,SAAS,KAAK,YAAY,IAC1E,KAAK,SAAS,KAAK,UAAU,IAAI,IACjC,IACN;CAEA,MAAM,UAAU,cAAc,MAAM,MAAM,UAAU,SAAS,MAAM,MAAM,IACrE,QAAQ,KAAK,GAAG,aAAa,IAC7B,QAAQ;CAEZ,OAAO,OAAO,OAAO;EACnB,GAAG;EACH,SAAS,eAAe,SAAS,QAAQ,OAAO;EAChD,QAAQ,YAAY,QAAQ,QAAQ,MAAM;EAC1C,iBAAiB,OAAO,OAAO,EAAE,GAAG,QAAQ,OAAO,CAAC;EACpD,cACE,QAAQ,iBAAiB,KAAA,IACrB,KAAA,IACA,OAAO,OAAO;GACZ,GAAG,QAAQ;GACX,kBAAkB,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,oBAAoB,CAAC,CAAE,CAAC;EACpF,CAAC;EACP,IAAIA,OAAE,WAAW,OAAO,CAAC,CAAC,EAAE;EAC5B,UAAU,QAAQ,aAAa,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,EAAE,GAAG,QAAQ,SAAS,CAAC;EAC5F,YACE,QAAQ,eAAe,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,EAAE,GAAG,QAAQ,WAAW,CAAC;EACxF,qBACE,QAAQ,wBAAwB,KAAA,IAC5B,KAAA,IACA,OAAO,OACL,QAAQ,oBAAoB,KAAK,gBAAgB,OAAO,OAAO,EAAE,GAAG,YAAY,CAAC,CAAC,CACpF;EACN,gBACE,QAAQ,mBAAmB,KAAA,IACvB,KAAA,IACA,OAAO,OAAO,EAAE,GAAG,QAAQ,eAAe,CAAC;CACnD,CAAC;AACH;;AAGA,MAAa,aACX,YACA,UAEA,OAAO,OAAO;CACZ;CACA;AACF,CAAC"}