@yielded/agent 0.1.0-beta.172 → 0.1.0-beta.174

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 (226) hide show
  1. package/dist/{Admin-BX9ns28E.d.mts → Admin-BHmp2V9p.d.mts} +25 -16
  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-CQ-qcETl.mjs → AgentRuntime-B6qZlD3f.mjs} +199 -191
  6. package/dist/AgentRuntime-B6qZlD3f.mjs.map +1 -0
  7. package/dist/{AgentRuntime-BfP14534.d.mts → AgentRuntime-BD3ZHAMq.d.mts} +10 -10
  8. package/dist/{Digest-DCuPlhNk.mjs → Digest-EpeqWEdv.mjs} +41 -14
  9. package/dist/Digest-EpeqWEdv.mjs.map +1 -0
  10. package/dist/{DurableAgentRuntime-BAmSkWYr.mjs → DurableAgentRuntime-CBBjRNJN.mjs} +1447 -1424
  11. package/dist/DurableAgentRuntime-CBBjRNJN.mjs.map +1 -0
  12. package/dist/{EventSource-BwliwQz9.d.mts → EventSource-C9aaJaXT.d.mts} +2 -2
  13. package/dist/{MessageDelivery-CeSDfHZa.d.mts → MessageDelivery-BGDm-c46.d.mts} +4 -4
  14. package/dist/{Messaging-C_6OOg_s.d.mts → Messaging-SVu6rWV8.d.mts} +12 -6
  15. package/dist/{MessagingHost-B8oKM7AC.d.mts → MessagingHost-C6SOAcoG.d.mts} +2 -2
  16. package/dist/{Output-Dsx6k52t.d.mts → Output-CRamN1Fy.d.mts} +2 -2
  17. package/dist/{PreparedInputAdmission-CxSJSiTl.d.mts → PreparedInputAdmission-BvDqlgiP.d.mts} +3 -3
  18. package/dist/{RunContinuation-DHYNAQFi.mjs → RunContinuation-4ZATcVLB.mjs} +113 -56
  19. package/dist/RunContinuation-4ZATcVLB.mjs.map +1 -0
  20. package/dist/{RunContinuation-FHM7XPjq.d.mts → RunContinuation-CTJ1jGrO.d.mts} +6 -6
  21. package/dist/{RunJournal-kfKVxJj7.mjs → RunJournal-CNZqA3Ge.mjs} +33 -5
  22. package/dist/RunJournal-CNZqA3Ge.mjs.map +1 -0
  23. package/dist/{RunOptions-D8zxFIrZ.d.mts → RunOptions-Be77lKVZ.d.mts} +2 -2
  24. package/dist/{RunStorage-uqPxps09.mjs → RunStorage-BHjuuERI.mjs} +9 -6
  25. package/dist/RunStorage-BHjuuERI.mjs.map +1 -0
  26. package/dist/{Scheduling-CVyfXlBR.mjs → Scheduling-NG8slKdI.mjs} +11 -11
  27. package/dist/Scheduling-NG8slKdI.mjs.map +1 -0
  28. package/dist/{Subagent-vpffemql.mjs → Subagent-CTIpnzlB.mjs} +53 -40
  29. package/dist/Subagent-CTIpnzlB.mjs.map +1 -0
  30. package/dist/{Subagent-E6tvd7-k.d.mts → Subagent-DKhZA72u.d.mts} +19 -8
  31. package/dist/{SubagentHost-B6w2m-SI.d.mts → SubagentHost-D1xBgn9g.d.mts} +2 -2
  32. package/dist/{Subscription-DONig54Q.d.mts → Subscription-BNg9VCRl.d.mts} +2 -2
  33. package/dist/{SubscriptionInput-mJIRxWJM.d.mts → SubscriptionInput-BUoXv-_K.d.mts} +2 -2
  34. package/dist/{ThreadImport-CoQTZywm.d.mts → ThreadImport-CMgzttvr.d.mts} +43 -43
  35. package/dist/{ThreadImport-DckUMEqJ.mjs → ThreadImport-CodYoJoa.mjs} +7 -7
  36. package/dist/ThreadImport-CodYoJoa.mjs.map +1 -0
  37. package/dist/{ThreadStore-CEekRa80.mjs → ThreadStore-59uDGXul.mjs} +163 -84
  38. package/dist/ThreadStore-59uDGXul.mjs.map +1 -0
  39. package/dist/{ThreadTransfer-B4gTQLIl.mjs → ThreadTransfer-3jigUl3g.mjs} +3 -3
  40. package/dist/{ThreadTransfer-B4gTQLIl.mjs.map → ThreadTransfer-3jigUl3g.mjs.map} +1 -1
  41. package/dist/{WorkerAdmission-DFVbbVh2.mjs → WorkerAdmission-DDYJdOsU.mjs} +4 -4
  42. package/dist/{WorkerAdmission-DFVbbVh2.mjs.map → WorkerAdmission-DDYJdOsU.mjs.map} +1 -1
  43. package/dist/{agent-registration-ByMZ_cK5.mjs → agent-registration-DRbyhAu-.mjs} +69 -56
  44. package/dist/agent-registration-DRbyhAu-.mjs.map +1 -0
  45. package/dist/capabilities/Approval.mjs +2 -2
  46. package/dist/capabilities/Approval.mjs.map +1 -1
  47. package/dist/capabilities/BrowserUse.d.mts +102 -1867
  48. package/dist/capabilities/BrowserUse.mjs +74 -798
  49. package/dist/capabilities/BrowserUse.mjs.map +1 -1
  50. package/dist/capabilities/Budget.mjs +3 -1
  51. package/dist/capabilities/Budget.mjs.map +1 -1
  52. package/dist/capabilities/CodeMode.d.mts +1 -1
  53. package/dist/capabilities/CodeMode.mjs +16 -9
  54. package/dist/capabilities/CodeMode.mjs.map +1 -1
  55. package/dist/capabilities/Commands.d.mts +1 -1
  56. package/dist/capabilities/McpClient.mjs +1 -1
  57. package/dist/capabilities/McpClient.mjs.map +1 -1
  58. package/dist/capabilities/Messaging.d.mts +1 -1
  59. package/dist/capabilities/Messaging.mjs +4 -4
  60. package/dist/capabilities/Messaging.mjs.map +1 -1
  61. package/dist/capabilities/ModelContext.mjs +7 -5
  62. package/dist/capabilities/ModelContext.mjs.map +1 -1
  63. package/dist/capabilities/Redaction.mjs +49 -19
  64. package/dist/capabilities/Redaction.mjs.map +1 -1
  65. package/dist/capabilities/RunHooks.d.mts +1 -1
  66. package/dist/capabilities/RunHooks.mjs +1 -1
  67. package/dist/capabilities/RunHooks.mjs.map +1 -1
  68. package/dist/capabilities/Subagent.d.mts +1 -1
  69. package/dist/capabilities/Subagent.mjs +1 -1
  70. package/dist/capabilities/SubagentReservations.mjs +3 -1
  71. package/dist/capabilities/SubagentReservations.mjs.map +1 -1
  72. package/dist/capabilities/WebCapture.mjs.map +1 -1
  73. package/dist/capabilities/WebSearch.mjs +7 -7
  74. package/dist/capabilities/WebSearch.mjs.map +1 -1
  75. package/dist/core/Agent.d.mts +1 -1
  76. package/dist/core/Agent.mjs +1 -1
  77. package/dist/core/AgentUpdates.mjs +8 -8
  78. package/dist/core/AgentUpdates.mjs.map +1 -1
  79. package/dist/core/Thread.mjs +1 -1
  80. package/dist/core/Thread.mjs.map +1 -1
  81. package/dist/core/Usage.mjs +2 -2
  82. package/dist/core/Usage.mjs.map +1 -1
  83. package/dist/durable/Admin.d.mts +1 -1
  84. package/dist/durable/AgentRegistration.d.mts +1 -1
  85. package/dist/durable/AgentRegistration.mjs +1 -1
  86. package/dist/durable/Certification.d.mts +1 -1
  87. package/dist/durable/CommittedActivity.d.mts +1 -1
  88. package/dist/durable/CommittedActivity.mjs +2 -2
  89. package/dist/durable/Digest.mjs +1 -1
  90. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  91. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  92. package/dist/durable/EventSource.d.mts +1 -1
  93. package/dist/durable/EventSource.mjs +6 -6
  94. package/dist/durable/EventSource.mjs.map +1 -1
  95. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  96. package/dist/durable/LifecyclePublication.d.mts +1 -1
  97. package/dist/durable/LifecyclePublication.mjs +1 -1
  98. package/dist/durable/MessageDelivery.d.mts +1 -1
  99. package/dist/durable/MessageDelivery.mjs +1 -1
  100. package/dist/durable/MessageDeliveryStoreConformance.d.mts +2 -2
  101. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  102. package/dist/durable/PersistentHistory.d.mts +1 -1
  103. package/dist/durable/PersistentHistory.mjs +3 -3
  104. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  105. package/dist/durable/RecordFormat.mjs +2 -2
  106. package/dist/durable/RecordFormat.mjs.map +1 -1
  107. package/dist/durable/Recovery.d.mts +1 -1
  108. package/dist/durable/RunContinuation.d.mts +2 -2
  109. package/dist/durable/RunContinuation.mjs +2 -2
  110. package/dist/durable/RunJournal.d.mts +1 -1
  111. package/dist/durable/RunJournal.mjs +1 -1
  112. package/dist/durable/RunStorage.d.mts +1 -1
  113. package/dist/durable/RunStorage.mjs +1 -1
  114. package/dist/durable/Scheduling.d.mts +1 -1
  115. package/dist/durable/Scheduling.mjs +1 -1
  116. package/dist/durable/SettlementPublisher.d.mts +1 -1
  117. package/dist/durable/SettlementPublisher.mjs +2 -2
  118. package/dist/durable/SubmissionLedger.d.mts +1 -1
  119. package/dist/durable/SubmissionLedger.mjs +5 -1
  120. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  121. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  122. package/dist/durable/SubmissionLedgerConformance.mjs +4 -4
  123. package/dist/durable/SubmissionStatus.d.mts +1 -1
  124. package/dist/durable/Subscription.d.mts +1 -1
  125. package/dist/durable/SubscriptionInput.d.mts +1 -1
  126. package/dist/durable/SubscriptionInput.mjs +3 -3
  127. package/dist/durable/SubscriptionInput.mjs.map +1 -1
  128. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  129. package/dist/durable/SubscriptionStoreConformance.mjs +2 -2
  130. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -1
  131. package/dist/durable/SubscriptionTools.d.mts +2 -2
  132. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  133. package/dist/durable/Subscriptions.d.mts +5 -5
  134. package/dist/durable/Subscriptions.mjs +2 -2
  135. package/dist/durable/Subscriptions.mjs.map +1 -1
  136. package/dist/durable/ThreadArchiveRange.d.mts +1 -1
  137. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  138. package/dist/durable/ThreadContextHistory.mjs +1 -1
  139. package/dist/durable/ThreadImport.d.mts +1 -1
  140. package/dist/durable/ThreadImport.mjs +1 -1
  141. package/dist/durable/ThreadInvariants.d.mts +3 -3
  142. package/dist/durable/ThreadInvariants.mjs +4 -4
  143. package/dist/durable/ThreadInvariants.mjs.map +1 -1
  144. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  145. package/dist/durable/ThreadReader.d.mts +1 -1
  146. package/dist/durable/ThreadReader.mjs +1 -1
  147. package/dist/durable/ThreadStore.d.mts +1 -1
  148. package/dist/durable/ThreadStore.mjs +1 -1
  149. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  150. package/dist/durable/ThreadStoreConformance.mjs +3 -3
  151. package/dist/durable/ThreadTransfer.d.mts +1 -1
  152. package/dist/durable/ThreadTransfer.mjs +1 -1
  153. package/dist/durable/ThreadWork.d.mts +1 -1
  154. package/dist/durable/ThreadWork.mjs +4 -4
  155. package/dist/durable/ThreadWork.mjs.map +1 -1
  156. package/dist/durable/WorkerAdmission.d.mts +1 -1
  157. package/dist/durable/WorkerAdmission.mjs +1 -1
  158. package/dist/durable/WorkerHost.d.mts +2 -2
  159. package/dist/engine/AgentRuntime.d.mts +1 -1
  160. package/dist/engine/AgentRuntime.mjs +1 -1
  161. package/dist/engine/MessagingHost.d.mts +1 -1
  162. package/dist/engine/Output.d.mts +1 -1
  163. package/dist/engine/RunOptions.d.mts +1 -1
  164. package/dist/engine/SubagentHost.d.mts +1 -1
  165. package/dist/index.d.mts +19 -19
  166. package/dist/index.mjs +14 -14
  167. package/dist/{run-context-reader-OcsZr4bk.d.mts → run-context-reader-CC7ZD95F.d.mts} +2 -2
  168. package/package.json +1 -1
  169. package/src/capabilities/Approval.ts +58 -60
  170. package/src/capabilities/BrowserUse.ts +89 -944
  171. package/src/capabilities/Budget.ts +8 -1
  172. package/src/capabilities/CodeMode.ts +57 -33
  173. package/src/capabilities/McpClient.ts +2 -2
  174. package/src/capabilities/Messaging.ts +51 -55
  175. package/src/capabilities/ModelContext.ts +5 -2
  176. package/src/capabilities/Redaction.ts +64 -34
  177. package/src/capabilities/RunHooks.ts +52 -55
  178. package/src/capabilities/Subagent.ts +33 -33
  179. package/src/capabilities/SubagentReservations.ts +9 -1
  180. package/src/capabilities/WebCapture.ts +6 -0
  181. package/src/capabilities/WebSearch.ts +10 -7
  182. package/src/capabilities/internal/subagent-background.ts +202 -158
  183. package/src/core/Agent.ts +11 -6
  184. package/src/core/AgentUpdates.ts +8 -8
  185. package/src/core/Thread.ts +9 -10
  186. package/src/core/Usage.ts +7 -8
  187. package/src/core/internal/agent-updates.ts +1 -0
  188. package/src/durable/DurableAgentRuntime.ts +645 -625
  189. package/src/durable/EventSource.ts +15 -9
  190. package/src/durable/RecordFormat.ts +5 -3
  191. package/src/durable/RunContinuation.ts +233 -81
  192. package/src/durable/RunJournal.ts +10 -9
  193. package/src/durable/RunStorage.ts +122 -124
  194. package/src/durable/Scheduling.ts +639 -651
  195. package/src/durable/SubmissionLedger.ts +4 -0
  196. package/src/durable/SubscriptionInput.ts +5 -3
  197. package/src/durable/SubscriptionStoreConformance.ts +23 -23
  198. package/src/durable/Subscriptions.ts +18 -19
  199. package/src/durable/ThreadImport.ts +18 -19
  200. package/src/durable/ThreadInvariants.ts +2 -1
  201. package/src/durable/ThreadStore.ts +215 -111
  202. package/src/durable/ThreadWork.ts +1 -2
  203. package/src/durable/internal/StorageOwner.ts +10 -4
  204. package/src/durable/internal/agent-registration.ts +96 -89
  205. package/src/durable/internal/canonical-json.ts +61 -20
  206. package/src/durable/internal/prompt-history-cache.ts +13 -4
  207. package/src/durable/internal/record-encoding.ts +120 -64
  208. package/src/durable/internal/schedule-time.ts +6 -6
  209. package/src/durable/internal/usage-totals.ts +38 -0
  210. package/src/durable/internal/worker-host.ts +69 -74
  211. package/src/engine/internal/agent-runtime.ts +1067 -1018
  212. package/src/engine/internal/provisional-text.ts +12 -10
  213. package/src/engine/internal/tool-exposure.ts +22 -18
  214. package/src/engine/internal/tool-telemetry.ts +12 -7
  215. package/dist/Agent-0WvBWWbM.mjs.map +0 -1
  216. package/dist/AgentRuntime-CQ-qcETl.mjs.map +0 -1
  217. package/dist/Digest-DCuPlhNk.mjs.map +0 -1
  218. package/dist/DurableAgentRuntime-BAmSkWYr.mjs.map +0 -1
  219. package/dist/RunContinuation-DHYNAQFi.mjs.map +0 -1
  220. package/dist/RunJournal-kfKVxJj7.mjs.map +0 -1
  221. package/dist/RunStorage-uqPxps09.mjs.map +0 -1
  222. package/dist/Scheduling-CVyfXlBR.mjs.map +0 -1
  223. package/dist/Subagent-vpffemql.mjs.map +0 -1
  224. package/dist/ThreadImport-DckUMEqJ.mjs.map +0 -1
  225. package/dist/ThreadStore-CEekRa80.mjs.map +0 -1
  226. 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";
@@ -359,9 +359,8 @@ const makeAttempt = Effect.fnUntraced(function* (threadId, submissionId, attempt
359
359
  submissionId,
360
360
  attemptId
361
361
  };
362
- const active = /* @__PURE__ */ new Set();
363
362
  let closed = false;
364
- let generation = 0;
363
+ let nextGeneration = 0;
365
364
  const offerUnsafe = (event) => {
366
365
  try {
367
366
  return publisher.offerUnsafe(event);
@@ -373,12 +372,7 @@ const makeAttempt = Effect.fnUntraced(function* (threadId, submissionId, attempt
373
372
  threadId,
374
373
  openModel: (runId, turnId) => {
375
374
  if (closed) return void 0;
376
- const model = {
377
- ...identity,
378
- runId,
379
- turnId,
380
- generation: ++generation
381
- };
375
+ const generation = ++nextGeneration;
382
376
  let open = true;
383
377
  const handle = {
384
378
  offerUnsafe: (part) => {
@@ -389,31 +383,34 @@ const makeAttempt = Effect.fnUntraced(function* (threadId, submissionId, attempt
389
383
  }) : Response.makePart(part.type, { id: part.id });
390
384
  return offerUnsafe({
391
385
  _tag: "Text",
392
- ...model,
386
+ ...identity,
387
+ runId,
388
+ turnId,
389
+ generation,
393
390
  part: detached
394
391
  });
395
392
  },
396
393
  discard: () => {
397
- if (!open) return;
394
+ if (!open || closed) return;
398
395
  handle.close();
399
396
  offerUnsafe({
400
397
  _tag: "Discard",
401
- ...model
398
+ ...identity,
399
+ runId,
400
+ turnId,
401
+ generation
402
402
  });
403
403
  },
404
404
  close: () => {
405
405
  if (!open) return;
406
406
  open = false;
407
- active.delete(handle);
408
407
  }
409
408
  };
410
- active.add(handle);
411
409
  return handle;
412
410
  },
413
411
  close: () => {
414
412
  if (closed) return;
415
413
  closed = true;
416
- for (const handle of active) handle.close();
417
414
  offerUnsafe({
418
415
  _tag: "AttemptEnded",
419
416
  ...identity
@@ -508,19 +505,24 @@ const exposureSnapshot = Effect.fnUntraced(function* (definition, selection, ent
508
505
  maxSchemaBytes: definition.toolExposure?.maxSchemaBytes ?? 262144
509
506
  }).pipe(Effect.mapError(() => invalid("Invalid Tool exposure bounds")));
510
507
  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) ? {
508
+ const declarations = [];
509
+ for (const name of names) {
510
+ const tool = definition.toolkit.tools[name];
511
+ if (tool === void 0) return yield* invalid("A selected Tool schema cannot be rendered");
512
+ declarations.push(yield* Effect.try({
513
+ try: () => Tool.isProviderDefined(tool) ? {
516
514
  type: tool.providerName,
517
515
  args: tool.args
518
516
  } : {
519
517
  name,
520
518
  description: Tool.getDescription(tool),
521
519
  parameters: Tool.getJsonSchema(tool, { transformer })
522
- };
523
- }))),
520
+ },
521
+ catch: () => invalid("A selected Tool schema cannot be rendered")
522
+ }));
523
+ }
524
+ if ((yield* Effect.try({
525
+ try: () => utf8ByteLength(JSON.stringify(declarations)),
524
526
  catch: () => invalid("A selected Tool schema cannot be rendered")
525
527
  })) > limits.maxSchemaBytes) return yield* invalid("Tool exposure exceeds the configured schema byte bound");
526
528
  }
@@ -590,11 +592,9 @@ const restoreToolSpanFailureCause = (cause, marker, original) => {
590
592
  };
591
593
  const MAX_REPORTED_SPAN_LIFECYCLE_DEFECTS = 16;
592
594
  /** Content-free marker used only to close a delegate that cannot be wrapped safely. */
593
- var ToolSpanLifecycleFailure = class extends Error {
595
+ var ToolSpanLifecycleFailure = class extends Schema.TaggedError()("ToolSpanLifecycleFailure", {}) {
594
596
  name = "ToolSpanLifecycleFailure";
595
- constructor() {
596
- super("Tool span lifecycle failed");
597
- }
597
+ message = "Tool span lifecycle failed";
598
598
  };
599
599
  /**
600
600
  * @internal Guard one host span so synchronous exporter defects cannot alter Tool execution.
@@ -636,7 +636,7 @@ var IsolatedToolSpan = class {
636
636
  }
637
637
  end(endTime, exit) {
638
638
  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;
639
+ const exportedExit = this.#terminalOutcome === "failure" ? Exit.fail(this.#terminalFailure ?? ToolSpanLifecycleFailure.make({})) : this.#terminalOutcome === "success" ? Exit.succeed(void 0) : exit;
640
640
  this.status = {
641
641
  _tag: "Ended",
642
642
  startTime: this.status.startTime,
@@ -780,7 +780,7 @@ const makeIsolatedToolTracer = (delegate) => {
780
780
  } catch (defect) {
781
781
  recordDefect(defect);
782
782
  try {
783
- delegateSpan.end(options.startTime, Exit.fail(new ToolSpanLifecycleFailure()));
783
+ delegateSpan.end(options.startTime, Exit.fail(ToolSpanLifecycleFailure.make({})));
784
784
  } catch (closeDefect) {
785
785
  recordDefect(closeDefect);
786
786
  }
@@ -990,15 +990,14 @@ const schemaClassToolPartPreflight = (part, toolkit) => {
990
990
  if (part === null || typeof part !== "object") return void 0;
991
991
  const read = (key) => {
992
992
  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;
993
+ return descriptor !== void 0 && "value" in descriptor ? descriptor : void 0;
995
994
  };
996
- const type = read("type");
995
+ const type = read("type")?.value;
997
996
  if (type !== "tool-call" && type !== "tool-result") return void 0;
998
- const name = read("name");
997
+ const name = read("name")?.value;
999
998
  if (typeof name !== "string" || !hasTool(toolkit.tools, name)) return void 0;
1000
999
  const tool = toolkit.tools[name];
1001
- const payload = read(type === "tool-call" ? "params" : "result");
1000
+ const payload = read(type === "tool-call" ? "params" : "result")?.value;
1002
1001
  if (payload === null || typeof payload !== "object") return void 0;
1003
1002
  const payloadPrototype = Object.getPrototypeOf(payload);
1004
1003
  if (!(type === "tool-call" ? [tool.parametersSchema] : [tool.successSchema, tool.failureSchema]).some((schema) => schemaClassPrototype(schema) === payloadPrototype)) return;
@@ -1019,7 +1018,11 @@ const schemaClassToolPartPreflight = (part, toolkit) => {
1019
1018
  "metadata",
1020
1019
  "encodedResult"
1021
1020
  ];
1022
- for (const key of retainedKeys) preflight[key] = read(key);
1021
+ for (const key of retainedKeys) {
1022
+ const descriptor = read(key);
1023
+ if (descriptor === void 0) return void 0;
1024
+ preflight[key] = descriptor.value;
1025
+ }
1023
1026
  return preflight;
1024
1027
  } catch {
1025
1028
  return;
@@ -1072,10 +1075,10 @@ const captureModelResponsePartGeneral = Effect.fnUntraced(function* (part, toolk
1072
1075
  }
1073
1076
  const encoded = yield* modelResponseParsersFor(toolkit).encode(part).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Model response part failed canonical encoding" })));
1074
1077
  const retainedBytes = yield* inspectModelResponsePartCapacity(usage, encoded, limits);
1078
+ if (typeof structuredCloneFunction !== "function") return yield* ModelProtocolError.make({ message: "Model response part could not be converted into engine-owned data" });
1075
1079
  return {
1076
1080
  encodedPart: yield* Effect.try({
1077
1081
  try: () => {
1078
- if (typeof structuredCloneFunction !== "function") throw new TypeError("structuredClone is unavailable");
1079
1082
  return Reflect.apply(structuredCloneFunction, globalThis, [encoded]);
1080
1083
  },
1081
1084
  catch: () => ModelProtocolError.make({ message: "Model response part could not be converted into engine-owned data" })
@@ -1121,25 +1124,29 @@ const encodeToolCallParameters = (tool, toolName, decodedParams) => {
1121
1124
  const decodeToolCallParameters = (tool, toolName, encodedParams, boundary = "execution") => {
1122
1125
  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
1126
  };
1127
+ /** Native identity proves encoding does not transform the already validated parameters. */
1128
+ const reusesValidatedToolParameters = (tool) => (tool.needsApproval === void 0 || tool.needsApproval === false) && SchemaAST.toEncoded(tool.parametersSchema.ast) === tool.parametersSchema.ast;
1124
1129
  /**
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.
1130
+ * Fresh responses and resumed batches validate every call before reaching this boundary.
1131
+ * Identity encodings with no approval need no second decoded value. Other codecs retain the
1132
+ * complete batch preflight, including validation of their canonical round trip, before dispatch.
1127
1133
  */
1128
1134
  const prepareToolCall = (toolkit, call, declarationIndex, rejection) => {
1129
1135
  const name = call.name;
1130
1136
  if (!hasTool(toolkit.tools, name)) return Effect.fail(ModelProtocolError.make({ message: `Model requested unknown Tool ${call.name}` }));
1131
1137
  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 {
1138
+ return Effect.flatMap(decodeToolCallId(call.id), (toolCallId) => {
1139
+ const prepared = (validation) => ({
1136
1140
  call,
1137
1141
  name,
1138
1142
  toolCallId,
1139
1143
  validation,
1140
1144
  tool,
1141
1145
  declarationIndex
1142
- };
1146
+ });
1147
+ if (rejection !== void 0) return Effect.succeed(prepared(Result.fail(rejection)));
1148
+ if (reusesValidatedToolParameters(tool)) return Effect.succeed(prepared(Result.succeed(Option.none())));
1149
+ return Effect.map(decodeToolCallParameters(tool, call.name, copyJson(call.params)), (parameters) => prepared(Result.succeed(Option.some(parameters))));
1143
1150
  });
1144
1151
  };
1145
1152
  /**
@@ -1166,29 +1173,36 @@ const effectiveRunBounds = (policy, options) => ({
1166
1173
  maxTurns: boundedAllowance(policy.maxTurns, options.turnAllowance),
1167
1174
  maxToolCalls: boundedAllowance(policy.maxToolCalls, options.toolCallAllowance)
1168
1175
  });
1176
+ const readSnapshotProperty = Effect.fnUntraced(function* (input, key, invalid, optional = false) {
1177
+ const descriptor = yield* Effect.try({
1178
+ try: () => Object.getOwnPropertyDescriptor(input, key),
1179
+ catch: invalid
1180
+ });
1181
+ if (descriptor === void 0 && optional) return void 0;
1182
+ if (descriptor === void 0 || !("value" in descriptor)) return yield* invalid();
1183
+ return descriptor.value;
1184
+ });
1169
1185
  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" })
1186
+ const invalid = () => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call" });
1187
+ if (input === null || typeof input !== "object") return yield* invalid();
1188
+ const id = yield* readSnapshotProperty(input, "id", invalid);
1189
+ const resultValue = yield* readSnapshotProperty(input, "result", invalid);
1190
+ const isFailure = yield* readSnapshotProperty(input, "isFailure", invalid);
1191
+ const { selection, rejected } = yield* Effect.try({
1192
+ try: () => ({
1193
+ selection: Object.getOwnPropertyDescriptor(input, "toolSelection"),
1194
+ rejected: Object.getOwnPropertyDescriptor(input, "budgetRejected")
1195
+ }),
1196
+ catch: invalid
1191
1197
  });
1198
+ if (selection !== void 0 && !("value" in selection) || rejected !== void 0 && !("value" in rejected)) return yield* invalid();
1199
+ const raw = {
1200
+ id,
1201
+ result: resultValue,
1202
+ isFailure,
1203
+ ...rejected === void 0 ? {} : { budgetRejected: rejected.value },
1204
+ ...selection === void 0 ? {} : { toolSelection: selection.value }
1205
+ };
1192
1206
  const result = boundedCanonicalJsonSnapshot(raw.result, MAX_RESUMED_RESULT_BYTES);
1193
1207
  if (result === void 0) return yield* ModelProtocolError.make({ message: "Turn resume settled Tool result is not bounded canonical JSON" });
1194
1208
  return yield* Schema.decodeUnknownEffect(RunTurnResumeSettledCallSchema)({
@@ -1196,59 +1210,48 @@ const decodeResumedSettledCall = Effect.fnUntraced(function* (input) {
1196
1210
  result: result.value
1197
1211
  }).pipe(Effect.mapError(() => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call" })));
1198
1212
  });
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" })
1213
+ const snapshotResumedSettledCalls = Effect.fnUntraced(function* (resume, maximum) {
1214
+ const invalid = () => ModelProtocolError.make({ message: "Turn resume contains an invalid settled Tool Call collection" });
1215
+ if (resume === null || typeof resume !== "object") return yield* invalid();
1216
+ const settled = yield* readSnapshotProperty(resume, "settled", invalid);
1217
+ if (!(yield* Effect.try({
1218
+ try: () => Array.isArray(settled),
1219
+ catch: invalid
1220
+ })) || settled === null || typeof settled !== "object") return yield* invalid();
1221
+ const length = yield* readSnapshotProperty(settled, "length", invalid);
1222
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maximum) return yield* invalid();
1223
+ const snapshot = [];
1224
+ for (let index = 0; index < length; index += 1) snapshot.push(yield* readSnapshotProperty(settled, String(index), invalid));
1225
+ return snapshot;
1217
1226
  });
1218
1227
  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
- });
1228
+ 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" });
1229
+ if (input === null || typeof input !== "object") return yield* invalid();
1230
+ const snapshot = {};
1231
+ for (const key of [
1232
+ "usageStatus",
1233
+ "pricingStatus",
1234
+ "unobservedModelCalls",
1235
+ "children",
1236
+ "modelRestarts",
1237
+ "webSearchCalls"
1238
+ ]) {
1239
+ const value = yield* readSnapshotProperty(input, key, invalid, true);
1240
+ if (value !== void 0) snapshot[key] = value;
1241
+ }
1242
+ for (const key of [
1243
+ "modelCalls",
1244
+ "inputTokens",
1245
+ "outputTokens",
1246
+ "lastInputTokens",
1247
+ "lastOutputTokens",
1248
+ "costMicrousd",
1249
+ "committedTurns",
1250
+ "toolCalls",
1251
+ "programmaticToolCalls",
1252
+ "consecutiveToolFailures",
1253
+ "finalizationUsed"
1254
+ ]) snapshot[key] = yield* readSnapshotProperty(input, key, invalid);
1252
1255
  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
1256
  });
1254
1257
  const makeToolFailedEvent = Effect.fnUntraced(function* (context, turnId, call, error, failureHandling, budgetRejected) {
@@ -1354,7 +1357,8 @@ const stampSubagentEvent = Effect.fnUntraced(function* (context, turnId, payload
1354
1357
  });
1355
1358
  const prepareApprovalRequest = (context, turnId, prepared) => prepareWithinDeadline(context, Effect.gen(function* () {
1356
1359
  if (Result.isFailure(prepared.validation)) return void 0;
1357
- const decodedParams = prepared.validation.success;
1360
+ if (Option.isNone(prepared.validation.success)) return void 0;
1361
+ const decodedParams = prepared.validation.success.value;
1358
1362
  const approval = prepared.tool.needsApproval;
1359
1363
  if (!(typeof approval === "function" ? yield* Effect.suspend(() => {
1360
1364
  const result = approval(decodedParams, {
@@ -1678,7 +1682,7 @@ const executePreparedToolCall = Effect.fnUntraced(function* (context, turnId, to
1678
1682
  }));
1679
1683
  if (result.isFailure) return yield* failureMarker();
1680
1684
  });
1681
- const failTerminalResult = (cause) => Effect.gen(function* () {
1685
+ const failTerminalResult = Effect.fnUntraced(function* (cause) {
1682
1686
  terminal = true;
1683
1687
  terminalResult = void 0;
1684
1688
  propagatedFailure = cause;
@@ -1716,10 +1720,11 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1716
1720
  const visibility = yield* RunToolVisibility;
1717
1721
  const eligible = new Set(context.toolCatalog.filter((entry) => entry.kind === "native").map((entry) => entry.nativeToolName));
1718
1722
  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) ? [] : [{
1723
+ const prepareCalls = Effect.forEach(calls.flatMap((call, declarationIndex) => settledCallIds?.has(call.id) ? [] : [{
1720
1724
  call,
1721
1725
  declarationIndex
1722
- }]), ({ call, declarationIndex }) => prepareToolCall(toolkit, call, declarationIndex, trace.toolParameterRejections.get(call.id))));
1726
+ }]), ({ call, declarationIndex }) => prepareToolCall(toolkit, call, declarationIndex, trace.toolParameterRejections.get(call.id)));
1727
+ 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
1728
  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
1729
  const descriptors = trace.applicationCallDescriptors.filter((call) => !trace.toolParameterRejections.has(call.toolCallId));
1725
1730
  const executable = settledCallIds === void 0 ? prepared : prepared.filter((call) => !settledCallIds.has(call.call.id));
@@ -1792,25 +1797,25 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1792
1797
  "SubagentFailed",
1793
1798
  "SubagentInterrupted",
1794
1799
  "SubagentJoined"
1795
- ].includes(payload._tag) ? Effect.fail(new RunEventSinkClosedError({ message: "Unsupported Tool event payload" })) : emitPayload(payload) };
1800
+ ].includes(payload._tag) ? Effect.fail(RunEventSinkClosedError.make({ message: "Unsupported Tool event payload" })) : emitPayload(payload) };
1796
1801
  const updateAcceptance = yield* AgentUpdateAcceptance;
1797
1802
  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" })));
1803
+ if (!updatesOpen) return yield* UpdateError.make({ reason: "unavailable" });
1804
+ if (request.target.id !== context.agentId || request.target.updates !== context.definition.updates || context.definition.updates === void 0) return yield* UpdateError.make({ reason: "identity" });
1805
+ const updateId = yield* Schema.decodeEffect(IdempotencyKey)(request.updateId).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
1806
+ const value = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(JSON.stringify(request.value)).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
1802
1807
  yield* context.validateUpdate(value);
1803
1808
  const existing = context.updates.get(updateId);
1804
1809
  if (existing !== void 0) {
1805
- if (!Schema.toEquivalence(Schema.Json)(existing.value, value)) return yield* new UpdateError({ reason: "conflict" });
1810
+ if (!Schema.toEquivalence(Schema.Json)(existing.value, value)) return yield* UpdateError.make({ reason: "conflict" });
1806
1811
  return existing;
1807
1812
  }
1808
1813
  const bytes = utf8ByteLength(JSON.stringify(value));
1809
1814
  const maxCount = options.updates?.maxCount ?? 32;
1810
1815
  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" });
1816
+ 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
1817
  const snapshot = boundedCanonicalJsonSnapshot(value, bytes);
1813
- if (snapshot === void 0) return yield* new UpdateError({ reason: "validation" });
1818
+ if (snapshot === void 0) return yield* UpdateError.make({ reason: "validation" });
1814
1819
  const accepted = yield* updateAcceptance.accept(Object.freeze(Update.make({
1815
1820
  schemaVersion: 1,
1816
1821
  agentId: context.agentId,
@@ -1820,8 +1825,8 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1820
1825
  sequence: context.updates.size + 1,
1821
1826
  value: snapshot.value
1822
1827
  })));
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" });
1828
+ const validated = yield* Schema.decodeEffect(Update)(accepted).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
1829
+ 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
1830
  const update = Object.freeze(Update.make({
1826
1831
  ...validated,
1827
1832
  value: snapshot.value
@@ -1831,43 +1836,43 @@ const executeToolBatch = Effect.fnUntraced(function* (context, turnId, turn, too
1831
1836
  yield* emitPayload({
1832
1837
  _tag: "AgentUpdateEmitted",
1833
1838
  update
1834
- }).pipe(Effect.mapError(() => new UpdateError({ reason: "unavailable" })));
1839
+ }).pipe(Effect.mapError(() => UpdateError.make({ reason: "unavailable" })));
1835
1840
  return update;
1836
1841
  })) };
1837
1842
  const permits = yield* Semaphore.make(concurrency);
1838
1843
  const handlers = Effect.gen(function* () {
1839
1844
  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",
1845
+ yield* Effect.forEach(group, (call) => permits.withPermit(Effect.acquireUseRelease(Effect.forkScoped(Effect.scoped(Effect.gen(function* () {
1846
+ yield* checkpointExecution(context, durability);
1847
+ const subagentHost = yield* SubagentHost.forTool;
1848
+ const messagingHost = yield* MessagingHost.forTool;
1849
+ const source = {
1850
+ _tag: "tool",
1851
+ agentId: context.agentId,
1852
+ threadId: context.threadId,
1853
+ runId: context.runId,
1854
+ toolCallId: call.toolCallId
1855
+ };
1856
+ const broker = yield* makeToolBrokerService({
1857
+ context,
1858
+ turnId,
1859
+ outerToolCallId: call.toolCallId,
1860
+ turn,
1861
+ maxToolCalls: brokerAccounting.maxToolCalls,
1862
+ declaredToolCalls: brokerAccounting.declaredToolCalls,
1863
+ budget: options.budget,
1864
+ reservePolicyUsage: durability?.reservePolicyUsage,
1865
+ hookServices
1866
+ });
1867
+ const step = stepServiceFor(call);
1868
+ const subagent = subagentHost(source);
1869
+ const messaging = messagingHost(source);
1870
+ const catalog = { entries: context.toolCatalog };
1871
+ return yield* executePreparedToolCall(context, turnId, toolkit, call, trace, resultBounds, (waiting) => {
1872
+ waitingByDeclaration.set(call.declarationIndex, waiting);
1873
+ }).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())));
1874
+ }))), Fiber.join, Fiber.interrupt)), {
1875
+ concurrency: group.length === 1 ? 1 : "unbounded",
1871
1876
  discard: true
1872
1877
  });
1873
1878
  yield* checkpointExecution(context, durability);
@@ -2451,7 +2456,7 @@ const compactContext = (agent, context, source, turn, options, resolvedModelInpu
2451
2456
  let summaryFailure;
2452
2457
  const textParts = /* @__PURE__ */ new Map();
2453
2458
  const reasoningParts = /* @__PURE__ */ new Map();
2454
- const consumeSummaryPart = (owned) => Effect.gen(function* () {
2459
+ const consumeSummaryPart = Effect.fnUntraced(function* (owned) {
2455
2460
  responseUsage.responsePartCount++;
2456
2461
  responseUsage.responsePartBytes += owned.retainedBytes;
2457
2462
  const ownedPart = owned.ownedPart;
@@ -2604,13 +2609,13 @@ const evaluateInstructions = (instructions, input) => Effect.suspend(() => {
2604
2609
  return Effect.isEffect(result) ? result : Effect.succeed(result);
2605
2610
  });
2606
2611
  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)}` })
2612
+ const renderInputPromptEffect = (inputPrompt, decodedInput, encodedInput) => inputPrompt === void 0 ? Effect.gen(function* () {
2613
+ const encoded = yield* Effect.try({
2614
+ try: () => JSON.stringify(encodedInput),
2615
+ catch: (cause) => AgentInputError.make({ message: `Unable to materialize Agent input: ${errorMessage(cause)}` })
2616
+ });
2617
+ if (encoded === void 0) return yield* AgentInputError.make({ message: "Unable to materialize Agent input: Agent input cannot be represented as JSON" });
2618
+ return encoded;
2614
2619
  }) : Effect.suspend(() => {
2615
2620
  const result = inputPrompt(decodedInput);
2616
2621
  return Effect.isEffect(result) ? result : Effect.succeed(result);
@@ -2782,7 +2787,7 @@ const processModelPart = Effect.fnUntraced(function* (context, turnId, turn, too
2782
2787
  const error = AiError.make({
2783
2788
  module: "Toolkit",
2784
2789
  method: `${part.name}.handle`,
2785
- reason: new AiError.ToolParameterValidationError({
2790
+ reason: AiError.ToolParameterValidationError.make({
2786
2791
  toolName: part.name,
2787
2792
  description: decoded.failure.message
2788
2793
  })
@@ -3030,10 +3035,10 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3030
3035
  ...outputContractMessage === void 0 ? {} : { outputContract: outputContractMessage }
3031
3036
  };
3032
3037
  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({
3038
+ if (context.resolvedModel && modelContext.modelCall !== void 0) return yield* AiError.AiError.make({
3034
3039
  module: "AgentRuntime",
3035
3040
  method: "resolveModel",
3036
- reason: new AiError.InvalidRequestError({ description: "Context preparation cannot replace a thread-resolved model" })
3041
+ reason: AiError.InvalidRequestError.make({ description: "Context preparation cannot replace a thread-resolved model" })
3037
3042
  });
3038
3043
  const callContext = modelContext.modelCall === void 0 ? void 0 : yield* Schema.decodeEffect(ModelCallContext)(modelContext.modelCall.context).pipe(Effect.mapError((cause) => CompactionError.make({
3039
3044
  message: "Invalid resolved model context bounds",
@@ -3384,10 +3389,12 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3384
3389
  }))));
3385
3390
  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 }) => {
3386
3391
  const lastPart = trace.parts.at(-1);
3387
- return canRepeatModelCall && !hasStreamedContent(trace) && (lastPart?.type === "error" && isTransientErrorPayload(lastPart.error) || AiError.isAiError(error) && error.isRetryable);
3392
+ const providerError = error;
3393
+ return canRepeatModelCall && !hasStreamedContent(trace) && (lastPart?.type === "error" && isTransientErrorPayload(lastPart.error) || AiError.isAiError(providerError) && providerError.isRetryable);
3388
3394
  }), Schedule.modifyDelay(({ input: error, duration }) => Effect.gen(function* () {
3389
3395
  const backoff = Duration.min(duration, MODEL_RETRY_MAX_DELAY);
3390
- const retryAfter = AiError.isAiError(error) ? error.retryAfter : void 0;
3396
+ const providerError = error;
3397
+ const retryAfter = AiError.isAiError(providerError) ? providerError.retryAfter : void 0;
3391
3398
  const requested = retryAfter === void 0 ? backoff : Duration.max(backoff, retryAfter);
3392
3399
  const remaining = Math.max(0, context.durationDeadlineMillis - (yield* Clock.currentTimeMillis));
3393
3400
  return Duration.min(requested, Duration.millis(remaining));
@@ -3551,7 +3558,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3551
3558
  * steering at the safe seam, and start the next Turn. The `maxTurns`
3552
3559
  * guard already ran for these Tool Call sites.
3553
3560
  */
3554
- const continueTurn = (history) => Effect.gen(function* () {
3561
+ const continueTurn = Effect.fnUntraced(function* (history) {
3555
3562
  trace.historyAccepted = true;
3556
3563
  yield* advanceHistory(context, history, options);
3557
3564
  yield* settleTurn(context, trace, turn, turnId, options);
@@ -3565,7 +3572,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options, restart
3565
3572
  * under the `maxTurns` and repeated-failure Stop Policy bounds or
3566
3573
  * complete the Run with the Turn's decoded final output.
3567
3574
  */
3568
- const settleOrFollowUp = (history) => Effect.gen(function* () {
3575
+ const settleOrFollowUp = Effect.fnUntraced(function* (history) {
3569
3576
  trace.historyAccepted = true;
3570
3577
  yield* advanceHistory(context, history, options);
3571
3578
  const turnsBlocked = policy.onExhaustion === "fail" ? turn >= bounds.maxTurns : turn > bounds.maxTurns;
@@ -4081,7 +4088,7 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4081
4088
  const initialToolSelection = options.toolSelection ?? (agent.definition.toolExposure === void 0 ? void 0 : { toolNames: agent.definition.toolExposure.initialToolNames ?? [] });
4082
4089
  const updateSchema = agent.definition.updates;
4083
4090
  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" })));
4091
+ 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
4092
  const languageModel = yield* LanguageModel.LanguageModel;
4086
4093
  const resolver = isModelResolver(languageModel) ? languageModel : void 0;
4087
4094
  const context = {
@@ -4270,10 +4277,10 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4270
4277
  turn: pending.turn,
4271
4278
  input: context.input
4272
4279
  }, 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({
4280
+ const selectionPrompt = yield* Schema.encodeEffect(Schema.fromJsonString(Prompt.Prompt))(pending.prompt).pipe(Effect.mapError((cause) => AiError.AiError.make({
4274
4281
  module: "AgentRuntime",
4275
4282
  method: "resolveModel",
4276
- reason: new AiError.InvalidRequestError({ description: `Cannot encode model selection context: ${cause.message}` })
4283
+ reason: AiError.InvalidRequestError.make({ description: `Cannot encode model selection context: ${cause.message}` })
4277
4284
  })));
4278
4285
  const selected = yield* prepareWithinDeadline(context, resolver.resolve({
4279
4286
  threadId,
@@ -4289,11 +4296,11 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4289
4296
  return Effect.provide(turns, services);
4290
4297
  }));
4291
4298
  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" })));
4299
+ const updateHandlers = agent.definition.updates === void 0 || nativeUpdateTool === void 0 ? Context.empty() : yield* Toolkit.make(nativeUpdateTool).toHandlers({ emit_update: Effect.fnUntraced(function* (parameters, call) {
4300
+ if (call.toolCallId === void 0) return yield* UpdateError.make({ reason: "unavailable" });
4301
+ const decoded = yield* Schema.decodeUnknownEffect(Schema.Struct({ value: Schema.Unknown }))(parameters).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4302
+ const value = yield* Schema.encodeUnknownEffect(agent.definition.updates)(decoded.value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Json)), Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4303
+ const updateId = yield* Schema.decodeEffect(IdempotencyKey)(`tool:${context.runId}:${call.toolCallId}`).pipe(Effect.mapError(() => UpdateError.make({ reason: "validation" })));
4297
4304
  yield* (yield* Emitter).emit({
4298
4305
  target: agent.definition,
4299
4306
  updateId,
@@ -4323,7 +4330,7 @@ function executeWithCompletion(agentValue, input, runOptions = {}, onCompleted,
4323
4330
  contextTokenLimit,
4324
4331
  remainingTokens: contextTokenLimit === null ? null : Math.max(0, contextTokenLimit - estimatedTokens)
4325
4332
  });
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 : {
4333
+ }) }), 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
4334
  grant: options.subagentGrant,
4328
4335
  depth: options.delegationDepth ?? options.parentLink?.depth ?? 0
4329
4336
  }), Context.add(ToolBroker, closedToolBroker));
@@ -4470,13 +4477,13 @@ const executeWithUsageAccountingUnknown = (agent, input, options) => executeWith
4470
4477
  /** Accept schema-encoded input, retaining runtime validation. Use streamUnknown for external data. */
4471
4478
  const stream = (agent, input, options) => streamUnknown(agent, input, options);
4472
4479
  function runUnknown(agent, input, options = {}) {
4473
- const program = "definition" in agent ? agent : { definition: agent };
4480
+ const program = { definition: "definition" in agent ? agent.definition : agent };
4474
4481
  return runProgram(program, (onCompleted) => executeWithCompletion(agent, input, options, onCompleted).pipe(Effect.provide(Layer.mergeAll(ModelUsageAccounting.layerEphemeral, AgentUpdateAcceptance.layerEphemeral))));
4475
4482
  }
4476
4483
  /** Accept schema-encoded input, retaining runtime validation. Use runUnknown for external data. */
4477
4484
  const run = (agent, input, options) => runUnknown(agent, input, options);
4478
4485
  function startUnknown(agent, input, options = {}) {
4479
- const program = "definition" in agent ? agent : { definition: agent };
4486
+ const program = { definition: "definition" in agent ? agent.definition : agent };
4480
4487
  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
4488
  }
4482
4489
  /** Accept schema-encoded input, retaining runtime validation. Use startUnknown for external data. */
@@ -4607,11 +4614,12 @@ const makeToolBrokerService = Effect.fnUntraced(function* (binding) {
4607
4614
  permits: Semaphore.makeUnsafe(1)
4608
4615
  };
4609
4616
  return {
4610
- service: { openPass: (toolkit, passOptions) => Effect.gen(function* () {
4617
+ service: { openPass: Effect.fnUntraced(function* (toolkit, passOptions) {
4611
4618
  const inheritedAuthority = yield* CurrentSubagentAuthority;
4612
4619
  if (lifecycle.closed) return yield* ToolBrokerUnavailableError.make({ message: "The outer Tool Call for this broker has already settled" });
4613
4620
  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
4621
  const handlerServices = yield* Effect.context();
4622
+ const handle = toolkit.handle;
4615
4623
  const concurrency = passOptions.concurrency ?? 4;
4616
4624
  if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64) return yield* ToolBrokerConfigurationError.make({ message: "concurrency must be an integer between 1 and 64" });
4617
4625
  const permits = yield* Semaphore.make(concurrency);
@@ -4740,7 +4748,7 @@ const makeToolBrokerService = Effect.fnUntraced(function* (binding) {
4740
4748
  yield* Metric.update(toolCounter, 1);
4741
4749
  let terminal;
4742
4750
  let resultAfterTerminal = false;
4743
- const handlerFailed = yield* Stream.unwrap(toolSpanTelemetry.isolateToolkitHandle(toolkit.handle(input.toolName, input.encodedArguments, handleId))).pipe(Stream.runForEach((result) => Effect.sync(() => {
4751
+ const handlerFailed = yield* Stream.unwrap(toolSpanTelemetry.isolateToolkitHandle(handle(input.toolName, input.encodedArguments, handleId))).pipe(Stream.runForEach((result) => Effect.sync(() => {
4744
4752
  if (terminal !== void 0) {
4745
4753
  resultAfterTerminal = true;
4746
4754
  return;
@@ -4818,7 +4826,7 @@ const makeToolBrokerService = Effect.fnUntraced(function* (binding) {
4818
4826
  };
4819
4827
  })));
4820
4828
  return yield* observer === void 0 ? recorded : recorded.pipe(Effect.tap(() => failureObservation === void 0 ? Effect.void : deliverToolFailure(observer, failureObservation)));
4821
- }).pipe(Effect.provideContext(handlerServices));
4829
+ }).pipe(Effect.updateContext((current) => Context.merge(current, handlerServices)));
4822
4830
  return {
4823
4831
  snapshot: Effect.sync(() => records.map((record) => ({ ...record }))),
4824
4832
  invoke: (input) => Effect.suspend(() => {
@@ -4890,7 +4898,7 @@ const passthroughDurableStep = () => {
4890
4898
  const provideHookServices = (effect, services) => effect.pipe(Effect.provideContext(services));
4891
4899
  const makeDurableStepService = (toolCallId, hook, hookServices) => {
4892
4900
  const usedNames = /* @__PURE__ */ new Set();
4893
- return { do: (name, output, execute) => Effect.gen(function* () {
4901
+ return { do: Effect.fnUntraced(function* (name, output, execute) {
4894
4902
  if (usedNames.has(name)) return yield* DurableStepError.make({
4895
4903
  toolCallId,
4896
4904
  stepName: name,
@@ -5199,4 +5207,4 @@ var AgentRuntime_exports = /* @__PURE__ */ __exportAll({
5199
5207
  //#endregion
5200
5208
  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
5209
 
5202
- //# sourceMappingURL=AgentRuntime-CQ-qcETl.mjs.map
5210
+ //# sourceMappingURL=AgentRuntime-B6qZlD3f.mjs.map