effect-agent 0.1.0-beta.97 → 0.1.0-beta.98

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 (143) hide show
  1. package/dist/{AgentRuntime-B64362Id.d.mts → AgentRuntime-BMzrJos6.d.mts} +2 -2
  2. package/dist/{AgentRuntime-Cdvqw7l_.mjs → AgentRuntime-BWOnNc0d.mjs} +78 -42
  3. package/dist/AgentRuntime-BWOnNc0d.mjs.map +1 -0
  4. package/dist/{DurableAgentRuntime-DbUvZHDZ.mjs → DurableAgentRuntime-gF4YiEj2.mjs} +471 -252
  5. package/dist/DurableAgentRuntime-gF4YiEj2.mjs.map +1 -0
  6. package/dist/{DurableFailpoint-DQJet828.d.mts → DurableFailpoint-mx3-nsxU.d.mts} +3 -3
  7. package/dist/{EventSource-D6PAAEyK.d.mts → EventSource-BZ73J0s5.d.mts} +3 -3
  8. package/dist/{PreparedInputAdmission-omMbwd--.d.mts → PreparedInputAdmission-BkeI-Xvr.d.mts} +4 -4
  9. package/dist/{Records-CV49DgQK.d.mts → Records-BIiRLqlz.d.mts} +92 -128
  10. package/dist/{Records-BAutSSnJ.mjs → Records-DR1xtbXY.mjs} +35 -8
  11. package/dist/Records-DR1xtbXY.mjs.map +1 -0
  12. package/dist/{RunJournal-DRRRZmG7.mjs → RunJournal-DNs3PM4K.mjs} +80 -23
  13. package/dist/RunJournal-DNs3PM4K.mjs.map +1 -0
  14. package/dist/{RunOptions-Clj8cLsp.d.mts → RunOptions-Bruk54SE.d.mts} +13 -4
  15. package/dist/{Schedule-DePbGfgd.d.mts → Schedule-BNFlluAl.d.mts} +2 -2
  16. package/dist/{Scheduling-C3QpYn0W.mjs → Scheduling-HFH0pST1.mjs} +2 -2
  17. package/dist/{Scheduling-C3QpYn0W.mjs.map → Scheduling-HFH0pST1.mjs.map} +1 -1
  18. package/dist/{Subagent-Cbfzylz1.mjs → Subagent-C2s8PFrd.mjs} +2 -2
  19. package/dist/{Subagent-Cbfzylz1.mjs.map → Subagent-C2s8PFrd.mjs.map} +1 -1
  20. package/dist/{Subagent-Bm1dRecN.d.mts → Subagent-m7ywTCe4.d.mts} +3 -3
  21. package/dist/{Subscription-BR_8Cxh3.d.mts → Subscription-BCQ3L9Zp.d.mts} +3 -3
  22. package/dist/{SubscriptionInput-B95sQbuk.d.mts → SubscriptionInput-Cqu4_RW3.d.mts} +3 -3
  23. package/dist/{ToolReconciler-DQVaJfpE.d.mts → ToolReconciler-BmVRAHKs.d.mts} +8 -4
  24. package/dist/agent-registration-cXpB8cBU.mjs +199 -0
  25. package/dist/agent-registration-cXpB8cBU.mjs.map +1 -0
  26. package/dist/capabilities/Commands.d.mts +1 -1
  27. package/dist/capabilities/RunHooks.d.mts +1 -1
  28. package/dist/capabilities/Subagent.d.mts +1 -1
  29. package/dist/capabilities/Subagent.mjs +1 -1
  30. package/dist/durable/ActivityStore.d.mts +1 -1
  31. package/dist/durable/ActivityStore.mjs +1 -1
  32. package/dist/durable/Admin.d.mts +1 -1
  33. package/dist/durable/Admin.mjs +12 -10
  34. package/dist/durable/Admin.mjs.map +1 -1
  35. package/dist/durable/AgentRegistration.d.mts +2 -2
  36. package/dist/durable/AgentRegistration.mjs +4 -8
  37. package/dist/durable/AgentRegistration.mjs.map +1 -1
  38. package/dist/durable/Certification.d.mts +2 -2
  39. package/dist/durable/CommittedActivity.d.mts +1 -1
  40. package/dist/durable/CommittedActivity.mjs +1 -1
  41. package/dist/durable/Digest.d.mts +1 -1
  42. package/dist/durable/Digest.mjs +1 -1
  43. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  44. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  45. package/dist/durable/DurableFailpoint.d.mts +1 -1
  46. package/dist/durable/DurableFailpoint.mjs +2 -0
  47. package/dist/durable/DurableFailpoint.mjs.map +1 -1
  48. package/dist/durable/DurableFailpointTestControl.d.mts +1 -1
  49. package/dist/durable/EventSource.d.mts +1 -1
  50. package/dist/durable/EventSource.mjs +1 -1
  51. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  52. package/dist/durable/GitHubWorkflowSource.mjs +1 -1
  53. package/dist/durable/MessageDelivery.d.mts +3 -3
  54. package/dist/durable/MessageDelivery.mjs +1 -1
  55. package/dist/durable/MessageDeliveryStoreConformance.d.mts +39 -39
  56. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  57. package/dist/durable/PersistentHistory.d.mts +1 -1
  58. package/dist/durable/PersistentHistory.mjs +2 -2
  59. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  60. package/dist/durable/Records.d.mts +2 -2
  61. package/dist/durable/Records.mjs +2 -2
  62. package/dist/durable/Recovery.d.mts +1 -1
  63. package/dist/durable/Recovery.mjs +9 -9
  64. package/dist/durable/Recovery.mjs.map +1 -1
  65. package/dist/durable/RunJournal.d.mts +2 -2
  66. package/dist/durable/RunJournal.mjs +2 -2
  67. package/dist/durable/Schedule.d.mts +1 -1
  68. package/dist/durable/Schedule.mjs +1 -1
  69. package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
  70. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  71. package/dist/durable/ScheduleTransition.d.mts +1 -1
  72. package/dist/durable/ScheduleTransition.mjs +1 -1
  73. package/dist/durable/Scheduling.d.mts +2 -2
  74. package/dist/durable/Scheduling.mjs +1 -1
  75. package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
  76. package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
  77. package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
  78. package/dist/durable/SqlSubscriptionStore.mjs +1 -1
  79. package/dist/durable/SubmissionLedger.d.mts +1 -1
  80. package/dist/durable/SubmissionLedger.mjs +14 -13
  81. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  82. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  83. package/dist/durable/SubmissionLedgerConformance.mjs +9 -2
  84. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -1
  85. package/dist/durable/SubmissionStatus.d.mts +1 -1
  86. package/dist/durable/Subscription.d.mts +1 -1
  87. package/dist/durable/Subscription.mjs +1 -1
  88. package/dist/durable/SubscriptionInput.d.mts +1 -1
  89. package/dist/durable/SubscriptionInput.mjs +2 -2
  90. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  91. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  92. package/dist/durable/SubscriptionTools.d.mts +3 -3
  93. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  94. package/dist/durable/SubscriptionTransition.mjs +1 -1
  95. package/dist/durable/Subscriptions.d.mts +5 -5
  96. package/dist/durable/Subscriptions.mjs +1 -1
  97. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  98. package/dist/durable/ThreadContextHistory.mjs +1 -1
  99. package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
  100. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  101. package/dist/durable/ThreadInvariants.d.mts +4 -2
  102. package/dist/durable/ThreadInvariants.mjs +49 -3
  103. package/dist/durable/ThreadInvariants.mjs.map +1 -1
  104. package/dist/durable/ThreadProjection.d.mts +1 -1
  105. package/dist/durable/ThreadProjection.mjs +1 -1
  106. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  107. package/dist/durable/ThreadStore.d.mts +1 -1
  108. package/dist/durable/ThreadStore.mjs +1 -1
  109. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  110. package/dist/durable/ThreadStoreConformance.mjs +1 -1
  111. package/dist/durable/ToolReconciler.d.mts +1 -1
  112. package/dist/durable/ToolReconciler.mjs +9 -5
  113. package/dist/durable/ToolReconciler.mjs.map +1 -1
  114. package/dist/durable/WorkerHost.d.mts +1 -1
  115. package/dist/engine/AgentRuntime.d.mts +1 -1
  116. package/dist/engine/AgentRuntime.mjs +1 -1
  117. package/dist/engine/RunOptions.d.mts +1 -1
  118. package/dist/engine/RunOptions.mjs.map +1 -1
  119. package/dist/index.d.mts +11 -11
  120. package/dist/index.mjs +6 -6
  121. package/package.json +1 -1
  122. package/src/durable/Admin.ts +20 -11
  123. package/src/durable/AgentRegistration.ts +1 -5
  124. package/src/durable/DurableAgentRuntime.ts +936 -464
  125. package/src/durable/DurableFailpoint.ts +2 -0
  126. package/src/durable/Records.ts +30 -5
  127. package/src/durable/Recovery.ts +8 -8
  128. package/src/durable/RunJournal.ts +128 -51
  129. package/src/durable/SubmissionLedger.ts +13 -12
  130. package/src/durable/SubmissionLedgerConformance.ts +13 -2
  131. package/src/durable/ThreadInvariants.ts +70 -5
  132. package/src/durable/ToolReconciler.ts +7 -3
  133. package/src/durable/internal/agent-registration.ts +65 -414
  134. package/src/durable/internal/messaging-host.ts +0 -2
  135. package/src/durable/internal/worker-host.ts +34 -96
  136. package/src/engine/RunOptions.ts +13 -3
  137. package/src/engine/internal/agent-runtime.ts +160 -106
  138. package/dist/AgentRuntime-Cdvqw7l_.mjs.map +0 -1
  139. package/dist/DurableAgentRuntime-DbUvZHDZ.mjs.map +0 -1
  140. package/dist/Records-BAutSSnJ.mjs.map +0 -1
  141. package/dist/RunJournal-DRRRZmG7.mjs.map +0 -1
  142. package/dist/agent-registration-CXGDwvJH.mjs +0 -379
  143. package/dist/agent-registration-CXGDwvJH.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgentRuntime-BWOnNc0d.mjs","names":["#delegate","#recordDefect","#terminalOutcome","#terminalFailure","#terminalFailureMode","#terminalFailureHandling","IdGenerator"],"sources":["../src/engine/internal/bounded-value.ts","../src/engine/internal/primitive-delta.ts","../src/engine/internal/tool-derivative.ts","../src/engine/internal/tool-exposure.ts","../src/engine/internal/tool-telemetry.ts","../src/engine/internal/error-diagnostic.ts","../src/engine/internal/agent-runtime.ts","../src/engine/AgentRuntime.ts"],"sourcesContent":["import { DateTime, Redacted } from \"effect\";\n\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\n\nconst DEFAULT_MAX_DEPTH = 128;\nconst OBJECT_OVERHEAD_BYTES = 32;\nconst PROPERTY_OVERHEAD_BYTES = 8;\nconst dateTimeUtcPrototype = Object.getPrototypeOf(DateTime.makeUnsafe(0)) as object;\nconst redactedPrototype = Object.getPrototypeOf(Redacted.make(undefined)) as object;\n\nconst intrinsicViewPrototypes = new Set<object>([\n DataView.prototype,\n Int8Array.prototype,\n Uint8Array.prototype,\n Uint8ClampedArray.prototype,\n Int16Array.prototype,\n Uint16Array.prototype,\n Int32Array.prototype,\n Uint32Array.prototype,\n Float32Array.prototype,\n Float64Array.prototype,\n BigInt64Array.prototype,\n BigUint64Array.prototype,\n]);\n\nconst arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(\n ArrayBuffer.prototype,\n \"byteLength\",\n)?.get;\n\nconst typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype) as object;\nconst typedArrayBufferGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"buffer\")?.get;\nconst typedArrayLengthGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"length\")?.get;\nconst dataViewBufferGetter = Object.getOwnPropertyDescriptor(DataView.prototype, \"buffer\")?.get;\nconst urlConstructor = Reflect.get(globalThis, \"URL\");\n\nconst urlPrototypeDescriptor =\n typeof urlConstructor === \"function\"\n ? Object.getOwnPropertyDescriptor(urlConstructor, \"prototype\")\n : undefined;\n\nconst urlHrefGetter =\n urlPrototypeDescriptor !== undefined &&\n \"value\" in urlPrototypeDescriptor &&\n urlPrototypeDescriptor.value !== null &&\n typeof urlPrototypeDescriptor.value === \"object\"\n ? Object.getOwnPropertyDescriptor(urlPrototypeDescriptor.value, \"href\")?.get\n : undefined;\n\nconst urlPrototype =\n urlPrototypeDescriptor !== undefined &&\n \"value\" in urlPrototypeDescriptor &&\n urlPrototypeDescriptor.value !== null &&\n typeof urlPrototypeDescriptor.value === \"object\"\n ? urlPrototypeDescriptor.value\n : undefined;\n\nconst intrinsicArrayBufferByteLength = (value: object): number | undefined => {\n if (arrayBufferByteLengthGetter === undefined) return undefined;\n try {\n const byteLength = Reflect.apply(arrayBufferByteLengthGetter, value, []);\n\n return Number.isSafeInteger(byteLength) && byteLength >= 0 ? byteLength : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst intrinsicViewBackingByteLength = (value: object): number | undefined => {\n const getters = [typedArrayBufferGetter, dataViewBufferGetter];\n\n for (const getter of getters) {\n if (getter === undefined) continue;\n try {\n const buffer = Reflect.apply(getter, value, []);\n\n if (buffer !== null && typeof buffer === \"object\") {\n return intrinsicArrayBufferByteLength(buffer);\n }\n } catch {\n // Try the other supported view family without consulting user properties.\n }\n }\n\n return undefined;\n};\n\nconst intrinsicTypedArrayLength = (value: object): number | undefined => {\n if (typedArrayLengthGetter === undefined) return undefined;\n try {\n const length = Reflect.apply(typedArrayLengthGetter, value, []);\n\n return Number.isSafeInteger(length) && length >= 0 ? length : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst intrinsicUrlByteLength = (value: object): number | undefined => {\n if (urlHrefGetter === undefined) return undefined;\n try {\n const href = Reflect.apply(urlHrefGetter, value, []);\n\n return typeof href === \"string\" ? utf8ByteLength(href) + 2 : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst inspectPrototype = (\n prototype: object | null,\n isArray: boolean,\n knownSafePrototypes: ReadonlySet<object>,\n): boolean => {\n if (prototype === null) return true;\n if (isArray) {\n return prototype === Array.prototype;\n }\n\n return (\n prototype === Object.prototype ||\n prototype === dateTimeUtcPrototype ||\n knownSafePrototypes.has(prototype)\n );\n};\n\nconst isCanonicalArrayIndex = (key: string): boolean => {\n const index = Number(key);\n\n return Number.isInteger(index) && index >= 0 && index < 0xffff_ffff && String(index) === key;\n};\n\n/**\n * Conservatively measure one retained, engine-owned JavaScript value without invoking getters,\n * coercion, or `toJSON`. `undefined` means the value exceeded the allowance or its shape could not\n * be measured without executing an accessor.\n *\n * This is a memory-retention guard, not an untrusted wire boundary. Callers must first canonicalize\n * provider values into owned data because JavaScript offers no portable, trap-free Proxy test.\n * Object and property overheads deliberately make the estimate larger than the visible primitive\n * payload for ordinary response values.\n */\nexport const boundedValueFootprint = (\n root: unknown,\n maxBytes: number,\n knownSafePrototypes: ReadonlySet<object> = new Set(),\n maxDepth = DEFAULT_MAX_DEPTH,\n): number | undefined => {\n if (\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 0 ||\n !Number.isSafeInteger(maxDepth) ||\n maxDepth < 0\n ) {\n return undefined;\n }\n\n let total = 0;\n const ancestors = new WeakSet<object>();\n\n const add = (bytes: number): boolean => {\n if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > maxBytes - total) return false;\n total += bytes;\n\n return true;\n };\n\n const canMaterializeIndexedKeys = (count: number): boolean => {\n if (!Number.isSafeInteger(count) || count < 0) return false;\n if (count === 0) return true;\n const largestKeyBytes = utf8ByteLength(String(count - 1));\n const temporaryBytesPerKey = PROPERTY_OVERHEAD_BYTES + largestKeyBytes;\n\n return count <= Math.floor((maxBytes - total) / temporaryBytesPerKey);\n };\n\n const visit = (value: unknown, depth: number): boolean => {\n if (depth > maxDepth) return false;\n if (value === null) return add(4);\n switch (typeof value) {\n case \"string\":\n return add(utf8ByteLength(value) + 2);\n case \"boolean\":\n return add(4);\n case \"number\":\n return add(16);\n case \"bigint\":\n case \"symbol\":\n return false;\n case \"undefined\":\n return add(16);\n case \"function\":\n return false;\n case \"object\": {\n if (ancestors.has(value) || !add(OBJECT_OVERHEAD_BYTES)) return false;\n const prototype = Object.getPrototypeOf(value);\n let skipIndexedProperties = false;\n let indexedPropertyCount = 0;\n let supportedSpecialObject = false;\n\n if (ArrayBuffer.isView(value)) {\n if (!intrinsicViewPrototypes.has(prototype)) return false;\n const byteLength = intrinsicViewBackingByteLength(value);\n\n if (byteLength === undefined || !add(byteLength)) return false;\n if (prototype !== DataView.prototype) {\n const length = intrinsicTypedArrayLength(value);\n\n if (length === undefined) return false;\n indexedPropertyCount = length;\n }\n skipIndexedProperties = true;\n supportedSpecialObject = true;\n }\n if (!supportedSpecialObject) {\n const bufferByteLength = intrinsicArrayBufferByteLength(value);\n\n if (bufferByteLength !== undefined) {\n if (prototype !== ArrayBuffer.prototype) return false;\n if (!add(bufferByteLength)) return false;\n supportedSpecialObject = true;\n }\n }\n if (!supportedSpecialObject) {\n const urlByteLength = intrinsicUrlByteLength(value);\n\n if (urlByteLength !== undefined) {\n if (prototype !== urlPrototype) return false;\n if (!add(urlByteLength)) return false;\n supportedSpecialObject = true;\n }\n }\n let redactedValue: unknown;\n let isRedacted = false;\n\n if (prototype === redactedPrototype) {\n const labelDescriptor = Object.getOwnPropertyDescriptor(value, \"label\");\n\n if (labelDescriptor !== undefined && !(\"value\" in labelDescriptor)) return false;\n try {\n redactedValue = Redacted.value(value as Redacted.Redacted<unknown>);\n isRedacted = true;\n } catch {\n return false;\n }\n }\n\n const isArray = Array.isArray(value);\n\n if (\n !supportedSpecialObject &&\n !isRedacted &&\n !inspectPrototype(prototype, isArray, knownSafePrototypes)\n ) {\n // Maps, Sets, arbitrary class instances, and other objects can retain storage that\n // own-key traversal cannot see. Only plain data and caller-supplied exact prototypes\n // whose implementations guarantee own-property state are measurable.\n return false;\n }\n if (isArray) {\n const lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n\n if (\n lengthDescriptor === undefined ||\n !(\"value\" in lengthDescriptor) ||\n !Number.isSafeInteger(lengthDescriptor.value) ||\n lengthDescriptor.value < 0 ||\n !add(lengthDescriptor.value)\n ) {\n return false;\n }\n indexedPropertyCount = lengthDescriptor.value;\n }\n\n // `Reflect.ownKeys` eagerly allocates one string per dense array or typed-array index.\n // Reject before that allocation when even the conservative temporary key list cannot fit\n // inside the caller's allowance. Sparse arrays deliberately use their worst-case length.\n if (!canMaterializeIndexedKeys(indexedPropertyCount)) return false;\n\n ancestors.add(value);\n try {\n if (isRedacted && !visit(redactedValue, depth + 1)) return false;\n for (const key of Reflect.ownKeys(value)) {\n if (key === \"length\" && isArray) continue;\n if (typeof key === \"symbol\") return false;\n if (skipIndexedProperties && isCanonicalArrayIndex(key)) continue;\n if (!add(PROPERTY_OVERHEAD_BYTES)) return false;\n if (!add(utf8ByteLength(key))) return false;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n\n if (descriptor === undefined) return false;\n if (\"value\" in descriptor) {\n if (!visit(descriptor.value, depth + 1)) return false;\n } else {\n // Accessors and functions may retain arbitrarily large closure graphs.\n return false;\n }\n }\n\n return true;\n } finally {\n ancestors.delete(value);\n }\n }\n }\n\n return false;\n };\n\n try {\n return visit(root, 0) ? total : undefined;\n } catch {\n return undefined;\n }\n};\n","import { Option, Schema } from \"effect\";\nimport { Response } from \"effect/unstable/ai\";\n\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\nimport { boundedValueFootprint } from \"./bounded-value.ts\";\n\nconst brand = \"~effect/ai/Response/Part\";\nconst keys = [brand, \"type\", \"id\", \"delta\", \"metadata\"];\n\nconst decode = Schema.decodeUnknownOption(\n Schema.toType(Schema.Union([Response.TextDeltaPart, Response.ReasoningDeltaPart])),\n);\n\nconst overhead = (type: \"text-delta\" | \"reasoning-delta\") => ({\n source: boundedValueFootprint(\n Response.makePart(type, { id: \"\", delta: \"\" }),\n Number.MAX_SAFE_INTEGER,\n ),\n encoded: boundedValueFootprint(\n { type, id: \"\", delta: \"\", metadata: {} },\n Number.MAX_SAFE_INTEGER,\n ),\n});\n\nconst overheads = {\n \"text-delta\": overhead(\"text-delta\"),\n \"reasoning-delta\": overhead(\"reasoning-delta\"),\n};\n\n/**\n * Copy the common primitive delta into owned data before native Schema validation.\n * Descriptor checks select this optimization; they do not replace the native codec.\n * Extra fields, accessors, and nonempty metadata use the general ownership path.\n * No provider object survives, including an empty metadata object's hidden storage.\n * Unlike a generic footprint shortcut, this cannot retain an exotic backing buffer.\n */\nexport const ownPrimitiveDelta = (part: unknown, maxBytes: number) => {\n try {\n if (part === null || typeof part !== \"object\") return undefined;\n if (Array.isArray(part) || ArrayBuffer.isView(part)) return undefined;\n const prototype = Object.getPrototypeOf(part);\n\n if (prototype !== Object.prototype && prototype !== null) return undefined;\n if (Reflect.ownKeys(part).length !== keys.length) return undefined;\n const snapshot: Record<string, unknown> = {};\n\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(part, key);\n\n if (descriptor === undefined || !(\"value\" in descriptor)) return undefined;\n snapshot[key] = descriptor.value;\n }\n const { type, id, delta, metadata } = snapshot;\n\n if (type !== \"text-delta\" && type !== \"reasoning-delta\") return undefined;\n if (typeof id !== \"string\" || typeof delta !== \"string\") return undefined;\n if (metadata === null || typeof metadata !== \"object\") return undefined;\n if (Array.isArray(metadata) || ArrayBuffer.isView(metadata)) return undefined;\n const metadataPrototype = Object.getPrototypeOf(metadata);\n\n if (metadataPrototype !== Object.prototype && metadataPrototype !== null) return undefined;\n if (Reflect.ownKeys(metadata).length !== 0) return undefined;\n const fixed = overheads[type];\n\n if (fixed.source === undefined || fixed.encoded === undefined) return undefined;\n const bytes = utf8ByteLength(id) + utf8ByteLength(delta);\n\n if (bytes + fixed.source > maxBytes || bytes + fixed.encoded > maxBytes) return undefined;\n // Never pass the provider's metadata object (or any other object) to the decoder.\n snapshot.metadata = {};\n const validated = decode(snapshot);\n\n if (Option.isNone(validated)) return undefined;\n\n return { ownedPart: validated.value, retainedBytes: bytes + fixed.encoded };\n } catch {\n // Reflection may throw for proxies. The general path owns the typed failure.\n return undefined;\n }\n};\n","import { Cause, Effect, ErrorReporter, Exit, Stream } from \"effect\";\n\nimport type { RunToolFailureObserver, ToolFailureObservation } from \"../RunOptions.ts\";\n\n/** @internal Only the explicitly installed trusted observer sees this live value. */\nexport const deliverToolFailure = (\n observer: RunToolFailureObserver,\n observation: ToolFailureObservation,\n): Effect.Effect<void> =>\n isolateToolDerivative(Effect.suspend(() => observer.observe(observation)));\n\n/**\n * Report failures of derivative work without consuming external interruption. Reporter defects\n * are isolated too. Neither observer delivery nor telemetry owns the authoritative Tool outcome.\n */\nconst reportDerivativeCause = <E>(cause: Cause.Cause<E>): Effect.Effect<void> => {\n const reportableReasons: Array<Cause.Reason<E>> = [];\n const interruptionReasons: Array<Cause.Interrupt> = [];\n\n for (const reason of cause.reasons) {\n if (Cause.isInterruptReason(reason)) interruptionReasons.push(reason);\n else reportableReasons.push(reason);\n }\n\n const reportExit =\n reportableReasons.length === 0\n ? Effect.succeed(Exit.succeed(undefined))\n : Effect.exit(ErrorReporter.report(Cause.fromReasons(reportableReasons)));\n\n return Effect.flatMap(reportExit, (exit) => {\n if (Exit.isFailure(exit)) {\n for (const reason of exit.cause.reasons) {\n if (Cause.isInterruptReason(reason)) interruptionReasons.push(reason);\n }\n }\n\n return interruptionReasons.length === 0\n ? Effect.void\n : Effect.failCause(Cause.fromReasons<never>(interruptionReasons));\n });\n};\n\n/** @internal Isolate reporting defects independently of Logger/Tracer configuration. */\nexport const isolateToolDerivative = <R>(\n effect: Effect.Effect<void, never, R>,\n): Effect.Effect<void, never, R> => effect.pipe(Effect.catchCause(reportDerivativeCause));\n\n/**\n * @internal Emit one authoritative value, then run derivative work from either the next pull or\n * structured finalization on early close. Telemetry and application observation share this one\n * owner. A started action is never retried after interruption.\n */\nexport const emitThenAfter = <A, E, R, E2, R2>(\n event: Effect.Effect<A, E, R>,\n after: Effect.Effect<void, E2, R2>,\n): Stream.Stream<A, E | E2, R | R2> =>\n Stream.unwrap(\n Effect.sync(() => {\n let firstPull = true;\n let afterPhase: \"unarmed\" | \"pending\" | \"running\" | \"completed\" = \"unarmed\";\n\n const runAfter = Effect.suspend((): Effect.Effect<void, E2, R2> => {\n if (afterPhase !== \"pending\") return Effect.void;\n afterPhase = \"running\";\n\n return after.pipe(\n Effect.onExit(() =>\n Effect.sync(() => {\n afterPhase = \"completed\";\n }),\n ),\n );\n });\n\n const pull = Effect.suspend(\n (): Effect.Effect<readonly [A], E | E2 | Cause.Done<void>, R | R2> => {\n if (firstPull) {\n return Effect.map(event, (value) => {\n firstPull = false;\n afterPhase = \"pending\";\n\n return [value] as const;\n });\n }\n\n return Effect.andThen(runAfter, Cause.done());\n },\n );\n\n return Stream.fromPull(Effect.succeed(pull)).pipe(\n Stream.ensuring(\n // A typed `after` failure remains visible to an ordinary second pull. Cleanup owns\n // only early close; capture its Exit after terminal annotation. The isolated Tool span\n // derives its export status from that annotation even if cleanup consumes the private\n // span marker. External interruption still escapes.\n Effect.exit(Effect.interruptible(runAfter)).pipe(\n Effect.flatMap((exit) => {\n if (Exit.isSuccess(exit)) return Effect.void;\n\n return reportDerivativeCause(exit.cause);\n }),\n ),\n ),\n );\n }),\n );\n","import { Context, Effect, Schema } from \"effect\";\nimport { Tool, type LanguageModel } from \"effect/unstable/ai\";\n\nimport type { AnyDefinition } from \"../../core/Agent.ts\";\nimport { ModelProtocolError } from \"../../core/AgentError.ts\";\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\nimport {\n getToolExecutionKind,\n isSubagentToolAllowed,\n type SubagentGrant,\n} from \"../../core/SubagentContract.ts\";\nimport {\n AdditionalToolCatalog,\n IncludesCatalogDocumentation,\n DiscoveryTool,\n Limits,\n PinnedTool,\n Selection,\n Snapshot,\n ToolNames,\n ToolNamespace,\n} from \"../../core/ToolExposure.ts\";\nimport { ContextRolloverTool } from \"../ContextWindow.ts\";\nimport { getToolExecutionClass } from \"../DurableStep.ts\";\nimport { RunToolVisibility, type CatalogEntry, type VisibilityRequest } from \"../ToolExposure.ts\";\n\nconst invalid = (message: string) => ModelProtocolError.make({ message });\n\nexport const decodeSelection = (value: unknown) =>\n Schema.decodeUnknownEffect(Selection)(value).pipe(\n Effect.mapError(() => invalid(\"Invalid Tool exposure selection\")),\n );\n\nexport const decodeSnapshot = (value: unknown) =>\n Schema.decodeUnknownEffect(Snapshot)(value).pipe(\n Effect.mapError(() => invalid(\"Invalid recorded Tool exposure snapshot\")),\n Effect.map((snapshot) =>\n Object.freeze(\n Snapshot.make({\n exposedToolNames: Object.freeze([...snapshot.exposedToolNames]),\n ...(snapshot.selection === undefined\n ? {}\n : {\n selection: Object.freeze(\n Selection.make({ toolNames: Object.freeze([...snapshot.selection.toolNames]) }),\n ),\n }),\n }),\n ),\n ),\n );\n\nexport const eligibleCatalog = Effect.fn(\"ToolExposure.eligibleCatalog\")(function* (\n definition: AnyDefinition,\n request: Omit<VisibilityRequest, \"toolNames\">,\n grant: SubagentGrant | undefined,\n depth: number,\n) {\n const visibility = yield* RunToolVisibility;\n const entries: Array<CatalogEntry> = [];\n\n for (const tool of Object.values(definition.toolkit.tools)) {\n if (\n Context.get(tool.annotations, DiscoveryTool) &&\n (getToolExecutionKind(tool.annotations) !== \"ordinary\" ||\n getToolExecutionClass(tool) !== \"readonly\")\n )\n return yield* invalid(\"Discovery requires ordinary readonly Tools\");\n const namespace = Context.get(tool.annotations, ToolNamespace);\n\n entries.push({\n kind: \"native\",\n tool,\n nativeToolName: tool.name,\n ...(namespace === undefined ? {} : { namespace }),\n });\n for (const extra of Context.get(tool.annotations, AdditionalToolCatalog)) {\n entries.push({ kind: \"code-mode\", ...extra, nativeToolName: tool.name });\n }\n }\n const names = [...new Set(entries.map((entry) => entry.tool.name))];\n\n const visible =\n visibility === undefined ? names : yield* visibility.visible({ ...request, toolNames: names });\n\n const checked =\n visibility === undefined\n ? visible\n : yield* Schema.decodeEffect(ToolNames)(visible).pipe(\n Effect.mapError(() => invalid(\"Host Tool visibility returned invalid names\")),\n );\n\n if (checked.some((name) => !names.includes(name)))\n return yield* invalid(\"Host Tool visibility returned an unregistered name\");\n const allowed = new Set(checked);\n\n const permits = (tool: Tool.Any) =>\n allowed.has(tool.name) && isSubagentToolAllowed(grant, depth, tool.name, tool.annotations);\n\n for (const outer of Object.values(definition.toolkit.tools)) {\n if (\n permits(outer) &&\n Context.get(outer.annotations, IncludesCatalogDocumentation) &&\n Context.get(outer.annotations, AdditionalToolCatalog).some((entry) => !permits(entry.tool))\n ) {\n return yield* invalid(\n \"A Tool description includes hidden catalogue declarations; configure includeDeclarations: false\",\n );\n }\n }\n\n return Object.freeze(\n entries\n .filter((entry) => {\n const outer = definition.toolkit.tools[entry.nativeToolName];\n\n return outer !== undefined && permits(outer) && permits(entry.tool);\n })\n .map((entry) => Object.freeze(entry)),\n );\n});\n\nexport const validateSelection = Effect.fn(\"ToolExposure.validateSelection\")(function* (\n value: unknown,\n definition: AnyDefinition,\n entries: ReadonlyArray<CatalogEntry>,\n requireEligible = true,\n) {\n const selection = yield* decodeSelection(value);\n\n const eligible = new Set(\n entries.filter((entry) => entry.kind === \"native\").map((entry) => entry.nativeToolName),\n );\n\n if (\n selection.toolNames.some(\n (name) =>\n !Object.hasOwn(definition.toolkit.tools, name) || (requireEligible && !eligible.has(name)),\n )\n ) {\n return yield* invalid(\"Tool selection names a Tool outside the eligible registered toolkit\");\n }\n\n return Selection.make({ toolNames: Object.freeze([...selection.toolNames]) });\n});\n\nexport const exposureSnapshot = Effect.fn(\"ToolExposure.exposureSnapshot\")(function* (\n definition: AnyDefinition,\n selection: Selection | undefined,\n entries: ReadonlyArray<CatalogEntry>,\n transformer?: LanguageModel.CodecTransformer,\n only?: ReadonlyArray<string>,\n) {\n const native = entries.filter((entry) => entry.kind === \"native\").map((entry) => entry.tool);\n const progressive = definition.toolExposure !== undefined || selection !== undefined;\n\n const mandatory = Object.values(definition.toolkit.tools).filter(\n (tool) =>\n Context.get(tool.annotations, DiscoveryTool) ||\n Context.get(tool.annotations, ContextRolloverTool) ||\n (definition.completion?.required === true && definition.completion.tool === tool.name),\n );\n\n if (\n progressive &&\n mandatory.some((tool) => !native.some((candidate) => candidate.name === tool.name))\n ) {\n return yield* invalid(\"A mandatory Tool is excluded by host visibility or the inherited grant\");\n }\n\n // Explicit pins affect selection, never eligibility. Hosts may disable a common action\n // without disabling the Run; protocol-required Tools still fail closed above.\n const pinned = native.filter(\n (tool) => Context.get(tool.annotations, PinnedTool) || mandatory.includes(tool),\n );\n\n if (selection !== undefined) yield* validateSelection(selection, definition, entries, false);\n const selected = selection === undefined ? undefined : new Set(selection.toolNames);\n\n const names = native\n .filter((tool) => selected === undefined || selected.has(tool.name) || pinned.includes(tool))\n .map((tool) => tool.name)\n .filter((name) => only === undefined || only.includes(name));\n\n if (progressive) {\n const limits = yield* Schema.decodeEffect(Limits)({\n maxTools: definition.toolExposure?.maxTools ?? 64,\n maxSchemaBytes: definition.toolExposure?.maxSchemaBytes ?? 262_144,\n }).pipe(Effect.mapError(() => invalid(\"Invalid Tool exposure bounds\")));\n\n if (names.length > limits.maxTools)\n return yield* invalid(\"Tool exposure exceeds the configured Tool count bound\");\n\n const bytes = yield* Effect.try({\n try: () =>\n utf8ByteLength(\n JSON.stringify(\n names.map((name) => {\n const tool = definition.toolkit.tools[name];\n\n if (tool === undefined) throw new Error(\"Selected Tool is unavailable\");\n\n return Tool.isProviderDefined(tool)\n ? { type: tool.providerName, args: tool.args }\n : {\n name,\n description: Tool.getDescription(tool),\n parameters: Tool.getJsonSchema(tool, { transformer }),\n };\n }),\n ),\n ),\n catch: () => invalid(\"A selected Tool schema cannot be rendered\"),\n });\n\n if (bytes > limits.maxSchemaBytes)\n return yield* invalid(\"Tool exposure exceeds the configured schema byte bound\");\n }\n\n return yield* decodeSnapshot({\n exposedToolNames: names,\n ...(selection === undefined ? {} : { selection }),\n });\n});\n","import {\n Cause,\n Context,\n Effect,\n ErrorReporter,\n Exit,\n type Fiber,\n Layer,\n Option,\n Stream,\n Tracer,\n} from \"effect\";\nimport { AiError, type Tool } from \"effect/unstable/ai\";\n\nimport type { ToolFailureHandling } from \"../../core/RunEvent.ts\";\nimport { isolateToolDerivative } from \"./tool-derivative.ts\";\n\n/**\n * @internal Payload-free control signal used only to close the canonical Tool span with a failed\n * Exit. It is removed immediately outside that span and never enters the public error channel.\n */\nexport class ToolSpanFailure extends AiError.AiError.extend<ToolSpanFailure>(\n \"@effect-agent/engine/ToolSpanFailure\",\n)({}) {\n override readonly name = \"ToolCallFailed\";\n\n /** Schema-safe factory retaining the generated constructor required by Effect Schema. */\n static marker(): ToolSpanFailure {\n return ToolSpanFailure.make({\n module: \"effect-agent\",\n method: \"execute_tool\",\n reason: AiError.UnknownError.make({\n description: \"Tool execution reached a failed terminal state\",\n }),\n });\n }\n}\n\nconst TOOL_SPAN_FAILURE_MARKER_ATTRIBUTE = \"@effect-agent/engine/ToolSpanFailureMarker\";\n\nconst terminalOutcomeTokens = new WeakMap<\n object,\n {\n readonly outcome: \"success\" | \"failure\";\n readonly failureMarker: ToolSpanFailure | undefined;\n readonly failureHandling: ToolFailureHandling | undefined;\n readonly failureMode: Tool.FailureMode | undefined;\n }\n>();\n\n/** @internal Annotate one completed attempt and hand its existing marker to the isolated span. */\nexport const annotateToolSpanTerminalOutcome = (\n outcome: \"success\" | \"failure\",\n failureMarker?: ToolSpanFailure,\n failureHandling?: ToolFailureHandling,\n failureMode?: Tool.FailureMode,\n): Effect.Effect<void> => {\n const token = {};\n\n terminalOutcomeTokens.set(token, { outcome, failureMarker, failureHandling, failureMode });\n\n return Effect.annotateCurrentSpan({\n \"effect_agent.tool.outcome\": outcome,\n [TOOL_SPAN_FAILURE_MARKER_ATTRIBUTE]: token,\n });\n};\n\nexport const stripToolSpanFailures = <E>(\n cause: Cause.Cause<E | ToolSpanFailure>,\n marker: ToolSpanFailure,\n): { readonly found: boolean; readonly residual: Cause.Cause<E | ToolSpanFailure> } => {\n const found = cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error === marker,\n );\n\n if (!found) {\n // Effect v4 Cause is a flat collection of Reasons. Object-identity absence proves only that\n // this invocation's marker is absent: another ToolSpanFailure may still be a genuine handler\n // failure, so retain both the exact Cause object and its complete error union.\n return { found: false, residual: cause };\n }\n\n const reasons = cause.reasons.filter((reason) => {\n if (Cause.isFailReason(reason) && reason.error === marker) {\n return false;\n }\n\n return true;\n });\n\n return { found: true, residual: Cause.fromReasons(reasons) };\n};\n\n/** @internal Remove only the private marker and restore the saved Cause plus every residual. */\nexport const restoreToolSpanFailureCause = <E, Original>(\n cause: Cause.Cause<E | ToolSpanFailure>,\n marker: ToolSpanFailure,\n original: Cause.Cause<Original> | undefined,\n): {\n readonly found: boolean;\n readonly restored: Cause.Cause<E | Original | ToolSpanFailure>;\n} => {\n const { found, residual } = stripToolSpanFailures(cause, marker);\n\n return {\n found,\n restored: original === undefined ? residual : Cause.combine(original, residual),\n };\n};\n\nconst MAX_REPORTED_SPAN_LIFECYCLE_DEFECTS = 16;\n\n/** Content-free marker used only to close a delegate that cannot be wrapped safely. */\nclass ToolSpanLifecycleFailure extends Error {\n override readonly name = \"ToolSpanLifecycleFailure\";\n\n constructor() {\n super(\"Tool span lifecycle failed\");\n }\n}\n\n/**\n * @internal Guard one host span so synchronous exporter defects cannot alter Tool execution.\n * The wrapper retains the span contract for Effect while forwarding every measurement to the host.\n */\nclass IsolatedToolSpan implements Tracer.Span {\n readonly _tag = \"Span\";\n readonly name: string;\n readonly spanId: string;\n readonly traceId: string;\n readonly parent: Tracer.Span[\"parent\"];\n readonly annotations: Tracer.Span[\"annotations\"];\n readonly attributes = new Map<string, unknown>();\n readonly links: Array<Tracer.SpanLink>;\n readonly sampled: boolean;\n readonly kind: Tracer.SpanKind;\n status: Tracer.SpanStatus;\n\n readonly #delegate: Tracer.Span;\n readonly #recordDefect: (defect: unknown) => void;\n #terminalOutcome: \"success\" | \"failure\" | undefined;\n #terminalFailure: ToolSpanFailure | undefined;\n #terminalFailureHandling: ToolFailureHandling | undefined;\n #terminalFailureMode: Tool.FailureMode | undefined;\n\n constructor(\n delegate: Tracer.Span,\n options: Parameters<Tracer.Tracer[\"span\"]>[0],\n recordDefect: (defect: unknown) => void,\n ) {\n this.#delegate = delegate;\n this.#recordDefect = recordDefect;\n this.name = options.name;\n this.spanId = delegate.spanId;\n this.traceId = delegate.traceId;\n this.parent = options.parent;\n this.annotations = options.annotations;\n this.links = [...options.links];\n // The host tracer owns the final sampling decision. Reading it here keeps that access inside\n // the caller's existing creation try/fallback together with span allocation and identifiers.\n this.sampled = delegate.sampled;\n this.kind = options.kind;\n this.status = { _tag: \"Started\", startTime: options.startTime };\n }\n\n end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n if (this.status._tag === \"Ended\") return;\n\n // Early downstream closure can own terminal telemetry from a no-fail stream finalizer, where\n // the private typed marker is intentionally captured because there is no consumer left to\n // observe it. Once present, the bounded outcome annotation is authoritative for this completed\n // attempt even if downstream cancellation or telemetry interruption determines the channel Exit.\n const exportedExit =\n this.#terminalOutcome === \"failure\"\n ? Exit.fail(this.#terminalFailure ?? new ToolSpanLifecycleFailure())\n : this.#terminalOutcome === \"success\"\n ? Exit.succeed(undefined)\n : exit;\n\n this.status = {\n _tag: \"Ended\",\n startTime: this.status.startTime,\n endTime,\n exit: exportedExit,\n };\n if (this.#terminalOutcome !== undefined) {\n // The public attribute map is intentionally mutable for ordinary instrumentation. Restore\n // this framework-owned value from the authenticated private token at the export boundary so\n // handler or telemetry code cannot forge the canonical terminal classification.\n this.attributes.set(\"effect_agent.tool.outcome\", this.#terminalOutcome);\n try {\n this.#delegate.attribute(\"effect_agent.tool.outcome\", this.#terminalOutcome);\n } catch (defect) {\n this.#recordDefect(defect);\n }\n }\n for (const [key, value] of [\n [\"effect_agent.tool.failure_mode\", this.#terminalFailureMode],\n [\"effect_agent.tool.failure_handling\", this.#terminalFailureHandling],\n ] as const) {\n if (value !== undefined) {\n this.attributes.set(key, value);\n try {\n this.#delegate.attribute(key, value);\n } catch (defect) {\n this.#recordDefect(defect);\n }\n } else if (key === \"effect_agent.tool.failure_handling\") {\n this.attributes.delete(key);\n }\n }\n try {\n this.#delegate.end(endTime, exportedExit);\n } catch (defect) {\n this.#recordDefect(defect);\n }\n }\n\n attribute(key: string, value: unknown): void {\n if (key === TOOL_SPAN_FAILURE_MARKER_ATTRIBUTE) {\n if (typeof value === \"object\" && value !== null) {\n const terminal = terminalOutcomeTokens.get(value);\n\n if (terminal !== undefined) {\n this.#terminalOutcome = terminal.outcome;\n this.#terminalFailure = terminal.failureMarker;\n this.#terminalFailureHandling = terminal.failureHandling;\n this.#terminalFailureMode = terminal.failureMode;\n }\n }\n\n return;\n }\n // Only the authenticated terminal token may classify a failure's route.\n if (key === \"effect_agent.tool.failure_handling\") return;\n this.attributes.set(key, value);\n try {\n this.#delegate.attribute(key, value);\n } catch (defect) {\n this.#recordDefect(defect);\n }\n }\n\n event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {\n try {\n this.#delegate.event(name, startTime, attributes);\n } catch (defect) {\n this.#recordDefect(defect);\n }\n }\n\n addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {\n this.links.push(...links);\n try {\n this.#delegate.addLinks(links);\n } catch (defect) {\n this.#recordDefect(defect);\n }\n }\n}\n\ninterface IsolatedToolTracer {\n readonly tracer: Tracer.Tracer;\n readonly reportLifecycleDefects: Effect.Effect<void>;\n}\n\n/**\n * @internal Isolate the complete canonical span lifecycle. A creation defect receives a local,\n * non-exported span so the handler still runs; delegate method/finalization defects are retained\n * as bounded reporter diagnostics and never enter the handler stream Cause.\n */\nexport const makeIsolatedToolTracer = (delegate: Tracer.Tracer): IsolatedToolTracer => {\n const defects: Array<unknown> = [];\n\n const recordDefect = (defect: unknown): void => {\n if (defects.length < MAX_REPORTED_SPAN_LIFECYCLE_DEFECTS) defects.push(defect);\n };\n\n let delegateContext: Tracer.Tracer[\"context\"];\n\n try {\n delegateContext = delegate.context?.bind(delegate);\n } catch (defect) {\n recordDefect(defect);\n delegateContext = undefined;\n }\n\n const context: Tracer.Tracer[\"context\"] =\n delegateContext === undefined\n ? undefined\n : <X>(primitive: Tracer.EffectPrimitive<X>, fiber: Fiber.Fiber<unknown, unknown>): X => {\n type Evaluation =\n | { readonly _tag: \"Pending\" }\n | { readonly _tag: \"Succeeded\"; readonly value: X }\n | { readonly _tag: \"Failed\"; readonly error: unknown };\n let evaluation: Evaluation = { _tag: \"Pending\" };\n const currentEvaluation = (): Evaluation => evaluation;\n\n const evaluate = (currentFiber: Fiber.Fiber<unknown, unknown>): X => {\n switch (evaluation._tag) {\n case \"Succeeded\":\n return evaluation.value;\n case \"Failed\":\n throw evaluation.error;\n case \"Pending\": {\n try {\n const value = primitive[\"~effect/Effect/evaluate\"](currentFiber);\n\n evaluation = { _tag: \"Succeeded\", value };\n\n return value;\n } catch (error) {\n evaluation = { _tag: \"Failed\", error };\n throw error;\n }\n }\n }\n };\n\n const guardedPrimitive: Tracer.EffectPrimitive<X> = {\n [\"~effect/Effect/evaluate\"]: evaluate,\n };\n\n try {\n delegateContext(guardedPrimitive, fiber);\n } catch (defect) {\n const observed = currentEvaluation();\n\n switch (observed._tag) {\n case \"Failed\":\n throw observed.error;\n case \"Succeeded\":\n recordDefect(defect);\n\n return observed.value;\n case \"Pending\":\n recordDefect(defect);\n\n return evaluate(fiber);\n }\n }\n const observed = currentEvaluation();\n\n switch (observed._tag) {\n case \"Failed\":\n throw observed.error;\n case \"Succeeded\":\n return observed.value;\n case \"Pending\":\n return evaluate(fiber);\n }\n };\n\n const tracer = Tracer.make({\n context,\n span(options) {\n let delegateSpan: Tracer.Span;\n\n try {\n delegateSpan = delegate.span(options);\n } catch (defect) {\n recordDefect(defect);\n\n // This native span is deliberately not handed to the host exporter. It only preserves\n // Effect's current-span contract so Tool behavior continues without observable tracing.\n return new Tracer.NativeSpan(options);\n }\n try {\n return new IsolatedToolSpan(delegateSpan, options, recordDefect);\n } catch (defect) {\n recordDefect(defect);\n try {\n // Allocation succeeded, so best-effort close the host span without attaching the raw\n // wrapper defect. The start time gives this abandoned measurement a bounded duration.\n delegateSpan.end(options.startTime, Exit.fail(new ToolSpanLifecycleFailure()));\n } catch (closeDefect) {\n recordDefect(closeDefect);\n }\n\n return new Tracer.NativeSpan(options);\n }\n },\n });\n\n const reportLifecycleDefects = Effect.suspend(() => {\n const pending = defects.splice(0);\n\n return Effect.forEach(\n pending,\n (defect) => isolateToolDerivative(ErrorReporter.report(Cause.die(defect))),\n { discard: true },\n );\n });\n\n return { tracer, reportLifecycleDefects };\n};\n\nexport interface ToolSpanTelemetryService {\n /** Measure one Tool handler attempt while isolating every host span-lifecycle defect. */\n readonly isolateSpanLifecycle: <A, E, R>(\n stream: Stream.Stream<A, E, R>,\n ) => Stream.Stream<A, E, R>;\n /** Effect counterpart used by programmatic Tool handlers nested inside an outer Tool stream. */\n readonly isolateEffectSpanLifecycle: <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n /** Keep Effect AI implementation annotations local while preserving host-owned handler spans. */\n readonly isolateToolkitHandle: <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n}\n\n/**\n * @internal Engine-owned span-lifecycle policy. The AgentRuntime composition boundary builds this\n * capability from the host's ambient Tracer; Tool execution consumes it without selecting,\n * decorating, or locally providing a Tracer implementation.\n */\nexport class ToolSpanTelemetry extends Context.Service<\n ToolSpanTelemetry,\n ToolSpanTelemetryService\n>()(\"@effect-agent/engine/ToolSpanTelemetry\") {\n static readonly layer: Layer.Layer<ToolSpanTelemetry> = Layer.effect(\n ToolSpanTelemetry,\n Effect.map(Tracer.Tracer, (delegate) =>\n ToolSpanTelemetry.of({\n isolateEffectSpanLifecycle: (effect) =>\n Effect.suspend(() => {\n const isolated = makeIsolatedToolTracer(delegate);\n\n return effect.pipe(\n Effect.provideService(Tracer.Tracer, isolated.tracer),\n // `Effect.ensuring` runs after the measured span's finalizer, matching the Stream\n // boundary below while keeping the broker's value and error channels unchanged.\n Effect.ensuring(isolated.reportLifecycleDefects),\n );\n }),\n isolateToolkitHandle: (effect) =>\n Effect.currentSpan.pipe(\n Effect.option,\n Effect.flatMap((parentOption) => {\n if (Option.isNone(parentOption)) return effect;\n const parent = parentOption.value;\n\n // Effect AI annotates its current span with decoded Tool parameters before forking\n // the handler. Keep those annotations on a local span that is never handed to the\n // host tracer. DisablePropagation makes explicit handler spans filter past this\n // implementation parent and attach to the canonical execute_tool span instead.\n const local = new Tracer.NativeSpan({\n name: \"AgentRuntime.toolkit.handle\",\n parent: Option.some(parent),\n annotations: Context.add(Context.empty(), Tracer.DisablePropagation, true),\n links: [],\n startTime: 0n,\n kind: \"internal\",\n sampled: parent.sampled,\n });\n\n return effect.pipe(\n Effect.withParentSpan(local),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n local.end(0n, exit);\n }),\n ),\n );\n }),\n ),\n isolateSpanLifecycle: (stream) =>\n Stream.unwrap(\n Effect.sync(() => {\n const isolated = makeIsolatedToolTracer(delegate);\n\n return stream.pipe(\n Stream.provideService(Tracer.Tracer, isolated.tracer),\n // `Stream.ensuring` runs after the canonical span's own finalizer, so creation,\n // annotation, and close defects are reported outside this execution's measurement.\n Stream.ensuring(isolated.reportLifecycleDefects),\n );\n }),\n ),\n }),\n ),\n );\n}\n","const DIAGNOSTIC_MESSAGE_LIMIT = 4_096;\nconst DIAGNOSTIC_TAG_LIMIT = 128;\n\nconst boundedDiagnostic = (value: string, maxCharacters: number): string =>\n value.length <= maxCharacters ? value : value.slice(0, maxCharacters);\n\nconst ownStringDiagnostic = (\n input: unknown,\n key: \"message\" | \"_tag\",\n maxCharacters: number,\n): string | undefined => {\n if (input === null || (typeof input !== \"object\" && typeof input !== \"function\")) {\n return undefined;\n }\n try {\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n\n return descriptor !== undefined && \"value\" in descriptor && typeof descriptor.value === \"string\"\n ? boundedDiagnostic(descriptor.value, maxCharacters)\n : undefined;\n } catch {\n return undefined;\n }\n};\n\n/** Total, bounded projection for opaque failures. It never invokes arbitrary coercion hooks. */\nexport const errorMessage = (error: unknown): string => {\n const message = ownStringDiagnostic(error, \"message\", DIAGNOSTIC_MESSAGE_LIMIT);\n\n if (message !== undefined) return message;\n\n return typeof error === \"string\"\n ? boundedDiagnostic(error, DIAGNOSTIC_MESSAGE_LIMIT)\n : \"Unknown error\";\n};\n\n/** Total, bounded tag projection for opaque failures. */\nexport const errorTag = (error: unknown): string =>\n ownStringDiagnostic(error, \"_tag\", DIAGNOSTIC_TAG_LIMIT) ?? \"UnknownError\";\n","import type { Take } from \"effect\";\nimport {\n Cause,\n Channel,\n Clock,\n Context,\n DateTime,\n Duration,\n Effect,\n Equal,\n Exit,\n Fiber,\n Layer,\n Metric,\n Option,\n PubSub,\n Queue,\n Result,\n Schema,\n SchemaGetter,\n Scope,\n Semaphore,\n Stream,\n Tracer,\n} from \"effect\";\nimport { Tool, AiError, LanguageModel, Model, Prompt, Response, Toolkit } from \"effect/unstable/ai\";\n\nimport type * as Agent from \"../../core/Agent.ts\";\nimport {\n type CompletionToolDeclaration,\n type CompletionFromToolDeclaration,\n type Definition,\n type InputPromptSource,\n type InstructionSource,\n type RunDispositionDeclaration,\n} from \"../../core/Agent.ts\";\nimport {\n AgentApprovalDenied,\n AgentApprovalPending,\n AgentInputError,\n AgentOutputError,\n AgentRunDispositionError,\n AgentToolAuthorizationDenied,\n AgentPolicyError,\n ContextBudgetError,\n ContextOverflowError,\n ModelProtocolError,\n} from \"../../core/AgentError.ts\";\nimport { type AgentPolicy } from \"../../core/AgentPolicy.ts\";\nimport { Emitter, Update, UpdateError } from \"../../core/AgentUpdates.ts\";\nimport {\n type AgentId,\n ThreadId,\n type DelegationId,\n ReceiptId,\n SubmissionId,\n RunId,\n ToolCallId,\n type TurnId,\n} from \"../../core/Identifiers.ts\";\nimport { IdGenerator } from \"../../core/IdGenerator.ts\";\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\nimport { IdempotencyKey } from \"../../core/Receipt.ts\";\nimport {\n AgentUpdateEmitted,\n ApprovalRequested,\n BudgetWarning,\n CompactionPerformed,\n ModelStarted,\n ReasoningDelta,\n RunCompleted,\n RunFailed,\n RunStarted,\n RunSuspended,\n SubagentCompleted,\n SubagentFailed,\n SubagentInterrupted,\n SubagentJoined,\n SubagentProgress,\n SubagentRequested,\n SubagentStarted,\n TextDelta,\n ToolCallDeclared,\n ToolCallFailed,\n type ToolFailureHandling,\n type RunEvent,\n ToolCallStarted,\n ToolCallSucceeded,\n ToolProgress,\n TurnCompleted,\n TurnStarted,\n} from \"../../core/RunEvent.ts\";\nimport {\n DelegationDepth,\n getToolExecutionKind,\n isSubagentToolAllowed,\n type SubagentGrant,\n type SubagentBudgetReservation,\n SubagentParentLink,\n} from \"../../core/SubagentContract.ts\";\nimport type { Selection } from \"../../core/ToolExposure.ts\";\nimport { AdditionalToolCatalog, DiscoveryTool, Snapshot } from \"../../core/ToolExposure.ts\";\nimport {\n ToolParameterRejection,\n TruncatedToolResult,\n applyToolResultBounds,\n unserializableToolResult,\n type ToolResultBounds,\n} from \"../../core/ToolResult.ts\";\nimport {\n InputTokenUsage,\n ModelCallUsage,\n ModelResponseIdentity,\n OutputTokenUsage,\n RunTotals,\n RunUsageReport,\n emptyRunTotals,\n unknownRunTotals,\n sumRunTotals,\n type UsageCompleteness,\n} from \"../../core/Usage.ts\";\nimport { FrameworkMessage, type WorkerBudgetScope } from \"../../core/Worker.ts\";\nimport { MessagingHost } from \"../MessagingHost.ts\";\nimport { SubagentHost } from \"../SubagentHost.ts\";\nimport { ThreadHistory, ThreadHistoryError } from \"../ThreadHistory.ts\";\nimport { CurrentToolCatalog, RunToolVisibility, type CatalogEntry } from \"../ToolExposure.ts\";\nimport { boundedValueFootprint } from \"./bounded-value.ts\";\nimport { insertOutputContract, isTextOutput, outputSchemaContract } from \"./output-contract.ts\";\nimport { ownPrimitiveDelta } from \"./primitive-delta.ts\";\nimport {\n boundedCanonicalJsonSnapshot,\n boundedJsonSnapshot,\n type BoundedJsonSnapshot,\n} from \"./provider-result-staging.ts\";\nimport { deliverToolFailure, emitThenAfter, isolateToolDerivative } from \"./tool-derivative.ts\";\nimport {\n decodeSelection,\n decodeSnapshot,\n eligibleCatalog,\n exposureSnapshot,\n validateSelection,\n} from \"./tool-exposure.ts\";\nimport {\n annotateToolSpanTerminalOutcome,\n restoreToolSpanFailureCause,\n stripToolSpanFailures,\n ToolSpanFailure,\n ToolSpanTelemetry,\n type ToolSpanTelemetryService,\n} from \"./tool-telemetry.ts\";\n\ntype RuntimeProgram<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 definition: Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n Toolkit.Toolkit<Tools>,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly instructions: InstructionSource<\n InputSchema[\"Type\"],\n NoInfer<InstructionError>,\n NoInfer<InstructionRequirements>\n >;\n readonly inputPrompt?: InputPromptValue | undefined;\n };\n};\n\n/**\n * Structural shape of an Agent Binding accepted by the interpreter and by\n * `AgentSpawner.spawn`: a model-agnostic Definition paired with an explicit\n * native model Layer whose requirements stay visible. The Layer must provide\n * LanguageModel, ProviderName, and ModelName, including after requirement capture.\n */\nexport type RuntimeBinding<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n _Provider,\n ModelProvides,\n ModelRequires,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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> = RuntimeProgram<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n> & {\n readonly model: Layer.Layer<\n LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName | ModelProvides,\n never,\n ModelRequires\n >;\n};\n\ntype InstructionResultOf<Instructions, Input> = Instructions extends (input: Input) => infer Result\n ? Result\n : Instructions;\n\ntype InstructionErrorOf<Instructions, Input> =\n InstructionResultOf<Instructions, Input> extends Effect.Effect<\n infer _Success,\n infer Error,\n infer _Requirements\n >\n ? Error\n : never;\n\ntype InstructionRequirementsOf<Instructions, Input> =\n InstructionResultOf<Instructions, Input> extends Effect.Effect<\n infer _Success,\n infer _Error,\n infer Requirements\n >\n ? Requirements\n : never;\n\ntype InputPromptErrorOf<InputPromptValue, Input> = InputPromptValue extends (\n input: Input,\n) => infer Result\n ? Result extends Effect.Effect<infer _Success, infer Error, infer _Requirements>\n ? Error\n : never\n : never;\n\ntype InputPromptRequirementsOf<InputPromptValue, Input> = InputPromptValue extends (\n input: Input,\n) => infer Result\n ? Result extends Effect.Effect<infer _Success, infer _Error, infer Requirements>\n ? Requirements\n : never\n : never;\n\nimport {\n CompactionDecision,\n CompactionError,\n ContextCompactor,\n type CompactionModelLayer,\n type ContextMessageTokenEstimator,\n} from \"../ContextCompactor.ts\";\nimport {\n ContextRolloverRequest,\n ContextRolloverTool,\n ContextWindow,\n ContextWindowStatus,\n ContextRolloverSelection,\n ModelCallContext,\n} from \"../ContextWindow.ts\";\nimport {\n DurableStep,\n DurableStepError,\n getToolExecutionClass,\n type DurableStepService,\n type RunStepHook,\n type RunStepKey,\n} from \"../DurableStep.ts\";\nimport {\n RunEventSink,\n RunEventSinkClosedError,\n type RunEventSinkService,\n type SubagentEventPayload,\n} from \"../RunEventSink.ts\";\nimport {\n CurrentToolFailureObserver,\n AgentUpdateAcceptance,\n ModelUsageAccounting,\n type ModelToolFailure,\n type ProgrammaticToolFailure,\n type RunToolFailureObserver,\n type ChildEstablishStatus,\n type CommandDrainPolicy,\n type RunApprovalDecision,\n type RunBufferLimits,\n type RunResumeUsage,\n type RunDurabilityHook,\n RunResumeUsageSchema,\n RunContextPreparation,\n RunToolAuthorization,\n type RunToolAuthorizationHook,\n RunToolScheduling,\n type PreparedRunContext,\n type RunContextPreparationError,\n type RunOptions,\n type RunCostEstimateRequest,\n type RunSchedulingHook,\n type RunSubagentChildIdentity,\n type RunSubagentEstablishRequest,\n type RunSubagentHook,\n type RunSubagentJoinRequest,\n type RunCompactionCommit,\n type RunToolCallDescriptor,\n RunTurnResumeSettledCallSchema,\n type RunTurnResume,\n type RunUsageDelta,\n} from \"../RunOptions.ts\";\nimport {\n ToolBroker,\n ToolBrokerConfigurationError,\n ToolBrokerUnavailableError,\n type ProgrammaticCallOutcome,\n type ProgrammaticCallRecord,\n type ProgrammaticToolInput,\n type ToolBrokerPass,\n type ToolBrokerService,\n} from \"../ToolBroker.ts\";\nimport {\n buildCompactedView,\n contextWindowId,\n collectCoveredMessages,\n estimatePromptTokens,\n evaluateMessageTokenEstimates,\n initialCompactionState,\n isContextOverflowMessage,\n type ContextCompactionState,\n} from \"./compaction.ts\";\nimport { errorMessage, errorTag } from \"./error-diagnostic.ts\";\n\n/** Schema factory for the terminal value produced by reducing a completed agent event stream. */\nexport const AgentResultSchema = <Output extends Schema.Top>(output: Output) =>\n Schema.Struct({\n output,\n threadId: ThreadId,\n runId: RunId,\n turns: Schema.Int.check(Schema.isGreaterThan(0)),\n finishReason: Schema.Literals([\"completed\", \"model-stop\", \"budget-exhausted\"]),\n /** Dimension that bound when the Run settled budget-exhausted (RUN-025; the grant-flow marker). */\n exhausted: Schema.optionalKey(Schema.Literals([\"tokens\", \"tool-calls\", \"turns\"])),\n /** Schema-encoded application disposition declared for an ordinary completed Run. */\n runDisposition: Schema.optionalKey(Schema.Json),\n /** Cumulative spend for the Run, as reported on its terminal event. */\n usage: Schema.optionalKey(RunTotals),\n /** Disjoint usage of attached descendants, including nested and failed children. */\n delegatedUsage: Schema.optionalKey(RunTotals),\n }).check(\n Schema.makeFilter(\n (result) =>\n !(\"runDisposition\" in result) ||\n result.runDisposition === undefined ||\n !(\"finishReason\" in result) ||\n result.finishReason !== \"budget-exhausted\",\n {\n expected: \"runDisposition only when finishReason is not budget-exhausted\",\n },\n ),\n );\n\n/** Direct usage only: budget counters never absorb descendant consumption. */\nconst runTotalsOf = (context: RunContext): RunTotals =>\n RunTotals.make({\n modelCalls: context.modelCalls,\n inputTokens: context.inputTokens,\n outputTokens: context.outputTokens,\n costMicrousd: context.costMicrousd,\n usageStatus: context.usageStatus,\n pricingStatus: context.pricingStatus,\n unobservedModelCalls: context.unobservedModelCalls,\n });\n\nconst usageReportOf = Effect.fn(\"AgentRuntime.usageReport\")(function* (context: RunContext) {\n const contributions: RunTotals[] = [];\n\n for (const read of context.childUsage.values()) {\n const report = yield* read;\n\n contributions.push(report.usage, report.delegatedUsage);\n }\n\n // Observation must not change execution when a subtree exceeds numeric accounting capacity.\n const delegatedUsage = yield* sumRunTotals(contributions).pipe(\n Effect.catchTag(\"UsageAggregationError\", () => Effect.succeed(unknownRunTotals())),\n );\n\n return RunUsageReport.make({ usage: runTotalsOf(context), delegatedUsage });\n});\n\nconst noteIncompleteUsage = Effect.fn(\"AgentRuntime.noteIncompleteUsage\")(function* (\n context: RunContext,\n turn: number,\n) {\n const accounting = yield* ModelUsageAccounting;\n\n context.unobservedModelCalls += 1;\n context.usageStatus =\n context.usageStatus === \"unknown\" || context.modelCalls === 0 ? \"unknown\" : \"partial\";\n context.pricingStatus =\n context.pricingStatus === \"unknown\" || context.modelCalls === 0 ? \"unknown\" : \"partial\";\n yield* accounting.noteIncompleteUsage(turn);\n});\n\n/** Decoded terminal value produced by reducing a completed agent event stream. */\nexport type AgentResult<Output> = ReturnType<\n typeof AgentResultSchema<Schema.Schema<Output>>\n>[\"Type\"];\n\n/** Expected agent, policy, and model-protocol failures exposed by the runtime. */\nexport type AgentRuntimeFailure<\n AgentValue extends Agent.AnyDefinition | Agent.Any,\n HookError = never,\n InstructionError = never,\n> =\n | Agent.Failure<AgentValue>\n | ([Agent.UpdatesSchema<AgentValue>] extends [never] ? never : UpdateError)\n | AgentPolicyError\n | ContextBudgetError\n | ContextOverflowError\n | CompactionError\n | RunContextPreparationError\n | ModelProtocolError\n | AgentApprovalDenied\n | AgentToolAuthorizationDenied\n | AgentApprovalPending\n | AgentChildPending\n | ThreadHistoryError\n | HookError\n | InstructionError;\n\n/**\n * Services the engine itself provides locally to every Run: `AgentSpawner`\n * bound to the Run's immutable identity and delegation depth, `RunEventSink`\n * and `SubagentDurability` bound to the active Tool batch, `DurableStep`\n * bound to the active Tool Call, and `ToolSpanTelemetry` bound at the Run\n * composition edge. They are excluded from the runtime's public\n * requirements and MUST NOT be satisfied from an application Layer.\n */\nexport type EngineProvidedToolServices =\n | Emitter\n | AgentSpawner\n | RunEventSink\n | DurableStep\n | SubagentDurability\n | SubagentHost\n | MessagingHost\n | ToolBroker\n | ToolSpanTelemetry\n | ContextWindow\n | CurrentToolCatalog;\n\n/** Schema services needed to reconstruct a completion Tool's canonical Agent output. */\nexport type AgentCompletionProjectionRequirements<\n AgentValue extends Agent.AnyDefinition | Agent.Any,\n> =\n | Agent.OutputSchema<AgentValue>[\"DecodingServices\"]\n | Agent.OutputSchema<AgentValue>[\"EncodingServices\"]\n | Tool.ParametersSchema<Agent.ToolUnion<AgentValue>>[\"DecodingServices\"]\n | Tool.SuccessSchema<Agent.ToolUnion<AgentValue>>[\"DecodingServices\"];\n\n/**\n * Inferred agent services plus the runtime's identity and Thread history authorities.\n * Engine-provided Tool handler services are excluded because the interpreter\n * supplies them itself, bound to the current Run's identity. Tool parameter\n * encoding, output decoding, and completion-projection Schema services stay\n * listed unexcluded: the interpreter records canonical parameters before the\n * handler boundary, `run`/`start` re-decode terminal output, and durable recovery\n * re-decodes canonical completion Tool parameters/results.\n */\nexport type AgentRuntimeRequirements<\n AgentValue extends Agent.AnyDefinition | Agent.Any,\n HookRequirements = never,\n InstructionRequirements = never,\n> =\n | Exclude<Agent.Requirements<AgentValue>, EngineProvidedToolServices>\n | Tool.ParametersSchema<Agent.ToolUnion<AgentValue>>[\"EncodingServices\"]\n | AgentCompletionProjectionRequirements<AgentValue>\n | Agent.OutputSchema<AgentValue>[\"DecodingServices\"]\n | ThreadHistory\n | HookRequirements\n | InstructionRequirements;\n\n/**\n * Interpreter-internal requirements before the Run boundary in `stream`\n * provides the engine-owned Tool services. Native model services remain ambient.\n */\ntype InterpreterRequirements<\n AgentValue extends Agent.Any,\n HookRequirements = never,\n InstructionRequirements = never,\n> =\n | Agent.Requirements<AgentValue>\n | ThreadHistory\n | ContextCompactor\n | AgentUpdateAcceptance\n | ModelUsageAccounting\n | ProgrammaticToolAuthorization\n | HookRequirements\n | InstructionRequirements;\n\ninterface RunContext {\n readonly updates: Map<string, Update>;\n readonly validateUpdate: (value: Schema.Json) => Effect.Effect<void, UpdateError>;\n updateBytes: number;\n readonly updatePermits: Semaphore.Semaphore;\n\n readonly definition: Agent.AnyDefinition;\n toolSelection: Selection | undefined;\n toolCatalog: ReadonlyArray<CatalogEntry>;\n toolExposure: Snapshot | undefined;\n toolSchemaTransformer: LanguageModel.CodecTransformer | undefined;\n readonly agentId: Agent.AnyDefinition[\"id\"];\n readonly threadId: ThreadId;\n readonly runId: RunId;\n /** Captured once at the Run boundary, never reconstructed from events or durable data. */\n readonly toolFailureObserver: RunToolFailureObserver | undefined;\n /** Agent-Schema encoded input identifying this logical Run's originating authority/wake. */\n input: unknown;\n readonly pendingFollowUps: Array<Prompt.RawInput>;\n /** Wall-clock Run start, the base of the run-status elapsed rendering (RUN-024). */\n readonly startedAtMillis: number;\n /** Absolute `maxDuration` rail for this Attempt, optionally tightened by its coordinator. */\n readonly durationDeadlineMillis: number;\n history: Prompt.Prompt;\n modelCalls: number;\n usageStatus: typeof UsageCompleteness.Type;\n pricingStatus: typeof UsageCompleteness.Type;\n unobservedModelCalls: number;\n readonly childUsage: Map<RunId, Effect.Effect<RunUsageReport>>;\n readonly liveChildren: Set<RunId>;\n consecutiveToolFailures: number;\n inputTokens: number;\n outputTokens: number;\n /** The most recent model call's provider-reported tokens — the live-context estimate (RUN-023). */\n lastInputTokens: number;\n lastOutputTokens: number;\n costMicrousd: number;\n /** The most recent model call's estimated spend, staged for the Turn's canonical record. */\n lastCostMicrousd: number;\n /** Budget dimensions whose one-shot `BudgetWarning` already fired (RUN-025). */\n readonly warnedLimits: Set<\"tokens\" | \"tool-calls\" | \"turns\">;\n /** Held during the compaction summarizer's accounting so it cannot breach or recurse (RUN-026). */\n finalizing: boolean;\n /** One-shot token-breach flag: joins the final-answer derivation, never re-breaches (RUN-025). */\n tokenExhausted: boolean;\n /** First dimension that bound — the exhausted marker on budget-exhausted settlement (RUN-025). */\n exhaustedDimension: \"tokens\" | \"tool-calls\" | \"turns\" | undefined;\n /** Model-visible view state for engine-native compaction (RUN-026). */\n readonly compaction: ContextCompactionState;\n /** Owned content snapshots bind disposable compaction indices to prepared history. */\n preparedCompactionSource:\n | {\n readonly protectedReferences: ReadonlyArray<Prompt.Message>;\n readonly protectedMessages: ReadonlyArray<Schema.Json>;\n prefix: ReadonlyArray<Schema.Json>;\n }\n | undefined;\n windowId: string;\n windowTokens: number;\n windowContextTokenLimit: number | undefined;\n pendingContextToolCallId: string | undefined;\n /** One allowance shared by threshold compaction and the same Turn's overflow retry. */\n readonly compactionTurn: {\n turn: number;\n summaryCalls: number;\n readonly applied: Set<CompactionDecision[\"kind\"]>;\n };\n /** Finite engine-owned memory ceilings, optionally tightened per Run. */\n readonly bufferLimits: EffectiveRunBufferLimits;\n sequence: number;\n /** Cumulative JSON bytes of published progress, retained by detached replay until Scope close. */\n toolProgressBytes: number;\n /**\n * Run-wide count of reserved programmatic (broker) Tool invocations.\n * A committed reservation survives interruption before Handler start.\n * The broker consumes it mid-pass; the Turn-seam\n * `maxToolCalls` checks add it to the declared-call count.\n */\n programmaticToolCalls: number;\n finalizationUsed: boolean;\n readonly policyReservations: Semaphore.Semaphore;\n}\n\nconst runCounter = Metric.counter(\"effect_agent_runs_total\", {\n description: \"Agent runs started; no content or high-cardinality identifiers are recorded.\",\n});\n\nconst modelCounter = Metric.counter(\"effect_agent_model_calls_total\", {\n description:\n \"Agent model calls started; no content or high-cardinality identifiers are recorded.\",\n});\n\nconst toolCounter = Metric.counter(\"effect_agent_tool_calls_total\", {\n description:\n \"Agent tool handlers started; no content or high-cardinality identifiers are recorded.\",\n});\n\n/**\n * Tool Call parameters remain in their prompt/canonical form everywhere on\n * the trace. `prepareToolCall` decodes that bounded plain data for policy and\n * authorization, while the pinned `Toolkit.handle` receives the same encoded\n * value and performs its own decode before invoking the handler.\n */\ninterface TurnTrace {\n /** A resumed Turn already has an authoritative model response in canonical history. */\n readonly replayedResponse?: Prompt.Prompt | undefined;\n /** Number of decoded provider parts retained or inspected during this model call. */\n responsePartCount: number;\n /** Conservative retained-memory estimate across decoded provider parts. */\n responsePartBytes: number;\n readonly parts: Array<Response.AnyPart>;\n readonly text: Array<string>;\n readonly textParts: Map<string, PartLifecycle>;\n readonly reasoningParts: Map<string, PartLifecycle>;\n readonly toolParameterParts: Map<\n string,\n {\n readonly name: string;\n readonly providerExecuted: boolean;\n state: PartLifecycle;\n }\n >;\n readonly toolCalls: Map<\n string,\n {\n readonly name: string;\n readonly providerExecuted: boolean;\n }\n >;\n readonly finalToolResultIds: Set<string>;\n /** Provider result payloads held until the complete model response validates. */\n readonly providerResultPayloads: Array<ProviderResultEventPayload>;\n /** Exact retained JSON bytes across provider Tool results and staged provider events. */\n providerStagedPayloadBytes: number;\n /** Turn completion held with provider results so malformed trailing parts append neither. */\n turnCompletion: { readonly finishReason: Response.FinishReason } | undefined;\n readonly applicationToolCalls: Array<Response.ToolCallPart<string, unknown>>;\n /** Fresh validation failures retained independently of executable parameters. */\n readonly toolParameterRejections: Map<string, ToolParameterRejection>;\n /** Durable-hook view of the application calls, in declaration order (encoded parameters). */\n readonly applicationCallDescriptors: Array<RunToolCallDescriptor>;\n readonly applicationToolResults: Array<{\n readonly toolSelection?: Selection | undefined;\n readonly id: string;\n readonly name: string;\n readonly encodedResult: unknown;\n readonly isFailure: boolean;\n /** Settled synthetically by budget rejection: no handler ran, exempt from repeated-failure folding. */\n readonly budgetRejected?: boolean;\n }>;\n finished: boolean;\n finishReason: Response.FinishReason | undefined;\n usage: Response.Usage | undefined;\n response?: ModelResponseIdentity;\n finishMetadata?: Response.FinishPart[\"metadata\"];\n usageConsumed?: boolean;\n}\n\ntype ProviderResultEventPayload =\n | {\n readonly _tag: \"ToolProgress\";\n readonly toolCallId: ToolCallId;\n readonly toolName: string;\n readonly result: Schema.Json;\n readonly providerExecuted: true;\n }\n | {\n readonly _tag: \"ToolCallSucceeded\";\n readonly toolCallId: ToolCallId;\n readonly toolName: string;\n readonly result: Schema.Json;\n readonly providerExecuted: true;\n }\n | {\n readonly _tag: \"ToolCallFailed\";\n readonly toolCallId: ToolCallId;\n readonly toolName: string;\n readonly errorTag: string;\n readonly message: string;\n readonly providerExecuted: true;\n };\n\n// Provider output is untrusted. Holding terminal facts until whole-response validation is\n// fail-closed only while the additional staging allocation itself is deterministic and bounded.\nconst MAX_STAGED_PROVIDER_EVENTS = 256;\nconst MAX_STAGED_PROVIDER_BYTES = 1024 * 1024;\n/** Saved outcomes obey the canonical JSON ceiling, independently of today's display policy. */\nconst MAX_RESUMED_RESULT_BYTES = 1024 * 1024;\n\nconst DEFAULT_RUN_BUFFER_LIMITS = {\n maxModelResponseParts: 16_384,\n maxModelResponseBytes: 8 * 1024 * 1024,\n maxRunEvents: 65_536,\n maxToolProgressBytes: 8 * 1024 * 1024,\n maxSubagentEventsPerBatch: 1_024,\n} as const;\n\ninterface EffectiveRunBufferLimits {\n readonly maxModelResponseParts: number;\n readonly maxModelResponseBytes: number;\n readonly maxRunEvents: number;\n readonly maxToolProgressBytes: number;\n readonly maxSubagentEventsPerBatch: number;\n}\n\nconst tighteningBufferLimit = (\n configured: number | undefined,\n ceiling: number,\n minimum: number,\n): number =>\n configured === undefined || !Number.isFinite(configured)\n ? ceiling\n : Math.min(ceiling, Math.max(minimum, Math.floor(configured)));\n\nconst effectiveRunBufferLimits = (\n configured: RunBufferLimits | undefined,\n): EffectiveRunBufferLimits => ({\n maxModelResponseParts: tighteningBufferLimit(\n configured?.maxModelResponseParts,\n DEFAULT_RUN_BUFFER_LIMITS.maxModelResponseParts,\n 1,\n ),\n maxModelResponseBytes: tighteningBufferLimit(\n configured?.maxModelResponseBytes,\n DEFAULT_RUN_BUFFER_LIMITS.maxModelResponseBytes,\n 1,\n ),\n // A Run always needs one ordinary event and one reserved typed terminal event.\n maxRunEvents: tighteningBufferLimit(\n configured?.maxRunEvents,\n DEFAULT_RUN_BUFFER_LIMITS.maxRunEvents,\n 2,\n ),\n maxToolProgressBytes: tighteningBufferLimit(\n configured?.maxToolProgressBytes,\n DEFAULT_RUN_BUFFER_LIMITS.maxToolProgressBytes,\n 1,\n ),\n maxSubagentEventsPerBatch: tighteningBufferLimit(\n configured?.maxSubagentEventsPerBatch,\n DEFAULT_RUN_BUFFER_LIMITS.maxSubagentEventsPerBatch,\n 1,\n ),\n});\n\ninterface ModelResponseBufferUsage {\n responsePartCount: number;\n responsePartBytes: number;\n}\n\nconst structuredCloneFunction = Reflect.get(globalThis, \"structuredClone\");\nconst knownSafeModelResponsePrototypes = new Set<object>([Response.Usage.prototype]);\n\nconst schemaClassPrototype = (schema: Schema.Top): object | undefined => {\n if (typeof schema !== \"function\" || !Schema.isSchema(schema)) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(schema, \"prototype\");\n\n return descriptor !== undefined &&\n \"value\" in descriptor &&\n descriptor.value !== null &&\n typeof descriptor.value === \"object\"\n ? descriptor.value\n : undefined;\n};\n\n/**\n * Build the bounded preflight view for a decoded Tool payload whose root is an\n * application-selected Schema class. The class instance is deliberately omitted:\n * its complete canonical encoding is measured before cloning, and it is never\n * retained in the Turn trace. Every other response field remains in the preflight.\n */\nconst schemaClassToolPartPreflight = <Tools extends Record<string, Tool.Any>>(\n part: unknown,\n toolkit: Toolkit.Toolkit<Tools>,\n): object | undefined => {\n try {\n if (part === null || typeof part !== \"object\") return undefined;\n\n const read = (key: string): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(part, key);\n\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n throw new TypeError(`response part ${key} must be an own data property`);\n }\n\n return descriptor.value;\n };\n\n const type = read(\"type\");\n\n if (type !== \"tool-call\" && type !== \"tool-result\") return undefined;\n const name = read(\"name\");\n\n if (typeof name !== \"string\" || !hasTool(toolkit.tools, name)) return undefined;\n const tool = toolkit.tools[name];\n const payload = read(type === \"tool-call\" ? \"params\" : \"result\");\n\n if (payload === null || typeof payload !== \"object\") return undefined;\n const payloadPrototype = Object.getPrototypeOf(payload);\n\n const schemas =\n type === \"tool-call\" ? [tool.parametersSchema] : [tool.successSchema, tool.failureSchema];\n\n if (!schemas.some((schema) => schemaClassPrototype(schema) === payloadPrototype)) {\n return undefined;\n }\n\n const preflight: Record<string, unknown> = {};\n\n const retainedKeys =\n type === \"tool-call\"\n ? [\"type\", \"id\", \"name\", \"providerExecuted\", \"metadata\"]\n : [\n \"type\",\n \"id\",\n \"name\",\n \"isFailure\",\n \"providerExecuted\",\n \"preliminary\",\n \"metadata\",\n \"encodedResult\",\n ];\n\n for (const key of retainedKeys) {\n preflight[key] = read(key);\n }\n\n return preflight;\n } catch {\n return undefined;\n }\n};\n\nconst inspectModelResponsePartCapacity = (\n usage: ModelResponseBufferUsage,\n part: unknown,\n limits: EffectiveRunBufferLimits,\n knownSafePrototypes: ReadonlySet<object> = knownSafeModelResponsePrototypes,\n): Effect.Effect<number, ModelProtocolError> =>\n Effect.suspend(() => {\n const bytes = boundedValueFootprint(\n part,\n limits.maxModelResponseBytes - usage.responsePartBytes,\n knownSafePrototypes,\n );\n\n return bytes === undefined\n ? Effect.fail(\n ModelProtocolError.make({\n message: `Model response exceeded the ${limits.maxModelResponseBytes}-byte retained response limit`,\n }),\n )\n : Effect.succeed(bytes);\n });\n\n/**\n * LanguageModel validates encoded parameters even with automatic resolution disabled.\n * Defer only recoverable application parameter validation; the declaration's JSON codec\n * still exposes the original schema to providers and preserves their wire normalization.\n * No handler is installed or executed by this transport-only Toolkit.\n */\nconst defersToolParameters = (tool: Tool.Any): boolean =>\n tool.failureMode === \"return\" &&\n !(Tool.isProviderDefined(tool) && !tool.requiresHandler) &&\n !(Tool.isDynamic(tool) && tool.jsonSchema !== undefined);\n\nconst deferredToolParameterToolkit = <Tools extends Record<string, Tool.Any>>(\n toolkit: Toolkit.Toolkit<Tools>,\n): Toolkit.Toolkit<Record<string, Tool.Any>> => {\n // Preserve the native request unchanged when it has no recoverable parameters.\n // Toolkit's handler parameter variance is irrelevant to this resolution-disabled transport.\n if (!Object.values(toolkit.tools).some(defersToolParameters))\n return toolkit as unknown as Toolkit.Toolkit<Record<string, Tool.Any>>;\n\n return Toolkit.make(\n ...Object.values(toolkit.tools).map((tool) =>\n !defersToolParameters(tool)\n ? tool\n : tool.setParameters(\n Schema.declareConstructor<unknown>()(\n [],\n () => (input) =>\n Schema.decodeUnknownEffect(Schema.toEncoded(tool.parametersSchema))(input).pipe(\n Effect.orElseSucceed(() => input),\n ),\n {\n description: Tool.getDescription(tool),\n toCodecJson: () =>\n Schema.link<unknown>()(Schema.toEncoded(tool.parametersSchema), {\n decode: SchemaGetter.passthrough(),\n encode: SchemaGetter.passthrough(),\n }),\n },\n ),\n ),\n ),\n );\n};\n\n/** Own fresh JSON arguments without accepting them as executable parameters. */\nconst encodedToolParameterToolkit = (toolkit: Toolkit.Any): Toolkit.Any =>\n Toolkit.make(\n ...Object.values(toolkit.tools).map((tool) =>\n tool.setParameters(\n tool.failureMode === \"return\" && !(Tool.isProviderDefined(tool) && !tool.requiresHandler)\n ? Schema.Json\n : Schema.toEncoded(tool.parametersSchema),\n ),\n ),\n );\n\nconst makeModelResponseCodec = (toolkit: Toolkit.Any) =>\n Schema.toCodecJson(Response.StreamPart(encodedToolParameterToolkit(toolkit)));\n\n// Native Toolkits are immutable. Weak keys let discarded definitions and handler Toolkits go\n// away while each live Toolkit shares its canonical codec across response parts and Turns.\nconst modelResponseCodecs = new WeakMap<Toolkit.Any, ReturnType<typeof makeModelResponseCodec>>();\n\nconst modelResponseCodecFor = (toolkit: Toolkit.Any) => {\n const cached = modelResponseCodecs.get(toolkit);\n\n if (cached !== undefined) return cached;\n const codec = makeModelResponseCodec(toolkit);\n\n modelResponseCodecs.set(toolkit, codec);\n\n return codec;\n};\n\nconst ownModelResponsePartGeneral = Effect.fn(\"AgentRuntime.ownModelResponsePart\")(function* <\n Tools extends Record<string, Tool.Any>,\n>(\n part: unknown,\n toolkit: Toolkit.Toolkit<Tools>,\n usage: ModelResponseBufferUsage,\n limits: EffectiveRunBufferLimits,\n) {\n if (usage.responsePartCount >= limits.maxModelResponseParts) {\n return yield* ModelProtocolError.make({\n message: `Model response exceeded the ${limits.maxModelResponseParts}-part response limit`,\n });\n }\n\n // Reject an oversized provider graph before schema encoding, structured cloning, or decoding\n // can allocate additional full copies. A decoded application Schema class is the sole exception:\n // preflight its enclosing response fields, then measure its complete canonical plain encoding\n // before cloning. The class instance never enters retained Turn state.\n const directInputBytes = boundedValueFootprint(\n part,\n limits.maxModelResponseBytes - usage.responsePartBytes,\n knownSafeModelResponsePrototypes,\n );\n\n if (directInputBytes === undefined) {\n const preflight = schemaClassToolPartPreflight(part, toolkit);\n\n yield* inspectModelResponsePartCapacity(usage, preflight ?? part, limits);\n }\n const codec = modelResponseCodecFor(toolkit);\n\n const encodingFailure = ModelProtocolError.make({\n message: \"Model response part failed canonical encoding\",\n });\n\n const encoded = yield* Schema.encodeUnknownEffect(codec)(part).pipe(\n Effect.mapError(() => encodingFailure),\n );\n\n const retainedBytes = yield* inspectModelResponsePartCapacity(usage, encoded, limits);\n\n const ownedEncoded = yield* Effect.try({\n try: () => {\n if (typeof structuredCloneFunction !== \"function\") {\n throw new TypeError(\"structuredClone is unavailable\");\n }\n const cloned: unknown = Reflect.apply(structuredCloneFunction, globalThis, [encoded]);\n\n return cloned;\n },\n catch: () =>\n ModelProtocolError.make({\n message: \"Model response part could not be converted into engine-owned data\",\n }),\n });\n\n const decodingFailure = ModelProtocolError.make({\n message: \"Model response part failed canonical decoding\",\n });\n\n const ownedPart = yield* Schema.decodeUnknownEffect(codec)(ownedEncoded).pipe(\n Effect.mapError(() => decodingFailure),\n );\n\n return { ownedPart, retainedBytes };\n});\n\nconst ownModelResponsePart = <Tools extends Record<string, Tool.Any>>(\n part: unknown,\n toolkit: Toolkit.Toolkit<Tools>,\n usage: ModelResponseBufferUsage,\n limits: EffectiveRunBufferLimits,\n): ReturnType<typeof ownModelResponsePartGeneral> =>\n Effect.suspend((): ReturnType<typeof ownModelResponsePartGeneral> => {\n const primitive =\n usage.responsePartCount < limits.maxModelResponseParts\n ? ownPrimitiveDelta(part, limits.maxModelResponseBytes - usage.responsePartBytes)\n : undefined;\n\n return primitive === undefined\n ? ownModelResponsePartGeneral(part, toolkit, usage, limits)\n : Effect.succeed(primitive);\n });\n\nconst consumeModelResponsePart = (\n usage: ModelResponseBufferUsage,\n retainedBytes: number,\n limits: EffectiveRunBufferLimits,\n): Effect.Effect<void, ModelProtocolError> =>\n Effect.suspend(() => {\n if (\n usage.responsePartCount >= limits.maxModelResponseParts ||\n !Number.isSafeInteger(retainedBytes) ||\n retainedBytes < 0 ||\n retainedBytes > limits.maxModelResponseBytes - usage.responsePartBytes\n ) {\n return Effect.fail(\n ModelProtocolError.make({\n message:\n usage.responsePartCount >= limits.maxModelResponseParts\n ? `Model response exceeded the ${limits.maxModelResponseParts}-part response limit`\n : `Model response exceeded the ${limits.maxModelResponseBytes}-byte retained response limit`,\n }),\n );\n }\n\n return Effect.sync(() => {\n usage.responsePartCount += 1;\n usage.responsePartBytes += retainedBytes;\n });\n });\n\ntype PartLifecycle = \"open\" | \"closed\";\n\ntype ToolUnion<Tools extends Record<string, Tool.Any>> = Tools[keyof Tools];\n\ninterface PreparedToolCall<Tools extends Record<string, Tool.Any>> {\n readonly call: Response.ToolCallPart<string, unknown>;\n readonly name: keyof Tools & string;\n readonly toolCallId: ToolCallId;\n readonly validation: Result.Result<Tool.Parameters<ToolUnion<Tools>>, ToolParameterRejection>;\n readonly tool: ToolUnion<Tools>;\n readonly declarationIndex: number;\n}\n\nconst withSemaphorePermit = <A, E, R>(\n semaphore: Semaphore.Semaphore,\n stream: Stream.Stream<A, E, R>,\n): Stream.Stream<A, E, R> =>\n Stream.scoped(\n Stream.fromEffect(\n Effect.acquireRelease(semaphore.take(1), (permits) =>\n semaphore.release(permits).pipe(Effect.asVoid),\n ),\n ).pipe(Stream.flatMap(() => stream)),\n );\n\nconst hasTool = <Tools extends Record<string, Tool.Any>>(\n tools: Tools,\n name: string,\n): name is keyof Tools & string => Object.hasOwn(tools, name);\n\nconst startPart = (\n parts: Map<string, PartLifecycle>,\n id: string,\n description: string,\n): Effect.Effect<void, ModelProtocolError> => {\n if (parts.has(id)) {\n return Effect.fail(\n ModelProtocolError.make({\n message: `Model response repeated ${description} start for ${id}`,\n }),\n );\n }\n parts.set(id, \"open\");\n\n return Effect.void;\n};\n\nconst continuePart = (\n parts: Map<string, PartLifecycle>,\n id: string,\n description: string,\n): Effect.Effect<void, ModelProtocolError> =>\n parts.get(id) === \"open\"\n ? Effect.void\n : Effect.fail(\n ModelProtocolError.make({\n message: `Model response emitted ${description} for inactive part ${id}`,\n }),\n );\n\nconst endPart = (\n parts: Map<string, PartLifecycle>,\n id: string,\n description: string,\n): Effect.Effect<void, ModelProtocolError> =>\n continuePart(parts, id, `${description} end`).pipe(\n Effect.tap(() => Effect.sync(() => parts.set(id, \"closed\"))),\n );\n\nconst firstOpenPart = (trace: TurnTrace): string | undefined => {\n for (const [id, state] of trace.textParts) {\n if (state === \"open\") {\n return `text part ${id}`;\n }\n }\n for (const [id, state] of trace.reasoningParts) {\n if (state === \"open\") {\n return `reasoning part ${id}`;\n }\n }\n for (const [id, part] of trace.toolParameterParts) {\n if (part.state === \"open\") {\n return `Tool parameter part ${id}`;\n }\n }\n\n return undefined;\n};\n\n/** Canonically encode already-decoded Tool Call parameters for history and execution. */\nconst encodeToolCallParameters = <Tools extends Record<string, Tool.Any>>(\n tool: ToolUnion<Tools>,\n toolName: string,\n decodedParams: Tool.Parameters<ToolUnion<Tools>>,\n): Effect.Effect<\n unknown,\n ModelProtocolError,\n Tool.ParametersSchema<ToolUnion<Tools>>[\"EncodingServices\"]\n> => {\n const encodeParameters = Schema.encodeUnknownEffect(tool.parametersSchema) as (\n input: Tool.Parameters<ToolUnion<Tools>>,\n ) => Effect.Effect<\n unknown,\n Schema.SchemaError,\n Tool.ParametersSchema<ToolUnion<Tools>>[\"EncodingServices\"]\n >;\n\n return encodeParameters(decodedParams).pipe(\n Effect.mapError((cause) =>\n ModelProtocolError.make({\n message: `Invalid parameters for Tool ${toolName}: ${cause.message}`,\n }),\n ),\n );\n};\n\n/**\n * Decode canonically recorded Tool parameters for policy and authorization.\n * The private assertion restores the correlation lost by dynamic record\n * lookup only around a successful Schema decode.\n */\nconst decodeToolCallParameters = <Tools extends Record<string, Tool.Any>>(\n tool: ToolUnion<Tools>,\n toolName: string,\n encodedParams: unknown,\n boundary: \"model\" | \"execution\" | \"resume\" = \"execution\",\n): Effect.Effect<\n Tool.Parameters<ToolUnion<Tools>>,\n ModelProtocolError,\n Tool.HandlerServices<ToolUnion<Tools>>\n> => {\n const decodeParameters = Schema.decodeUnknownEffect(tool.parametersSchema) as (\n input: unknown,\n ) => Effect.Effect<\n Tool.Parameters<ToolUnion<Tools>>,\n Schema.SchemaError,\n Tool.HandlerServices<ToolUnion<Tools>>\n >;\n\n return decodeParameters(encodedParams).pipe(\n Effect.mapError((cause) =>\n ModelProtocolError.make({\n message:\n boundary === \"model\"\n ? `Invalid parameters for Tool ${toolName}: ${cause.message}`\n : `Recorded parameters for Tool ${toolName} failed validation${boundary === \"resume\" ? \" on resume\" : \"\"}: ${cause.message}`,\n }),\n ),\n );\n};\n\n/**\n * Decode executable parameters for approval while retaining their encoded form for\n * Toolkit.handle. A recorded rejection is a terminal failure, never an executable call.\n */\nconst prepareToolCall = <Tools extends Record<string, Tool.Any>>(\n toolkit: Toolkit.WithHandler<Tools>,\n call: Response.ToolCallPart<string, unknown>,\n declarationIndex: number,\n rejection?: ToolParameterRejection,\n): Effect.Effect<\n PreparedToolCall<Tools>,\n ModelProtocolError,\n Tool.HandlerServices<ToolUnion<Tools>>\n> => {\n const name = call.name;\n\n if (!hasTool(toolkit.tools, name)) {\n return Effect.fail(\n ModelProtocolError.make({ message: `Model requested unknown Tool ${call.name}` }),\n );\n }\n const tool = toolkit.tools[name] as ToolUnion<Tools>;\n\n return Effect.gen(function* () {\n const toolCallId = yield* decodeToolCallId(call.id);\n\n const validation: PreparedToolCall<Tools>[\"validation\"] =\n rejection === undefined\n ? Result.succeed(yield* decodeToolCallParameters<Tools>(tool, call.name, call.params))\n : Result.fail(rejection);\n\n return { call, name, toolCallId, validation, tool, declarationIndex };\n });\n};\n\n/**\n * Re-validate one canonically recorded Tool Call's encoded parameters through\n * the owning parameter Schema before a resumed batch may execute anything.\n * Declarations were validated when they entered the log (RUN-004), but a\n * resumed Attempt re-validates on read (STORE-006); a decode failure is a\n * strict no-start boundary. The same private assertion contract as\n * `encodeToolCallParameters` applies: correlation lost by dynamic record\n * lookup is restored only around a successful Schema decode.\n */\n/**\n * Effective Run bounds (RUN-021): per-Run allowances tighten the Agent\n * Policy's Turn and Tool Call ceilings but can never widen them — the\n * effective limit is `min(policy bound, max(1, floor(allowance)))`. The\n * `onExhaustion` resolution (RUN-018/RUN-019) keys off these effective\n * limits, which is how an orchestrator grants a delegated child a budget\n * extension by re-invoking with a larger allowance below the Definition's\n * ceiling.\n */\nconst CurrentSubagentAuthority = Context.Reference<\n { readonly grant: SubagentGrant; readonly depth: number } | undefined\n>(\"@effect-agent/engine/internal/CurrentSubagentAuthority\", { defaultValue: () => undefined });\n\nconst boundedAllowance = (policyBound: number, allowance: number | undefined): number =>\n // Fail closed on non-finite allowances (RUN-021): `NaN` propagates through\n // floor/max/min and every later `>` comparison answers false, which would\n // silently erase the bound — an invalid allowance keeps the policy bound.\n allowance === undefined || !Number.isFinite(allowance)\n ? policyBound\n : Math.min(policyBound, Math.max(1, Math.floor(allowance)));\n\nconst effectiveRunBounds = (\n policy: AgentPolicy,\n options: {\n readonly toolCallAllowance?: number | undefined;\n readonly turnAllowance?: number | undefined;\n },\n): { readonly maxTurns: number; readonly maxToolCalls: number } => ({\n maxTurns: boundedAllowance(policy.maxTurns, options.turnAllowance),\n maxToolCalls: boundedAllowance(policy.maxToolCalls, options.toolCallAllowance),\n});\n\nconst decodeResumedSettledCall = Effect.fn(\"AgentRuntime.decodeResumedSettledCall\")(\n (input: unknown) =>\n Effect.gen(function* () {\n const raw = yield* Effect.try({\n try: () => {\n if (input === null || typeof input !== \"object\") {\n throw new TypeError(\"settled Tool Call must be an object\");\n }\n\n const readOwnDataProperty = (key: \"id\" | \"result\" | \"isFailure\"): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n throw new TypeError(`settled Tool Call ${key} must be an own data property`);\n }\n\n return descriptor.value;\n };\n\n const selection = Object.getOwnPropertyDescriptor(input, \"toolSelection\");\n\n if (selection !== undefined && !(\"value\" in selection))\n throw new TypeError(\"settled Tool selection must be an own data property\");\n const rejected = Object.getOwnPropertyDescriptor(input, \"budgetRejected\");\n\n if (rejected !== undefined && !(\"value\" in rejected)) {\n throw new TypeError(\"settled Tool Call budgetRejected must be an own data property\");\n }\n\n return {\n id: readOwnDataProperty(\"id\"),\n result: readOwnDataProperty(\"result\"),\n isFailure: readOwnDataProperty(\"isFailure\"),\n ...(rejected === undefined ? {} : { budgetRejected: rejected.value }),\n ...(selection === undefined ? {} : { toolSelection: selection.value }),\n };\n },\n catch: () =>\n ModelProtocolError.make({\n message: \"Turn resume contains an invalid settled Tool Call\",\n }),\n });\n\n const result = boundedCanonicalJsonSnapshot(raw.result, MAX_RESUMED_RESULT_BYTES);\n\n if (result === undefined) {\n return yield* ModelProtocolError.make({\n message: \"Turn resume settled Tool result is not bounded canonical JSON\",\n });\n }\n\n return yield* Schema.decodeUnknownEffect(RunTurnResumeSettledCallSchema)({\n ...raw,\n result: result.value,\n }).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({\n message: \"Turn resume contains an invalid settled Tool Call\",\n }),\n ),\n );\n }),\n);\n\nconst snapshotResumedSettledCalls = Effect.fn(\"AgentRuntime.snapshotResumedSettledCalls\")(\n (resume: unknown, maximum: number) =>\n Effect.try({\n try: () => {\n if (resume === null || typeof resume !== \"object\") {\n throw new TypeError(\"Turn resume must be an object\");\n }\n const settledDescriptor = Object.getOwnPropertyDescriptor(resume, \"settled\");\n\n if (settledDescriptor === undefined || !(\"value\" in settledDescriptor)) {\n throw new TypeError(\"Turn resume settled must be an own data property\");\n }\n const settled = settledDescriptor.value;\n\n if (!Array.isArray(settled)) {\n throw new TypeError(\"Turn resume settled must be an array\");\n }\n const lengthDescriptor = Object.getOwnPropertyDescriptor(settled, \"length\");\n\n if (\n lengthDescriptor === undefined ||\n !(\"value\" in lengthDescriptor) ||\n !Number.isSafeInteger(lengthDescriptor.value) ||\n lengthDescriptor.value < 0 ||\n lengthDescriptor.value > maximum\n ) {\n throw new TypeError(\"Turn resume settled has an invalid length\");\n }\n const snapshot: Array<unknown> = [];\n\n for (let index = 0; index < lengthDescriptor.value; index += 1) {\n const entryDescriptor = Object.getOwnPropertyDescriptor(settled, String(index));\n\n if (entryDescriptor === undefined || !(\"value\" in entryDescriptor)) {\n throw new TypeError(\"Turn resume settled entries must be own data properties\");\n }\n snapshot.push(entryDescriptor.value);\n }\n\n return snapshot;\n },\n catch: () =>\n ModelProtocolError.make({\n message: \"Turn resume contains an invalid settled Tool Call collection\",\n }),\n }),\n);\n\nconst decodeResumeUsage = Effect.fn(\"AgentRuntime.decodeResumeUsage\")((input: unknown) =>\n Effect.gen(function* () {\n const snapshot = yield* Effect.try({\n try: () => {\n if (input === null || typeof input !== \"object\") {\n throw new TypeError(\"Run resume usage must be an object\");\n }\n\n const read = (key: keyof RunResumeUsage, optional = false): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n\n if (descriptor === undefined && optional) return undefined;\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n throw new TypeError(`Run resume usage ${key} must be an own data property`);\n }\n\n return descriptor.value;\n };\n\n const optional = Object.fromEntries(\n ([\"usageStatus\", \"pricingStatus\", \"unobservedModelCalls\", \"children\"] as const)\n .map((key) => [key, read(key, true)])\n .filter(([, value]) => value !== undefined),\n );\n\n return {\n ...optional,\n modelCalls: read(\"modelCalls\"),\n inputTokens: read(\"inputTokens\"),\n outputTokens: read(\"outputTokens\"),\n lastInputTokens: read(\"lastInputTokens\"),\n lastOutputTokens: read(\"lastOutputTokens\"),\n costMicrousd: read(\"costMicrousd\"),\n committedTurns: read(\"committedTurns\"),\n toolCalls: read(\"toolCalls\"),\n programmaticToolCalls: read(\"programmaticToolCalls\"),\n consecutiveToolFailures: read(\"consecutiveToolFailures\"),\n finalizationUsed: read(\"finalizationUsed\"),\n };\n },\n catch: () =>\n ModelProtocolError.make({\n message:\n \"Run resume usage requires own data properties with non-negative safe-integer totals and last-call tokens no greater than their cumulative totals\",\n }),\n });\n\n return yield* Schema.decodeUnknownEffect(RunResumeUsageSchema)(snapshot).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({\n message:\n \"Run resume usage requires own data properties with non-negative safe-integer totals and last-call tokens no greater than their cumulative totals\",\n }),\n ),\n );\n }),\n);\n\nconst makeToolFailedEvent = Effect.fn(\"AgentRuntime.makeToolFailedEvent\")(function* (\n context: RunContext,\n turnId: TurnId,\n call: Response.ToolCallPart<string, unknown>,\n error: unknown,\n failureHandling: \"propagated\" | \"returned-to-model\",\n budgetRejected?: true,\n): Effect.fn.Return<RunEvent, ModelProtocolError> {\n const toolCallId = yield* decodeToolCallId(call.id);\n const tools = context.definition.toolkit.tools;\n\n return ToolCallFailed.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: call.name,\n errorTag: errorTag(error),\n message: errorMessage(error),\n providerExecuted: false,\n failureHandling,\n ...(Object.hasOwn(tools, call.name) ? { failureMode: tools[call.name].failureMode } : {}),\n ...(budgetRejected === undefined ? {} : { budgetRejected }),\n });\n});\n\n/**\n * Settle a rejected Tool batch without starting any handler: every open\n * application call receives the encoded failure as its model-visible result.\n * Only budget rejections (RUN-018) are exempt from repeated-failure folding;\n * correctable model declarations count as ordinary failed calls. Emit one\n * `ToolCallFailed` per call with no `ToolCallStarted` (the\n * approval-denied precedent). The caller hands the trace to\n * `toolBatchContinuation`, so the synthetic results advance history through\n * the ordinary tool message and — under a durable coordinator that never saw\n * a response commit for this Turn — settle canonically via the single-batch\n * Turn commit.\n */\nconst settleRejectedBatch = Effect.fn(\"AgentRuntime.settleRejectedBatch\")(function* (\n context: RunContext,\n turnId: TurnId,\n trace: TurnTrace,\n error: AgentPolicyError | ModelProtocolError,\n alreadySettled?: ReadonlySet<string>,\n): Effect.fn.Return<ReadonlyArray<RunEvent>, ModelProtocolError> {\n const budgetRejected = error._tag === \"AgentPolicyError\" ? true : undefined;\n\n const encodedResult = {\n _tag: error._tag,\n ...(error._tag === \"AgentPolicyError\" ? { limit: error.limit } : {}),\n message: error.message,\n };\n\n const events: Array<RunEvent> = [];\n\n for (const [index, call] of trace.applicationToolCalls.entries()) {\n if (alreadySettled?.has(call.id) === true) {\n continue;\n }\n trace.finalToolResultIds.add(call.id);\n trace.applicationToolResults[index] = {\n id: call.id,\n name: call.name,\n encodedResult,\n isFailure: true,\n ...(budgetRejected === undefined ? {} : { budgetRejected }),\n };\n events.push(\n yield* makeToolFailedEvent(context, turnId, call, error, \"returned-to-model\", budgetRejected),\n );\n }\n\n return events;\n});\n\n/**\n * Stamp one pre-base Subagent payload into a first-class Run event through\n * the same `eventBase` path as every other event, so the Run's sequence stays\n * monotonic across handler-emitted and engine-emitted events. The engine is\n * authoritative for the base identity and the emitting batch's `turnId`; a\n * handler cannot forge either.\n */\ntype ToolEventPayload =\n | SubagentEventPayload\n | { readonly _tag: \"AgentUpdateEmitted\"; readonly update: Update };\n\nconst stampSubagentEvent = Effect.fn(\"AgentRuntime.stampSubagentEvent\")(function* (\n context: RunContext,\n turnId: TurnId,\n payload: ToolEventPayload,\n): Effect.fn.Return<RunEvent, ModelProtocolError> {\n if (payload._tag === \"AgentUpdateEmitted\")\n return AgentUpdateEmitted.make({\n ...(yield* eventBase(context)),\n turnId,\n update: payload.update,\n });\n\n const shared = {\n ...(yield* eventBase(context)),\n turnId,\n toolCallId: payload.toolCallId,\n delegationId: payload.delegationId,\n childThreadId: payload.childThreadId,\n childRunId: payload.childRunId,\n targetAgentId: payload.targetAgentId,\n depth: payload.depth,\n };\n\n const report =\n \"usage\" in payload\n ? {\n ...(payload.usage === undefined ? {} : { usage: payload.usage }),\n ...(payload.delegatedUsage === undefined\n ? {}\n : { delegatedUsage: payload.delegatedUsage }),\n }\n : {};\n\n switch (payload._tag) {\n case \"SubagentRequested\": {\n return SubagentRequested.make(shared);\n }\n case \"SubagentStarted\": {\n return SubagentStarted.make(shared);\n }\n case \"SubagentProgress\": {\n return SubagentProgress.make({ ...shared, summary: payload.summary });\n }\n case \"SubagentCompleted\": {\n return SubagentCompleted.make({\n ...shared,\n turns: payload.turns,\n finishReason: payload.finishReason,\n ...(payload.exhausted !== undefined ? { exhausted: payload.exhausted } : {}),\n ...report,\n });\n }\n case \"SubagentFailed\": {\n return SubagentFailed.make({\n ...shared,\n ...report,\n errorTag: payload.errorTag,\n message: payload.message,\n });\n }\n case \"SubagentInterrupted\": {\n return SubagentInterrupted.make({ ...shared, ...report, reason: payload.reason });\n }\n case \"SubagentJoined\": {\n return SubagentJoined.make({ ...shared, ...report });\n }\n }\n});\n\nconst approvalDecision = <Tools extends Record<string, Tool.Any>, Error, Requirements>(\n context: RunContext,\n turnId: TurnId,\n prepared: PreparedToolCall<Tools>,\n options: RunOptions<Error, Requirements>,\n): Effect.Effect<\n | {\n readonly required: false;\n }\n | {\n readonly required: true;\n readonly request: Response.ToolApprovalRequestPart;\n readonly decision: RunApprovalDecision;\n },\n Error | ModelProtocolError,\n Requirements\n> =>\n Effect.gen(function* () {\n if (Result.isFailure(prepared.validation)) return { required: false } as const;\n const decodedParams = prepared.validation.success;\n\n const approval = prepared.tool.needsApproval;\n\n if (approval === undefined || approval === false) {\n return { required: false as const };\n }\n\n const required =\n typeof approval === \"function\"\n ? yield* Effect.suspend(() => {\n const result = approval(decodedParams, {\n toolCallId: prepared.call.id,\n messages: context.history.content,\n });\n\n return Effect.isEffect(result) ? result : Effect.succeed(result);\n })\n : approval;\n\n if (!required) {\n return { required: false as const };\n }\n\n const request = Response.makePart(\"tool-approval-request\", {\n approvalId: `${context.runId}:${prepared.call.id}`,\n toolCallId: prepared.call.id,\n });\n\n if (options.approval === undefined) {\n return {\n required: true as const,\n request,\n decision: {\n _tag: \"unresolved\" as const,\n reason: \"No approval decision hook is available\",\n },\n };\n }\n const toolCallId = yield* decodeToolCallId(prepared.call.id);\n\n const decision = yield* options.approval.request({\n request,\n threadId: context.threadId,\n runId: context.runId,\n turnId,\n toolCallId,\n toolName: prepared.call.name,\n parameters: decodedParams,\n });\n\n return {\n required: true as const,\n request,\n decision,\n };\n });\n\n/**\n * Resolve every native Effect AI approval before the handler scheduler starts.\n * Concatenating this preflight stream ahead of handler streams makes denied or\n * unresolved batches a strict no-start boundary.\n */\nconst preflightApproval = <Tools extends Record<string, Tool.Any>, HookError, HookRequirements>(\n context: RunContext,\n turnId: TurnId,\n prepared: PreparedToolCall<Tools>,\n options: RunOptions<HookError, HookRequirements>,\n): Stream.Stream<\n RunEvent,\n HookError | ModelProtocolError | AgentApprovalDenied | AgentApprovalPending,\n HookRequirements\n> =>\n Stream.unwrap(\n approvalDecision(context, turnId, prepared, options).pipe(\n Effect.flatMap(\n (\n approval,\n ): Effect.Effect<\n Stream.Stream<RunEvent, AgentApprovalDenied | AgentApprovalPending>,\n ModelProtocolError\n > => {\n if (!approval.required) {\n return Effect.succeed(Stream.empty);\n }\n\n return Effect.gen(function* () {\n const toolCallId = yield* decodeToolCallId(prepared.call.id);\n\n const requested = ApprovalRequested.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: prepared.call.name,\n });\n\n switch (approval.decision._tag) {\n case \"approved\": {\n return Stream.succeed<RunEvent>(requested);\n }\n case \"denied\": {\n const denied = AgentApprovalDenied.make({\n toolCallId: prepared.call.id,\n toolName: prepared.call.name,\n message: approval.decision.reason ?? \"Tool approval was denied\",\n });\n\n const failed = ToolCallFailed.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: prepared.call.name,\n errorTag: denied._tag,\n message: denied.message,\n providerExecuted: false,\n failureMode: prepared.tool.failureMode,\n failureHandling: \"propagated\",\n });\n\n return Stream.fromIterable<RunEvent>([requested, failed]).pipe(\n Stream.concat(Stream.fail(denied)),\n );\n }\n case \"unresolved\": {\n const pending = AgentApprovalPending.make({\n approvalId: approval.request.approvalId,\n toolCallId: prepared.call.id,\n toolName: prepared.call.name,\n message: approval.decision.reason ?? \"Tool approval remains unresolved\",\n });\n\n return Stream.succeed<RunEvent>(requested).pipe(\n Stream.concat(Stream.fail(pending)),\n );\n }\n }\n });\n },\n ),\n ),\n );\n\n/**\n * Recheck host-owned Tool authority after approval and before durable preparation or scheduling.\n * Every call in the executable batch is authorized in declaration order before ANY Handler may\n * start, so a later denial leaves this Attempt's complete batch at zero application side effects.\n */\nconst preflightToolAuthorization = <HookError, HookRequirements>(\n context: RunContext,\n turnId: TurnId,\n turn: number,\n call: RunToolCallDescriptor,\n options: RunOptions<HookError, HookRequirements>,\n annotations: Context.Context<never>,\n): Stream.Stream<\n RunEvent,\n HookError | ModelProtocolError | AgentToolAuthorizationDenied,\n HookRequirements\n> => {\n const authorization = isSubagentToolAllowed(\n options.subagentGrant,\n options.delegationDepth ?? options.parentLink?.depth ?? 0,\n call.toolName,\n annotations,\n )\n ? options.toolAuthorization\n : {\n authorize: () =>\n Effect.succeed({\n _tag: \"denied\" as const,\n reason: \"Tool exceeds the inherited subagent grant\",\n }),\n };\n\n if (authorization === undefined) return Stream.empty;\n\n return Stream.unwrap(\n authorization\n .authorize({\n threadId: context.threadId,\n runId: context.runId,\n turnId,\n turn,\n input: context.input,\n call,\n })\n .pipe(\n Effect.map((decision) => {\n if (decision._tag === \"allowed\") return Stream.empty;\n\n const denied = AgentToolAuthorizationDenied.make({\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n message: decision.reason,\n });\n\n return Stream.fromEffect(\n Effect.map(eventBase(context), (base) =>\n ToolCallFailed.make({\n ...base,\n turnId,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n errorTag: denied._tag,\n message: denied.message,\n providerExecuted: false,\n failureMode: context.definition.toolkit.tools[call.toolName].failureMode,\n failureHandling: \"propagated\",\n }),\n ),\n ).pipe(Stream.concat(Stream.fail(denied)));\n }),\n ),\n );\n};\n\nconst ProviderResponsePartId = Schema.String.check(\n Schema.isMaxLength(128),\n Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),\n);\n\nconst ProviderToolCallId = ToolCallId.check(\n Schema.isMaxLength(128),\n Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),\n);\n\nconst isTelemetryToolCallId = Schema.is(ProviderToolCallId);\n\ntype ToolTelemetryOutcome = \"success\" | \"failure\";\n\ninterface ToolTelemetryDescriptor {\n readonly context: RunContext;\n readonly turnId: TurnId;\n readonly toolCallId: string | undefined;\n readonly toolName: string;\n readonly executionClass: ReturnType<typeof getToolExecutionClass>;\n readonly invocationKind: \"model\" | \"programmatic\";\n readonly failureMode: Tool.FailureMode;\n readonly parentToolCallId?: ToolCallId | undefined;\n readonly sequenceIndex?: number | undefined;\n}\n\n/** A definition names the agent; its Thread identifies the continuing instance and conversation. */\nconst agentTelemetryAttributes = (context: RunContext) => ({\n \"gen_ai.agent.name\": context.agentId,\n \"gen_ai.agent.id\": context.threadId,\n \"gen_ai.conversation.id\": context.threadId,\n});\n\n/** Label Effect AI's existing span, preserving provider usage, sampling and host async context. */\nconst modelTelemetryTracer = Effect.fnUntraced(function* (context: RunContext, turnId?: TurnId) {\n const delegate = yield* Tracer.Tracer;\n const model = yield* Model.ModelName;\n const provider = yield* Model.ProviderName;\n\n return Tracer.make({\n span(options) {\n if (options.name !== \"LanguageModel.streamText\") return delegate.span(options);\n\n const span = delegate.span({ ...options, name: `chat ${model}` });\n\n const attributes = {\n ...agentTelemetryAttributes(context),\n \"gen_ai.operation.name\": \"chat\",\n \"gen_ai.request.model\": model,\n \"gen_ai.provider.name\": provider,\n agentId: context.agentId,\n threadId: context.threadId,\n runId: context.runId,\n ...(turnId === undefined ? {} : { turnId }),\n };\n\n for (const [key, value] of Object.entries(attributes)) span.attribute(key, value);\n\n return span;\n },\n ...(delegate.context === undefined ? {} : { context: delegate.context.bind(delegate) }),\n });\n});\n\n/** One bounded identity surface shared by canonical Tool spans and terminal logs. */\nconst toolTelemetryAttributes = (descriptor: ToolTelemetryDescriptor) => ({\n ...agentTelemetryAttributes(descriptor.context),\n \"gen_ai.operation.name\": \"execute_tool\",\n \"gen_ai.tool.name\": descriptor.toolName,\n \"gen_ai.tool.type\": \"function\",\n ...(descriptor.toolCallId === undefined\n ? {}\n : {\n \"gen_ai.tool.call.id\": descriptor.toolCallId,\n toolCallId: descriptor.toolCallId,\n }),\n \"effect_agent.tool.execution_class\": descriptor.executionClass,\n \"effect_agent.tool.invocation_kind\": descriptor.invocationKind,\n \"effect_agent.tool.failure_mode\": descriptor.failureMode,\n ...(descriptor.parentToolCallId === undefined\n ? {}\n : {\n \"effect_agent.tool.parent_call.id\": descriptor.parentToolCallId,\n parentToolCallId: descriptor.parentToolCallId,\n }),\n ...(descriptor.sequenceIndex === undefined\n ? {}\n : {\n \"effect_agent.tool.sequence_index\": descriptor.sequenceIndex,\n sequenceIndex: descriptor.sequenceIndex,\n }),\n agentId: descriptor.context.agentId,\n threadId: descriptor.context.threadId,\n runId: descriptor.context.runId,\n turnId: descriptor.turnId,\n toolName: descriptor.toolName,\n});\n\n/** Canonical content-free terminal signal for any application Tool handler attempt. */\nconst terminalToolTelemetry = (\n descriptor: ToolTelemetryDescriptor,\n outcome: ToolTelemetryOutcome,\n failureMarker?: ToolSpanFailure,\n failureHandling?: ToolFailureHandling,\n): Effect.Effect<void> =>\n annotateToolSpanTerminalOutcome(\n outcome,\n failureMarker,\n failureHandling,\n descriptor.failureMode,\n ).pipe(\n Effect.andThen(\n (outcome === \"success\"\n ? Effect.logInfo(\"agent tool execution completed\")\n : Effect.logWarning(\"agent tool execution failed\")\n ).pipe(\n Effect.annotateLogs({\n ...toolTelemetryAttributes(descriptor),\n \"effect_agent.tool.outcome\": outcome,\n ...(failureHandling === undefined\n ? {}\n : { \"effect_agent.tool.failure_handling\": failureHandling }),\n toolExecutionClass: descriptor.executionClass,\n toolOutcome: outcome,\n }),\n ),\n ),\n );\n\n/** Bound only the observer's diagnostic; broker/public diagnostic policy is a separate contract. */\nconst toolFailureMessage = (message: string): string => {\n let bytes = 0;\n let end = 0;\n\n for (const character of message) {\n const size = utf8ByteLength(character);\n\n if (bytes + size > 4_096) break;\n bytes += size;\n end += character.length;\n }\n\n return message.slice(0, end);\n};\n\nconst executePreparedToolCall = <Tools extends Record<string, Tool.Any>>(\n context: RunContext,\n turnId: TurnId,\n toolkit: Toolkit.WithHandler<Tools>,\n prepared: PreparedToolCall<Tools>,\n trace: TurnTrace,\n resultBounds: ToolResultBounds,\n /**\n * Batch-level collector for the durable-Subagent waiting signal. A\n * `ToolCallWaiting` failure is not a Tool failure: the call stays open (no\n * terminal result, no `ToolCallFailed`, no batch failure policy) and the\n * batch reports it through `AgentChildPending` after every non-waiting\n * sibling settled.\n */\n onWaiting: (waiting: ToolCallWaiting) => void,\n): Stream.Stream<\n RunEvent,\n ModelProtocolError | AiError.AiError | Tool.HandlerError<ToolUnion<Tools>>,\n ToolSpanTelemetry | Tool.HandlerServices<ToolUnion<Tools>>\n> => {\n type ToolExecutionError =\n | ModelProtocolError\n | AiError.AiError\n | Tool.HandlerError<ToolUnion<Tools>>;\n\n const call = prepared.call;\n const observer = context.toolFailureObserver;\n const telemetryToolCallId = isTelemetryToolCallId(call.id) ? call.id : undefined;\n const executionClass = getToolExecutionClass(prepared.tool);\n\n const telemetryDescriptor: ToolTelemetryDescriptor = {\n context,\n turnId,\n toolCallId: telemetryToolCallId,\n toolName: call.name,\n executionClass,\n invocationKind: \"model\",\n failureMode: prepared.tool.failureMode,\n };\n\n const toolSpanFailure = ToolSpanFailure.marker();\n let terminal = false;\n let terminalResultCommitted = false;\n let terminalOutcome: \"success\" | \"failure\" | undefined;\n\n let terminalResult:\n | {\n readonly encodedResult: unknown;\n readonly isFailure: boolean;\n readonly result: unknown;\n }\n | undefined;\n\n let propagatedFailure: Cause.Cause<ToolExecutionError> | undefined;\n let failureObservation: ModelToolFailure | undefined;\n\n const terminalTelemetry = (\n outcome: ToolTelemetryOutcome,\n failureHandling?: ToolFailureHandling,\n ) =>\n terminalToolTelemetry(\n telemetryDescriptor,\n outcome,\n outcome === \"failure\" ? toolSpanFailure : undefined,\n failureHandling,\n );\n\n const isolatedTerminalTelemetry = (\n outcome: \"success\" | \"failure\",\n failureHandling?: ToolFailureHandling,\n ) =>\n // Measurement is derivative: a broken Logger/Tracer must never change the Tool event or make\n // an already-completed external side effect eligible for recovery. Non-interrupt Causes reach\n // Effect's owned reporter boundary; external interruption remains interruption.\n isolateToolDerivative(terminalTelemetry(outcome, failureHandling));\n\n /**\n * The authoritative event reaches the downstream Run stream before derivative work starts.\n * Telemetry and observation share one owner across the next-pull/early-close race, under this\n * call's batch permit. A returned failure still fails a normal second pull with the span marker.\n */\n const terminalEventThenAfter = <EventError>(\n event: Effect.Effect<RunEvent, EventError>,\n outcome: \"success\" | \"failure\",\n failSpan: boolean,\n failureHandling?: ToolFailureHandling,\n ): Stream.Stream<RunEvent, EventError | ToolSpanFailure> => {\n const telemetry = isolatedTerminalTelemetry(outcome, failureHandling);\n\n const after =\n observer === undefined\n ? telemetry\n : telemetry.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n failureObservation === undefined\n ? Effect.void\n : deliverToolFailure(observer, failureObservation),\n ),\n ),\n );\n\n return emitThenAfter(\n event,\n after.pipe(Effect.andThen(failSpan ? Effect.fail(toolSpanFailure) : Effect.void)),\n );\n };\n\n const started = Result.isFailure(prepared.validation)\n ? Stream.empty\n : Stream.fromEffect(\n Effect.gen(function* () {\n const toolCallId = yield* decodeToolCallId(call.id);\n\n yield* Effect.logDebug(\"agent tool handler started\").pipe(\n Effect.annotateLogs({\n agentId: context.agentId,\n runId: context.runId,\n turnId,\n ...(telemetryToolCallId === undefined ? {} : { toolCallId: telemetryToolCallId }),\n toolName: call.name,\n }),\n );\n yield* Metric.update(toolCounter, 1);\n\n return ToolCallStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: call.name,\n });\n }).pipe(Effect.withLogSpan(\"AgentRuntime.tool\")),\n );\n\n // Dynamic Tool lookup erases the name/ParametersEncoded correlation. The native handler\n // decodes these already-preflighted canonical parameters; only its input signature is widened.\n const handle = toolkit.handle as (\n name: keyof Tools & string,\n params: unknown,\n toolCallId: string,\n ) => ReturnType<typeof toolkit.handle>;\n\n const rejection = Result.isFailure(prepared.validation) ? prepared.validation.failure : undefined;\n\n const handlerResults: Stream.Stream<\n Tool.HandlerResult<Tool.Any>,\n ToolExecutionError,\n ToolSpanTelemetry | Tool.HandlerServices<ToolUnion<Tools>>\n > = rejection === undefined\n ? Stream.unwrap(\n Effect.flatMap(ToolSpanTelemetry, ({ isolateToolkitHandle }) =>\n isolateToolkitHandle(handle.call(toolkit, prepared.name, call.params, call.id)),\n ),\n )\n : Stream.fromEffect(\n Schema.decodeEffect(Schema.toCodecJson(AiError.AiError))(rejection.error).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({ message: \"Invalid parameter rejection evidence\" }),\n ),\n Effect.map((error) => ({\n result: error,\n encodedResult: rejection.error,\n isFailure: true,\n preliminary: false,\n })),\n ),\n );\n\n const results: Stream.Stream<\n RunEvent,\n ToolExecutionError,\n ToolSpanTelemetry | Tool.HandlerServices<ToolUnion<Tools>>\n > = handlerResults.pipe(\n Stream.mapEffect((result): Effect.Effect<RunEvent | undefined, ModelProtocolError> =>\n Effect.gen(function* () {\n if (terminal || trace.finalToolResultIds.has(call.id)) {\n return yield* ModelProtocolError.make({\n message: `Tool Call ${call.id} produced more than one terminal result`,\n });\n }\n const toolCallId = yield* decodeToolCallId(call.id);\n\n if (result.preliminary) {\n const owned = yield* ownApplicationToolProgress(context, result.encodedResult);\n\n const event: RunEvent = ToolProgress.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: call.name,\n result: owned,\n providerExecuted: false,\n });\n\n return event;\n }\n\n terminal = true;\n terminalOutcome = result.isFailure ? \"failure\" : \"success\";\n terminalResult = {\n encodedResult: result.encodedResult,\n isFailure: result.isFailure,\n result: result.result,\n };\n\n // A terminal Toolkit value is provisional until its handler stream closes. Emitting the\n // append-only event or committing the Turn trace here would leave contradictory Run state\n // if that stream later fails or produces another terminal value.\n return undefined;\n }),\n ),\n Stream.filter((event): event is RunEvent => event !== undefined),\n );\n\n const commitTerminalResult: Effect.Effect<RunEvent, ModelProtocolError> = Effect.suspend(\n (): Effect.Effect<RunEvent, ModelProtocolError> => {\n if (!terminal || terminalOutcome === undefined || terminalResult === undefined) {\n return Effect.fail(\n ModelProtocolError.make({\n message: `Tool Call ${call.id} completed without a terminal result`,\n }),\n );\n }\n const result = terminalResult;\n\n return Effect.gen(function* () {\n const toolCallId = yield* decodeToolCallId(call.id);\n // RUN-022: the policy bound applies exactly once, as the result\n // becomes terminal — the settled trace entry, the durable record,\n // and the live success event all carry the same bounded value.\n // Provider-executed results and the final-output path never pass\n // through this seam.\n let toolSelection: Selection | undefined;\n\n if (!result.isFailure && Context.get(prepared.tool.annotations, DiscoveryTool)) {\n toolSelection = yield* validateSelection(\n result.result,\n context.definition,\n context.toolCatalog,\n );\n // Validate count and rendered-schema bounds before accepting the selection.\n yield* exposureSnapshot(\n context.definition,\n toolSelection,\n context.toolCatalog,\n context.toolSchemaTransformer,\n );\n }\n const encodedResult = boundEncodedToolResult(result.encodedResult, resultBounds);\n\n const event: RunEvent = result.isFailure\n ? ToolCallFailed.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: call.name,\n errorTag: errorTag(result.result),\n message: errorMessage(result.result),\n providerExecuted: false,\n failureMode: prepared.tool.failureMode,\n failureHandling: \"returned-to-model\",\n })\n : ToolCallSucceeded.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: call.name,\n result: yield* decodeEventJson(encodedResult, \"Tool result\"),\n ...(toolSelection === undefined ? {} : { toolSelection }),\n providerExecuted: false,\n });\n\n trace.finalToolResultIds.add(call.id);\n trace.applicationToolResults[prepared.declarationIndex] = {\n ...(toolSelection === undefined ? {} : { toolSelection }),\n id: call.id,\n name: call.name,\n encodedResult,\n isFailure: result.isFailure,\n };\n terminalResultCommitted = true;\n if (observer !== undefined && event._tag === \"ToolCallFailed\") {\n failureObservation = {\n _tag: \"ModelToolFailure\",\n kind: \"declared-failure\",\n agentId: context.agentId,\n threadId: context.threadId,\n runId: context.runId,\n turnId,\n toolCallId,\n toolName: call.name,\n executionClass,\n tag: event.errorTag,\n };\n }\n\n return event;\n });\n },\n );\n\n const finalizeTerminalResult: Stream.Stream<RunEvent, ModelProtocolError | ToolSpanFailure> =\n Stream.unwrap(\n Effect.sync(() =>\n terminalEventThenAfter(\n commitTerminalResult,\n terminalOutcome ?? \"failure\",\n terminalOutcome === \"failure\",\n terminalOutcome === \"failure\" ? \"returned-to-model\" : undefined,\n ),\n ),\n );\n\n const failTerminalResult = (\n cause: Cause.Cause<ToolExecutionError>,\n ): Stream.Stream<RunEvent, ModelProtocolError | ToolSpanFailure> => {\n terminal = true;\n terminalOutcome = \"failure\";\n terminalResult = undefined;\n propagatedFailure = cause;\n\n return terminalEventThenAfter(\n makeToolFailedEvent(context, turnId, call, Cause.squash(cause), \"propagated\").pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n trace.finalToolResultIds.add(call.id);\n terminalResultCommitted = true;\n }),\n ),\n ),\n \"failure\",\n true,\n \"propagated\",\n );\n };\n\n const measured = started.pipe(\n Stream.concat(results),\n Stream.concat(finalizeTerminalResult),\n Stream.catchCause((cause) => {\n // A value-level failure already has its terminal event and bounded span-facing\n // signal. Let only the outer recovery consume it.\n const { found: hasToolSpanFailure, residual: toolCause } = stripToolSpanFailures(\n cause,\n toolSpanFailure,\n );\n\n if (hasToolSpanFailure) {\n return Stream.failCause(cause);\n }\n if (terminalResultCommitted) {\n return Stream.failCause(toolCause);\n }\n if (toolCause.reasons.length > 0 && toolCause.reasons.every(Cause.isInterruptReason)) {\n // Interruption terminates only this in-memory handler attempt. It emits no append-only Tool\n // terminal event and no success/failure terminal log; the canonical span observes and\n // preserves the exact interruption Cause from its enclosing stream Exit.\n return Stream.failCause(toolCause);\n }\n const waiting = waitingFromCause(toolCause);\n\n if (waiting !== undefined) {\n if (terminal || trace.finalToolResultIds.has(call.id)) {\n // A handler that produced a terminal result cannot also wait: the\n // anomaly fails loud and typed instead of suspending a settled call.\n return failTerminalResult(\n Cause.fail(\n ModelProtocolError.make({\n message: `Tool Call ${call.id} raised the waiting signal after its terminal result`,\n }),\n ),\n );\n }\n // The waiting call stays open: no terminal result is recorded, no\n // failure event is emitted, and the batch failure policy never\n // applies — sibling handlers keep running and the batch terminates\n // with `AgentChildPending` once they all settled.\n onWaiting(waiting);\n\n return Stream.empty;\n }\n\n return failTerminalResult(toolCause);\n }),\n Stream.withSpan(`execute_tool ${call.name}`, {\n kind: \"internal\",\n attributes: toolTelemetryAttributes(telemetryDescriptor),\n }),\n );\n\n return Stream.unwrap(\n Effect.map(ToolSpanTelemetry, ({ isolateSpanLifecycle }) => isolateSpanLifecycle(measured)),\n ).pipe(\n Stream.catchCause((cause) => {\n const { found, restored } = restoreToolSpanFailureCause(\n cause,\n toolSpanFailure,\n propagatedFailure,\n );\n\n if (!found) return Stream.failCause(restored);\n\n return restored.reasons.length === 0 ? Stream.empty : Stream.failCause(restored);\n }),\n );\n};\n\n/**\n * Execute a wholly preflighted native Toolkit batch under one finite engine\n * semaphore.\n *\n * The engine provides this batch's `RunEventSink` locally to the handler\n * streams, bound to the batch's Turn. Sink emissions are drained into the\n * batch stream and stamped through `eventBase`; the batch settles (including\n * by failure) only after every already-emitted Subagent event has surfaced.\n * The public exclusion of engine-provided services happens once at the Run\n * boundary in `stream`, so this signature keeps the naked handler services.\n */\nconst executeToolBatch = <Tools extends Record<string, Tool.Any>, HookError, HookRequirements>(\n context: RunContext,\n turnId: TurnId,\n turn: number,\n toolkit: Toolkit.WithHandler<Tools>,\n calls: ReadonlyArray<Response.ToolCallPart<string, unknown>>,\n trace: TurnTrace,\n concurrency: number,\n options: RunOptions<HookError, HookRequirements>,\n /**\n * Tool-call accounting for the per-call `ToolBroker` (RUN-017):\n * `declaredToolCalls` is the model-declared total committed through this\n * batch, and `maxToolCalls` the Agent policy bound the broker consumes\n * against mid-pass.\n */\n brokerAccounting: { readonly maxToolCalls: number; readonly declaredToolCalls: number },\n /** Policy byte bound applied to each settling result (RUN-022). */\n resultBounds: ToolResultBounds,\n /**\n * Call IDs already settled canonically (batch-resume seam). Their recorded\n * results were injected into the trace by the caller; approval preflight\n * and durable preparation still cover them, but no handler starts.\n */\n settledCallIds?: ReadonlySet<string>,\n): Stream.Stream<\n RunEvent,\n | HookError\n | ModelProtocolError\n | AgentApprovalDenied\n | AgentApprovalPending\n | AgentToolAuthorizationDenied\n | AgentChildPending\n | AiError.AiError\n | Tool.HandlerError<ToolUnion<Tools>>,\n | HookRequirements\n | AgentUpdateAcceptance\n | ToolSpanTelemetry\n | ProgrammaticToolAuthorization\n | Tool.HandlerServices<ToolUnion<Tools>>\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const exposed = context.toolExposure?.exposedToolNames;\n const visibility = yield* RunToolVisibility;\n\n const eligible = new Set(\n context.toolCatalog\n .filter((entry) => entry.kind === \"native\")\n .map((entry) => entry.nativeToolName),\n );\n\n if (\n calls.some(\n (call) =>\n (exposed !== undefined && !exposed.includes(call.name)) ||\n // Preserve the existing typed grant-denial preflight when no host visibility\n // hook is installed. Both checks still precede every unfinished handler.\n (visibility !== undefined && !settledCallIds?.has(call.id) && !eligible.has(call.name)),\n )\n ) {\n return yield* ModelProtocolError.make({\n message: \"Tool batch calls a Tool outside its request exposure or current visibility\",\n });\n }\n\n // Resolve the whole batch before constructing streams. Only calls with recorded\n // parameter rejection evidence bypass executable-parameter decoding and approval.\n const prepared = yield* Effect.forEach(\n calls.flatMap((call, declarationIndex) =>\n settledCallIds?.has(call.id) ? [] : [{ call, declarationIndex }],\n ),\n ({ call, declarationIndex }) =>\n prepareToolCall(\n toolkit,\n call,\n declarationIndex,\n trace.toolParameterRejections.get(call.id),\n ),\n );\n\n if (\n prepared.some((call) => Context.get(call.tool.annotations, ContextRolloverTool)) &&\n trace.toolCalls.size !== 1\n ) {\n return yield* ModelProtocolError.make({\n message: \"A context rollover Tool must be the only Tool Call in its batch\",\n });\n }\n const semaphore = yield* Semaphore.make(concurrency);\n\n const approvalPreflight = prepared.reduce<\n Stream.Stream<\n RunEvent,\n HookError | ModelProtocolError | AgentApprovalDenied | AgentApprovalPending,\n HookRequirements\n >\n >(\n (stream, call) =>\n stream.pipe(Stream.concat(preflightApproval(context, turnId, call, options))),\n Stream.empty,\n );\n\n // Reuse the canonical wire-form descriptors already committed with the response. Handler\n // parameters were decoded/re-encoded separately above, so the host policy never receives\n // the handler's live parameter object.\n const descriptors = trace.applicationCallDescriptors.filter(\n (call) => !trace.toolParameterRejections.has(call.toolCallId),\n );\n\n const durability = options.durability;\n // The hook's requirements are captured here (they are already part of\n // this stream's requirements) so the per-call `DurableStep` service can\n // run hook effects without leaking `HookRequirements` into handler\n // signatures.\n const hookServices = yield* Effect.context<HookRequirements>();\n\n const executable =\n settledCallIds === undefined\n ? prepared\n : prepared.filter((call) => !settledCallIds.has(call.call.id));\n\n const executableDescriptors =\n settledCallIds === undefined\n ? descriptors\n : descriptors.filter((call) => !settledCallIds.has(call.toolCallId));\n\n const authorizationPreflight = executableDescriptors.reduce<\n Stream.Stream<\n RunEvent,\n HookError | ModelProtocolError | AgentToolAuthorizationDenied,\n HookRequirements\n >\n >(\n (stream, call) =>\n stream.pipe(\n Stream.concat(\n preflightToolAuthorization(\n context,\n turnId,\n turn,\n call,\n options,\n toolkit.tools[call.toolName]?.annotations ?? Context.empty(),\n ),\n ),\n ),\n Stream.empty,\n );\n\n // Durable preparation runs strictly after every approval resolved\n // approved and before any handler acquires a permit. Ordinary `readonly`\n // calls need no uncertainty protocol. Delegations always prepare their\n // classification, including a caller-annotated readonly delegation.\n // A resumed batch replays the identical full\n // descriptor list so the prepared batch identity stays stable.\n const preparation: Stream.Stream<never, HookError, HookRequirements> =\n durability === undefined\n ? Stream.empty\n : Stream.fromEffect(\n Effect.suspend(() => {\n const preparedDescriptors = descriptors.filter(\n (call) => call.executionClass !== \"readonly\" || call.executionKind !== \"ordinary\",\n );\n\n return preparedDescriptors.length === 0\n ? Effect.void\n : durability.prepareToolCalls(preparedDescriptors);\n }),\n ).pipe(Stream.drain);\n\n // Each executable call gets its own locally provided `DurableStep`,\n // bound to that call's identity: durable over the coordinator's step\n // hook, honest pass-through otherwise.\n const stepServiceFor = (call: PreparedToolCall<Tools>): DurableStepService =>\n durability === undefined\n ? passthroughDurableStep()\n : makeDurableStepService(call.toolCallId, durability.step, hookServices);\n\n // This batch's live `SubagentDurability` service: durable over the\n // coordinator's subagent hook, the explicit ephemeral-mode default\n // otherwise. Absence of the hook means the Run is not under a durable\n // coordinator (the coordinator always supplies it), so no durable claim\n // is being made and the S1 in-process spawn semantics apply honestly.\n const subagentHook = options.subagent;\n\n const batchSubagentDurability: SubagentDurabilityService =\n subagentHook === undefined\n ? ephemeralSubagentDurability\n : makeSubagentDurabilityService(subagentHook, hookServices);\n\n // Delegation calls that raised the waiting signal, keyed by declaration\n // index so `AgentChildPending` lists its children deterministically\n // regardless of parallel handler completion order.\n const waitingByDeclaration = new Map<number, ToolCallWaiting>();\n\n const scheduling = options.scheduling ?? (yield* RunToolScheduling);\n const groups: Array<ReadonlyArray<PreparedToolCall<Tools>>> = [];\n let parallel: Array<PreparedToolCall<Tools>> = [];\n\n for (const call of executable) {\n if (scheduling.toolRequiresSequential?.(call.name) === true) {\n if (parallel.length > 0) {\n groups.push(parallel);\n parallel = [];\n }\n groups.push([call]);\n } else {\n parallel.push(call);\n }\n }\n if (parallel.length > 0) {\n groups.push(parallel);\n }\n\n const handlers = groups.reduce<\n Stream.Stream<\n RunEvent,\n ModelProtocolError | AiError.AiError | Tool.HandlerError<ToolUnion<Tools>>,\n ToolSpanTelemetry | ProgrammaticToolAuthorization | Tool.HandlerServices<ToolUnion<Tools>>\n >\n >((stream, group) => {\n const channels = group.map(\n (call) =>\n withSemaphorePermit(\n semaphore,\n Stream.unwrap(\n Effect.gen(function* () {\n const subagentHost = yield* SubagentHost.forTool;\n const messagingHost = yield* MessagingHost.forTool;\n\n const source = {\n _tag: \"tool\" as const,\n agentId: context.agentId,\n threadId: context.threadId,\n runId: context.runId,\n toolCallId: call.toolCallId,\n };\n\n const broker = yield* makeToolBrokerService({\n context,\n turnId,\n outerToolCallId: call.toolCallId,\n turn,\n maxToolCalls: brokerAccounting.maxToolCalls,\n declaredToolCalls: brokerAccounting.declaredToolCalls,\n budget: options.budget,\n reservePolicyUsage: options.durability?.reservePolicyUsage,\n hookServices,\n });\n\n return executePreparedToolCall(\n context,\n turnId,\n toolkit,\n call,\n trace,\n resultBounds,\n (waiting) => {\n waitingByDeclaration.set(call.declarationIndex, waiting);\n },\n ).pipe(\n Stream.provideService(DurableStep, stepServiceFor(call)),\n Stream.provideService(SubagentHost, subagentHost(source)),\n Stream.provideService(MessagingHost, messagingHost(source)),\n // Construct and close the broker within this call's permit. Inner\n // invocations use the handler's fiber and acquire no batch permit;\n // retained passes cannot outlive the call's scheduling authority.\n Stream.provideService(ToolBroker, broker.service),\n Stream.provideService(CurrentToolCatalog, { entries: context.toolCatalog }),\n Stream.ensuring(Effect.sync(() => broker.close())),\n );\n }),\n ),\n ).channel,\n );\n\n // Stream.mergeAll uses sequential concatenation at concurrency one. Keep a scoped call\n // fiber even then so early downstream close still runs terminal telemetry and observers.\n const next = Stream.fromChannel(\n Channel.mergeAll(Channel.fromIterable(channels), { concurrency }),\n );\n\n return stream.pipe(Stream.concat(next));\n }, Stream.empty);\n\n // This batch's live sink uses bounded structured backpressure. The Run's own stream drains\n // it concurrently with handlers, so a burst may suspend its emitting handler but a detached\n // external observer can never backpressure the batch. Emitting after settlement still fails\n // closed with `RunEventSinkClosedError`.\n const sinkQueue = yield* Queue.bounded<ToolEventPayload, Cause.Done>(\n context.bufferLimits.maxSubagentEventsPerBatch,\n );\n\n const batchSink: RunEventSinkService = {\n emit: (payload) =>\n ![\n \"SubagentRequested\",\n \"SubagentStarted\",\n \"SubagentProgress\",\n \"SubagentCompleted\",\n \"SubagentFailed\",\n \"SubagentInterrupted\",\n \"SubagentJoined\",\n ].includes(payload._tag)\n ? Effect.fail(\n new RunEventSinkClosedError({ message: \"Unsupported Tool event payload\" }),\n )\n : Queue.offer(sinkQueue, payload).pipe(\n Effect.flatMap((accepted) =>\n accepted\n ? Effect.sync(() => {\n if (context.liveChildren.has(payload.childRunId)) return;\n if (\"usage\" in payload && payload.usage !== undefined) {\n context.childUsage.set(\n payload.childRunId,\n Effect.succeed(\n RunUsageReport.make({\n usage: payload.usage,\n delegatedUsage: payload.delegatedUsage ?? unknownRunTotals(),\n }),\n ),\n );\n } else if (\n payload._tag === \"SubagentStarted\" &&\n !context.childUsage.has(payload.childRunId)\n ) {\n context.childUsage.set(\n payload.childRunId,\n Effect.succeed(\n RunUsageReport.make({\n usage: unknownRunTotals(),\n delegatedUsage: unknownRunTotals(),\n }),\n ),\n );\n }\n })\n : Effect.fail(\n RunEventSinkClosedError.make({\n message: `Subagent event ${payload._tag} was emitted after its Tool batch settled`,\n }),\n ),\n ),\n ),\n };\n\n const updateAcceptance = yield* AgentUpdateAcceptance;\n let updatesOpen = true;\n\n const updateEmitter: Emitter[\"Service\"] = {\n emit: (request) =>\n context.updatePermits.withPermit(\n Effect.gen(function* () {\n if (!updatesOpen) return yield* new UpdateError({ reason: \"unavailable\" });\n if (\n request.target.id !== context.agentId ||\n request.target.updates !== context.definition.updates ||\n context.definition.updates === undefined\n )\n return yield* new UpdateError({ reason: \"identity\" });\n\n const updateId = yield* Schema.decodeEffect(IdempotencyKey)(request.updateId).pipe(\n Effect.mapError(() => new UpdateError({ reason: \"validation\" })),\n );\n\n const value = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(\n JSON.stringify(request.value),\n ).pipe(Effect.mapError(() => new UpdateError({ reason: \"validation\" })));\n\n yield* context.validateUpdate(value);\n const existing = context.updates.get(updateId);\n\n if (existing !== undefined) {\n if (!Schema.toEquivalence(Schema.Json)(existing.value, value))\n return yield* new UpdateError({ reason: \"conflict\" });\n\n return existing;\n }\n const bytes = utf8ByteLength(JSON.stringify(value));\n const maxCount = options.updates?.maxCount ?? 32;\n const maxBytes = options.updates?.maxBytes ?? 16384;\n\n if (\n !Number.isSafeInteger(maxCount) ||\n maxCount < 1 ||\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 1 ||\n context.updates.size >= maxCount ||\n context.updateBytes + bytes > maxBytes\n )\n return yield* new UpdateError({ reason: \"capacity\" });\n\n const snapshot = boundedCanonicalJsonSnapshot(value, bytes);\n\n if (snapshot === undefined) return yield* new UpdateError({ reason: \"validation\" });\n\n const accepted = yield* updateAcceptance.accept(\n Object.freeze(\n Update.make({\n schemaVersion: 1,\n agentId: context.agentId,\n threadId: context.threadId,\n runId: context.runId,\n updateId,\n sequence: context.updates.size + 1,\n value: snapshot.value,\n }),\n ),\n );\n\n const validated = yield* Schema.decodeEffect(Update)(accepted).pipe(\n Effect.mapError(() => new UpdateError({ reason: \"validation\" })),\n );\n\n if (\n validated.agentId !== context.agentId ||\n validated.threadId !== context.threadId ||\n validated.runId !== context.runId ||\n validated.updateId !== request.updateId ||\n !Schema.toEquivalence(Schema.Json)(validated.value, value)\n )\n return yield* new UpdateError({ reason: \"identity\" });\n\n // Keep acknowledgements, replay, and retries on the same owned value even when\n // the accepting host retains its own mutable Update instance.\n const update = Object.freeze(Update.make({ ...validated, value: snapshot.value }));\n\n context.updates.set(request.updateId, update);\n context.updateBytes += bytes;\n\n const published = yield* Queue.offer(sinkQueue, {\n _tag: \"AgentUpdateEmitted\",\n update,\n });\n\n if (!published) return yield* new UpdateError({ reason: \"unavailable\" });\n\n return update;\n }),\n ),\n };\n\n // The batch fails only after already-emitted Subagent events surface:\n // a handler failure cause is held back, the sink queue is ended and\n // fully drained through the merge, and the cause is rethrown once both\n // sides finish. External interruption bypasses the capture and tears\n // the whole batch down through ordinary Scope closure. The widened\n // annotation reabsorbs the local `RunEventSink` exclusion because the\n // Run boundary in `stream` owns the public exclusion.\n let settledCause:\n | Cause.Cause<ModelProtocolError | AiError.AiError | Tool.HandlerError<ToolUnion<Tools>>>\n | undefined;\n\n const settling: Stream.Stream<\n RunEvent,\n never,\n ToolSpanTelemetry | ProgrammaticToolAuthorization | Tool.HandlerServices<ToolUnion<Tools>>\n > = handlers.pipe(\n Stream.provideService(RunEventSink, batchSink),\n Stream.provideService(Emitter, updateEmitter),\n Stream.provideService(SubagentDurability, batchSubagentDurability),\n Stream.catchCause((cause) => {\n settledCause = cause;\n\n return Stream.empty;\n }),\n Stream.ensuring(\n Effect.sync(() => {\n updatesOpen = false;\n }).pipe(Effect.andThen(Queue.end(sinkQueue))),\n ),\n );\n\n const sinkEvents = Stream.fromQueue(sinkQueue).pipe(\n Stream.mapEffect((payload) => stampSubagentEvent(context, turnId, payload)),\n );\n\n const settled = Stream.merge(settling, sinkEvents).pipe(\n Stream.concat(\n Stream.fromEffect(\n Effect.suspend(\n (): Effect.Effect<\n void,\n | HookError\n | AgentChildPending\n | ModelProtocolError\n | AiError.AiError\n | Tool.HandlerError<ToolUnion<Tools>>\n > => {\n if (settledCause !== undefined) {\n // A real sibling failure keeps the existing batch failure\n // policy even when another call is waiting: the Run fails\n // with the sibling's cause and the coordinator's durable\n // ledger state (not this stream) carries the attached child.\n return Effect.failCause(settledCause);\n }\n\n const waiting = [...waitingByDeclaration.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, signal]) => signal);\n\n const [first, ...rest] = waiting;\n\n if (first === undefined) {\n return Effect.void;\n }\n\n // Every non-waiting sibling has settled; the Run now suspends\n // `waitingForChild`\n // via the AgentApprovalPending-mirroring typed error below.\n const child = (signal: ToolCallWaiting) => ({\n toolCallId: signal.toolCallId,\n childThreadId: signal.childThreadId,\n childSubmissionId: signal.childSubmissionId,\n childRunId: signal.childRunId,\n });\n\n return Effect.fail(\n AgentChildPending.make({\n children: [child(first), ...rest.map(child)],\n message: `${waiting.length} durable delegation ${\n waiting.length === 1 ? \"call is\" : \"calls are\"\n } waiting on attached children; the Run suspended without settling`,\n }),\n );\n },\n ),\n ).pipe(Stream.drain),\n ),\n );\n\n return approvalPreflight.pipe(\n Stream.concat(authorizationPreflight),\n Stream.concat(preparation),\n Stream.concat(settled),\n );\n }),\n );\n\nconst schedulingConcurrency = Effect.fn(\"AgentRuntime.schedulingConcurrency\")(function* (\n configured: number,\n explicit: RunSchedulingHook | undefined,\n) {\n const scheduling = explicit ?? (yield* RunToolScheduling);\n const override = scheduling.runOverride;\n\n if (override === undefined) {\n return configured;\n }\n if (override.mode === \"sequential\") {\n return 1;\n }\n if (!Number.isInteger(override.concurrency) || override.concurrency <= 0) {\n return yield* AgentPolicyError.make({\n limit: \"usage\",\n message: \"Run Tool concurrency override must be a positive integer\",\n });\n }\n\n return Math.min(configured, override.concurrency);\n});\n\n/**\n * One terminal outcome per declared Tool Call of the completed Turn, in\n * declaration order. Provider-executed results are read from the response\n * parts; application results from the settled batch.\n */\nconst turnToolFailures = (trace: TurnTrace): ReadonlyArray<boolean> => {\n const outcomes: Array<boolean> = [];\n\n for (const [id, call] of trace.toolCalls) {\n if (call.providerExecuted) {\n for (const part of trace.parts) {\n if (part.type === \"tool-result\" && part.id === id && part.preliminary !== true) {\n outcomes.push(part.isFailure);\n break;\n }\n }\n continue;\n }\n const result = trace.applicationToolResults.find((candidate) => candidate?.id === id);\n\n // Budget-rejected calls never ran a handler; they neither advance nor\n // reset the consecutive-failure counter.\n if (result !== undefined && result.budgetRejected !== true) {\n outcomes.push(result.isFailure);\n }\n }\n\n return outcomes;\n};\n\n/**\n * Fold the completed Turn's terminal Tool outcomes into the Run's\n * consecutive-failure counter in declaration order, then enforce the\n * repeated-failure Stop Policy before the next model request. A terminal\n * success resets the counter; a `repeatedFailureLimit` of `0` disables the\n * bound.\n */\nconst applyRepeatedFailurePolicy = (\n context: RunContext,\n trace: TurnTrace,\n repeatedFailureLimit: number,\n): Effect.Effect<void, AgentPolicyError> =>\n Effect.suspend(() => {\n for (const isFailure of turnToolFailures(trace)) {\n context.consecutiveToolFailures = isFailure ? context.consecutiveToolFailures + 1 : 0;\n }\n if (repeatedFailureLimit > 0 && context.consecutiveToolFailures >= repeatedFailureLimit) {\n return Effect.fail(\n AgentPolicyError.make({\n limit: \"repeated-failures\",\n message: `Agent reached its ${repeatedFailureLimit} consecutive Tool Call failure limit`,\n }),\n );\n }\n\n return Effect.void;\n });\n\nconst inputsToPrompt = (\n inputs: ReadonlyArray<Prompt.RawInput>,\n): Effect.Effect<Prompt.Prompt, AgentInputError> =>\n Effect.try({\n try: () => Prompt.fromMessages(inputs.flatMap((input) => Prompt.make(input).content)),\n catch: (cause) =>\n AgentInputError.make({\n message: `Unable to materialize queued Run input: ${errorMessage(cause)}`,\n }),\n });\n\n/** Validate live reference context before it reaches budgeting or provider I/O. */\nconst transientInputToPrompt = (\n input: Prompt.RawInput,\n): Effect.Effect<Prompt.Prompt, AgentInputError> =>\n Effect.try({\n try: () => Prompt.make(input),\n catch: (cause) =>\n AgentInputError.make({\n message: `Unable to materialize transient Run context: ${errorMessage(cause)}`,\n }),\n }).pipe(\n Effect.flatMap((prompt) =>\n Schema.decodeEffect(Prompt.Prompt)({ content: prompt.content }).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({\n message: `Unable to materialize transient Run context: ${errorMessage(cause)}`,\n }),\n ),\n ),\n ),\n );\n\nconst advanceHistory = <HookError, HookRequirements>(\n context: RunContext,\n history: Prompt.Prompt,\n options: RunOptions<HookError, HookRequirements>,\n): Effect.Effect<void, HookError, HookRequirements> =>\n Effect.gen(function* () {\n context.history = history;\n if (options.onHistory !== undefined) {\n yield* options.onHistory(history);\n }\n });\n\nconst drainInputs = <HookError, HookRequirements>(\n context: RunContext,\n options: RunOptions<HookError, HookRequirements>,\n): Effect.Effect<ReadonlyArray<Prompt.RawInput>, HookError, HookRequirements> =>\n Effect.gen(function* () {\n if (options.input === undefined) {\n return [];\n }\n const commands = yield* options.input.drain(options.commandDrainPolicy ?? \"one\");\n const steering: Array<Prompt.RawInput> = [];\n\n for (const command of commands) {\n if (command.kind === \"steering\") {\n steering.push(command.input);\n } else {\n context.pendingFollowUps.push(command.input);\n }\n }\n\n return steering;\n });\n\nconst takeFollowUps = (\n context: RunContext,\n policy: CommandDrainPolicy,\n): ReadonlyArray<Prompt.RawInput> => {\n if (context.pendingFollowUps.length === 0) {\n return [];\n }\n if (policy === \"one\") {\n const input = context.pendingFollowUps.shift();\n\n return input === undefined ? [] : [input];\n }\n\n return context.pendingFollowUps.splice(0, context.pendingFollowUps.length);\n};\n\nconst appendInputs = <HookError, HookRequirements>(\n context: RunContext,\n source: Prompt.Prompt,\n inputs: ReadonlyArray<Prompt.RawInput>,\n options: RunOptions<HookError, HookRequirements>,\n): Effect.Effect<Prompt.Prompt, HookError | AgentInputError, HookRequirements> =>\n Effect.gen(function* () {\n if (inputs.length === 0) {\n return source;\n }\n const additions = yield* inputsToPrompt(inputs);\n const history = Prompt.fromMessages([...source.content, ...additions.content]);\n\n yield* advanceHistory(context, history, options);\n\n return history;\n });\n\n/**\n * RUN-022: bound one application Tool result at the settle seam. The bounded\n * value is what official history, the settled record, and the success event\n * all carry, so every downstream surface agrees; a within-bounds result\n * passes through with its identity preserved.\n */\nconst boundEncodedToolResult = (encodedResult: unknown, bounds: ToolResultBounds): unknown => {\n let text: string | undefined;\n\n try {\n text = JSON.stringify(encodedResult);\n } catch (cause) {\n // Fail closed (runtime spec §9): an unserializable result is unbounded by\n // construction, so the sentinel replaces it before history or records.\n return unserializableToolResult(cause);\n }\n if (text === undefined) {\n return unserializableToolResult(\"the encoded result is not a JSON value\");\n }\n const bounded = applyToolResultBounds(text, bounds);\n\n // The measured JSON representation is the ONLY value retained, in both the\n // truncated and unmodified cases: returning the original object would let a\n // stateful `toJSON` pass the byte check small and expand or throw on later\n // canonical serialization, carrying unchecked state past the boundary.\n try {\n return Schema.decodeSync(Schema.fromJsonString(Schema.Unknown))(bounded);\n } catch (cause) {\n // Defensive only: `applyToolResultBounds` always emits valid JSON.\n return unserializableToolResult(cause);\n }\n};\n\n/** Deterministic inputs of one run-status message (RUN-024). */\nexport interface RunStatusView {\n readonly turn: number;\n readonly maxTurns: number;\n readonly toolCallsUsed: number;\n readonly maxToolCalls: number;\n readonly tokensConsumed: number;\n readonly tokenBudget: number | undefined;\n readonly completionReserveTokens?: number;\n readonly lastInputTokens: number;\n readonly elapsedSeconds: number;\n readonly maxDurationSeconds: number;\n}\n\nconst RUN_STATUS_WARNING =\n \" · WARNING: approaching limits — converge and deliver your final result now.\";\n\n/** Fraction checks use `consumed * 5 >= limit * 4` so the 80% threshold stays integer-exact. */\nconst nearingLimit = (consumed: number, limit: number): boolean => consumed * 5 >= limit * 4;\n\n/**\n * RUN-024: render the derived run-status message appended to each outgoing\n * model request. The format is pinned here — tests target this function.\n */\nexport const formatRunStatus = (view: RunStatusView): string => {\n const researchBudget =\n view.tokenBudget === undefined\n ? undefined\n : Math.max(0, view.tokenBudget - (view.completionReserveTokens ?? 0));\n\n const remainingResearch =\n researchBudget === undefined ? undefined : Math.max(0, researchBudget - view.tokensConsumed);\n\n const warn =\n nearingLimit(view.turn, view.maxTurns) ||\n nearingLimit(view.toolCallsUsed, view.maxToolCalls) ||\n (researchBudget !== undefined &&\n (nearingLimit(view.tokensConsumed, researchBudget) ||\n (view.lastInputTokens > 0 && (remainingResearch ?? 0) <= view.lastInputTokens))) ||\n nearingLimit(view.elapsedSeconds, view.maxDurationSeconds);\n\n const reserveStatus =\n view.tokenBudget === undefined\n ? \"\"\n : ` · research-remaining ${remainingResearch} · completion-reserve ${view.completionReserveTokens ?? 0}`;\n\n return `<run-status>turn ${view.turn}/${view.maxTurns} · tool-calls ${view.toolCallsUsed}/${view.maxToolCalls} · tokens ${view.tokensConsumed}/${view.tokenBudget ?? \"unbounded\"}${reserveStatus} · last-context ${view.lastInputTokens} · elapsed ${view.elapsedSeconds}s/${view.maxDurationSeconds}s${warn ? RUN_STATUS_WARNING : \"\"}</run-status>`;\n};\n\n/**\n * The run-status message is derived per request and appended only to the\n * OUTGOING prompt: official history and durable commits never carry it, so it\n * can never accumulate or replay.\n */\nconst outgoingModelPrompt = (\n policy: AgentPolicy,\n context: RunContext,\n prepared: Prompt.Prompt,\n turn: number,\n declaredToolCalls: number,\n): Effect.Effect<Prompt.Prompt> =>\n Effect.gen(function* () {\n if (policy.runStatus !== \"appended\") {\n return prepared;\n }\n const now = yield* Clock.currentTimeMillis;\n\n const status = formatRunStatus({\n turn,\n maxTurns: policy.maxTurns,\n toolCallsUsed: declaredToolCalls + context.programmaticToolCalls,\n maxToolCalls: policy.maxToolCalls,\n tokensConsumed: context.inputTokens + context.outputTokens,\n tokenBudget: policy.tokenBudget,\n completionReserveTokens: policy.completionReserveTokens,\n lastInputTokens: context.lastInputTokens,\n elapsedSeconds: Math.max(0, Math.floor((now - context.startedAtMillis) / 1000)),\n maxDurationSeconds: Math.floor(Duration.toMillis(policy.maxDuration) / 1000),\n });\n\n return Prompt.fromMessages([\n ...prepared.content,\n Prompt.makeMessage(\"user\", {\n content: [Prompt.makePart(\"text\", { text: status })],\n }),\n ]);\n });\n\n/** Usage accounting outcome of one completed model response (RUN-025). */\ninterface ConsumedUsage {\n /** A finalize-eligible budget breach under `onExhaustion: \"final-answer\"`. */\n readonly breach: AgentPolicyError | undefined;\n readonly warnings: ReadonlyArray<RunEvent>;\n readonly modelUsage: ModelCallUsage;\n}\n\nconst ProviderUsage = Schema.Struct({\n inputTokens: Schema.Struct({\n uncached: Schema.optional(Schema.Natural),\n total: Schema.optional(Schema.Natural),\n cacheRead: Schema.optional(Schema.Natural),\n cacheWrite: Schema.optional(Schema.Natural),\n }),\n outputTokens: Schema.Struct({\n total: Schema.optional(Schema.Natural),\n text: Schema.optional(Schema.Natural),\n reasoning: Schema.optional(Schema.Natural),\n }),\n});\n\nconst invalidProviderUsage = () =>\n ModelProtocolError.make({\n message: \"Model response usage fields and derived totals must be non-negative safe integers\",\n });\n\nconst decodeProviderUsageTotal = (value: number): Effect.Effect<number, ModelProtocolError> =>\n Schema.decodeEffect(Schema.Natural)(value).pipe(Effect.mapError(() => invalidProviderUsage()));\n\nconst consumeUsage = <AgentValue extends Agent.Any, HookError, HookRequirements>(\n agent: AgentValue,\n context: RunContext,\n usage: Response.Usage | undefined,\n toolCallCount: number,\n turn: number,\n options: RunOptions<HookError, HookRequirements>,\n response: Pick<RunCostEstimateRequest, \"response\" | \"finishMetadata\" | \"purpose\"> = {},\n): Effect.Effect<\n ConsumedUsage,\n AgentPolicyError | ModelProtocolError | HookError,\n HookRequirements | Model.ProviderName | Model.ModelName\n> =>\n Effect.gen(function* () {\n if (usage === undefined) {\n return yield* AgentPolicyError.make({\n limit: \"usage\",\n message: \"A completed model response did not report usage\",\n });\n }\n\n const providerUsage = yield* Schema.decodeEffect(ProviderUsage)(usage).pipe(\n Effect.mapError(() => invalidProviderUsage()),\n );\n\n const reportedUncached = providerUsage.inputTokens.uncached ?? 0;\n const cacheRead = providerUsage.inputTokens.cacheRead ?? 0;\n const cacheWrite = providerUsage.inputTokens.cacheWrite ?? 0;\n const reportedText = providerUsage.outputTokens.text ?? 0;\n const reasoning = providerUsage.outputTokens.reasoning ?? 0;\n // Gross token accounting never discounts cache activity. An omitted\n // aggregate is derived from present components; an omitted component may\n // receive the aggregate remainder. Explicitly contradictory fields fail.\n // Some providers include cache writes in `uncached` while also reporting\n // them separately. Separate that overlap before constructing the canonical,\n // additive input components, but retain the raw provider usage for pricing.\n const reportedInputTotal = providerUsage.inputTokens.total;\n const reportedInputWithoutWrite = yield* decodeProviderUsageTotal(reportedUncached + cacheRead);\n\n const cacheWriteOverlapsUncached =\n reportedInputTotal !== undefined &&\n providerUsage.inputTokens.uncached !== undefined &&\n providerUsage.inputTokens.cacheWrite !== undefined &&\n cacheWrite <= reportedUncached &&\n reportedInputWithoutWrite <= reportedInputTotal &&\n cacheWrite > reportedInputTotal - reportedInputWithoutWrite;\n\n const disjointReportedUncached =\n reportedUncached - (cacheWriteOverlapsUncached ? cacheWrite : 0);\n\n const reportedInputComponents = yield* decodeProviderUsageTotal(\n disjointReportedUncached + cacheRead + cacheWrite,\n );\n\n const allInputComponentsReported =\n providerUsage.inputTokens.uncached !== undefined &&\n providerUsage.inputTokens.cacheRead !== undefined &&\n providerUsage.inputTokens.cacheWrite !== undefined;\n\n if (\n reportedInputTotal !== undefined &&\n (reportedInputTotal < reportedInputComponents ||\n (allInputComponentsReported && reportedInputTotal !== reportedInputComponents))\n ) {\n return yield* invalidProviderUsage();\n }\n const inputTokens = reportedInputTotal ?? reportedInputComponents;\n const reportedOutputComponents = yield* decodeProviderUsageTotal(reportedText + reasoning);\n const reportedOutputTotal = providerUsage.outputTokens.total;\n\n const allOutputComponentsReported =\n providerUsage.outputTokens.text !== undefined &&\n providerUsage.outputTokens.reasoning !== undefined;\n\n if (\n reportedOutputTotal !== undefined &&\n (reportedOutputTotal < reportedOutputComponents ||\n (allOutputComponentsReported && reportedOutputTotal !== reportedOutputComponents))\n ) {\n return yield* invalidProviderUsage();\n }\n const outputTokens = reportedOutputTotal ?? reportedOutputComponents;\n // When a provider reports only aggregates, classify the unexplained input\n // conservatively as uncached and non-reasoning output as text when those\n // fields are absent. If either was explicit, assign the remainder to the\n // first genuinely omitted component so no provider-supplied value changes.\n const inputRemainder = inputTokens - reportedInputComponents;\n const outputRemainder = outputTokens - reportedOutputComponents;\n\n const uncached =\n disjointReportedUncached +\n (providerUsage.inputTokens.uncached === undefined ? inputRemainder : 0);\n\n const normalizedCacheRead =\n cacheRead +\n (providerUsage.inputTokens.uncached !== undefined &&\n providerUsage.inputTokens.cacheRead === undefined\n ? inputRemainder\n : 0);\n\n const normalizedCacheWrite =\n cacheWrite +\n (providerUsage.inputTokens.uncached !== undefined &&\n providerUsage.inputTokens.cacheRead !== undefined &&\n providerUsage.inputTokens.cacheWrite === undefined\n ? inputRemainder\n : 0);\n\n const text =\n reportedText + (providerUsage.outputTokens.text === undefined ? outputRemainder : 0);\n\n const normalizedReasoning =\n reasoning +\n (providerUsage.outputTokens.text !== undefined &&\n providerUsage.outputTokens.reasoning === undefined\n ? outputRemainder\n : 0);\n\n const totalTokens = yield* decodeProviderUsageTotal(inputTokens + outputTokens);\n const provider = yield* Model.ProviderName;\n const model = yield* Model.ModelName;\n\n const estimate =\n options.estimateCostMicrousd === undefined\n ? 0\n : yield* options.estimateCostMicrousd(usage, { provider, model, usage, ...response });\n\n const costMicrousd = typeof estimate === \"number\" ? estimate : estimate.costMicrousd;\n\n if (!Number.isSafeInteger(costMicrousd) || costMicrousd < 0) {\n return yield* AgentPolicyError.make({\n limit: \"cost\",\n message: \"Model cost estimation must produce a non-negative integer number of microdollars\",\n });\n }\n const serviceTier = typeof estimate === \"number\" ? undefined : estimate.serviceTier;\n const pricingVersion = typeof estimate === \"number\" ? undefined : estimate.pricingVersion;\n\n const pricingStatus =\n options.estimateCostMicrousd === undefined\n ? \"unknown\"\n : typeof estimate === \"number\"\n ? \"estimated\"\n : (estimate.pricingStatus ?? \"estimated\");\n\n const validPricingIdentity = (value: string | undefined): boolean =>\n value === undefined || (value.length > 0 && value.length <= 256);\n\n if (!validPricingIdentity(serviceTier) || !validPricingIdentity(pricingVersion)) {\n return yield* AgentPolicyError.make({\n limit: \"cost\",\n message: \"Model cost estimation returned an invalid service tier or pricing version\",\n });\n }\n\n const modelUsage = ModelCallUsage.make({\n provider,\n model,\n ...(response.response === undefined\n ? {}\n : { response: ModelResponseIdentity.make(response.response) }),\n purpose: response.purpose ?? \"turn\",\n usageStatus:\n Object.values(providerUsage.inputTokens).every((value) => value === undefined) &&\n Object.values(providerUsage.outputTokens).every((value) => value === undefined)\n ? \"unknown\"\n : [\n providerUsage.inputTokens.uncached,\n providerUsage.inputTokens.cacheRead,\n providerUsage.inputTokens.cacheWrite,\n providerUsage.outputTokens.text,\n providerUsage.outputTokens.reasoning,\n ].every((value) => value !== undefined)\n ? \"complete\"\n : \"partial\",\n pricingStatus,\n ...(serviceTier === undefined ? {} : { serviceTier }),\n ...(pricingVersion === undefined ? {} : { pricingVersion }),\n inputTokens: InputTokenUsage.make({\n total: inputTokens,\n uncached,\n cacheRead: normalizedCacheRead,\n cacheWrite: normalizedCacheWrite,\n }),\n outputTokens: OutputTokenUsage.make({\n total: outputTokens,\n text,\n reasoning: normalizedReasoning,\n }),\n costMicrousd,\n });\n\n const modelCalls = yield* decodeProviderUsageTotal(context.modelCalls + 1);\n\n const cumulativeInputTokens = yield* decodeProviderUsageTotal(\n context.inputTokens + inputTokens,\n );\n\n const cumulativeOutputTokens = yield* decodeProviderUsageTotal(\n context.outputTokens + outputTokens,\n );\n\n const cumulativeCostMicrousd = context.costMicrousd + costMicrousd;\n\n if (!Number.isSafeInteger(cumulativeCostMicrousd)) {\n return yield* AgentPolicyError.make({\n limit: \"cost\",\n message: \"Cumulative model cost exceeds safe-integer accounting capacity\",\n });\n }\n const firstObserved = context.modelCalls === 0 && context.unobservedModelCalls === 0;\n\n const combineStatus = (\n prior: typeof UsageCompleteness.Type,\n next: typeof UsageCompleteness.Type,\n ) => (firstObserved && prior === \"complete\" ? next : prior === next ? prior : \"partial\");\n\n context.usageStatus = combineStatus(context.usageStatus, modelUsage.usageStatus ?? \"unknown\");\n context.pricingStatus = combineStatus(\n context.pricingStatus,\n pricingStatus === \"estimated\" ? \"complete\" : \"unknown\",\n );\n context.modelCalls = modelCalls;\n context.inputTokens = cumulativeInputTokens;\n context.outputTokens = cumulativeOutputTokens;\n context.lastInputTokens = inputTokens;\n context.lastOutputTokens = outputTokens;\n context.costMicrousd = cumulativeCostMicrousd;\n context.lastCostMicrousd = costMicrousd;\n\n if (options.durability !== undefined) {\n // Stage before enforcing hard rails: a response that spends past the\n // cost/token budget still becomes auditable in its canonical Turn and\n // terminal settlement.\n yield* options.durability.noteTurnUsage({ turn, usage: modelUsage });\n }\n\n const policy = agent.definition.policy;\n const consumedTokens = context.inputTokens + context.outputTokens;\n const tokenBudget = policy.tokenBudget;\n let breach: AgentPolicyError | undefined;\n\n if (\n !context.finalizing &&\n !context.tokenExhausted &&\n tokenBudget !== undefined &&\n consumedTokens > tokenBudget\n ) {\n breach = AgentPolicyError.make({\n limit: \"tokens\",\n message: `Agent exceeded its ${tokenBudget} token budget`,\n });\n // Fail mode rejects before any declared application Handler starts.\n if (policy.onExhaustion === \"fail\") {\n return yield* breach;\n }\n // One-shot (RUN-025): the flag joins the final-answer derivation so the\n // grace Turn's own usage accumulates and charges without re-breaching.\n context.tokenExhausted = true;\n context.exhaustedDimension ??= \"tokens\";\n }\n // Cost is an unconditional hard rail (runtime spec §3): it is enforced on\n // every response, including one that just soft-breached the token budget —\n // a simultaneous breach fails typed instead of soft-landing on overspend.\n const costBudget = policy.costBudgetMicrousd;\n\n if (costBudget !== undefined) {\n if (options.estimateCostMicrousd === undefined) {\n return yield* AgentPolicyError.make({\n limit: \"cost\",\n message: \"Agent cost budget requires a model cost estimator\",\n });\n }\n if (pricingStatus === \"unknown\") {\n return yield* AgentPolicyError.make({\n limit: \"cost\",\n message: \"Agent cost budget requires a known model cost estimate\",\n });\n }\n if (context.costMicrousd > costBudget) {\n // Cost is spend, not context: it never earns a grace Turn.\n return yield* AgentPolicyError.make({\n limit: \"cost\",\n message: `Agent exceeded its ${costBudget} microdollar cost budget`,\n });\n }\n }\n if (options.budget !== undefined) {\n const delta: RunUsageDelta = {\n modelCalls: 1,\n inputTokens,\n outputTokens,\n totalTokens,\n toolCalls: toolCallCount,\n costMicrousd,\n usage,\n modelUsage,\n };\n\n yield* options.budget.consume(delta);\n }\n const warnings: Array<RunEvent> = [];\n\n if (\n tokenBudget !== undefined &&\n !context.warnedLimits.has(\"tokens\") &&\n nearingLimit(consumedTokens, tokenBudget)\n ) {\n context.warnedLimits.add(\"tokens\");\n warnings.push(\n BudgetWarning.make({\n ...(yield* eventBase(context)),\n limit: \"tokens\",\n consumed: consumedTokens,\n limitValue: tokenBudget,\n }),\n );\n }\n\n return { breach, warnings, modelUsage };\n });\n\n// `Effect.fnUntraced`: this helper runs for every streamed Response Part, so a\n// named span here would emit one span per TextDelta/ReasoningDelta. Spans stay\n// on per-Run, per-Turn, and per-Tool operations.\nconst eventBaseFor = Effect.fnUntraced(function* (context: RunContext, terminal: boolean) {\n const ceiling = terminal\n ? context.bufferLimits.maxRunEvents\n : context.bufferLimits.maxRunEvents - 1;\n\n if (context.sequence >= ceiling) {\n return yield* ModelProtocolError.make({\n message: `Run exceeded the ${context.bufferLimits.maxRunEvents}-event buffer limit`,\n });\n }\n const timestamp = DateTime.makeUnsafe(yield* Clock.currentTimeMillis);\n const sequence = context.sequence;\n\n context.sequence += 1;\n\n return {\n eventVersion: 1 as const,\n runId: context.runId,\n threadId: context.threadId,\n agentId: context.agentId,\n sequence,\n timestamp,\n };\n});\n\nconst eventBase = (context: RunContext) => eventBaseFor(context, false);\n\n/** The ordinary event budget always reserves one slot for this typed terminal projection. */\nconst terminalEventBase = (context: RunContext) => eventBaseFor(context, true);\n\nconst toolProgressLimitError = (context: RunContext) =>\n ModelProtocolError.make({\n message: `Run exceeded the ${context.bufferLimits.maxToolProgressBytes}-byte Tool progress limit or received invalid progress JSON`,\n });\n\nconst admitToolProgress = (\n context: RunContext,\n snapshot: BoundedJsonSnapshot,\n): Effect.Effect<Schema.Json, ModelProtocolError> =>\n Effect.suspend(() => {\n if (snapshot.bytes > context.bufferLimits.maxToolProgressBytes - context.toolProgressBytes) {\n return Effect.fail(toolProgressLimitError(context));\n }\n context.toolProgressBytes += snapshot.bytes;\n\n return Effect.succeed(snapshot.value);\n });\n\nconst ownApplicationToolProgress = (\n context: RunContext,\n result: unknown,\n): Effect.Effect<Schema.Json, ModelProtocolError> =>\n Effect.suspend(() => {\n // Bound traversal before Schema validation or serialization can allocate a full copy. The\n // owned frozen value is the only payload published to live consumers and detached replay.\n const snapshot = boundedCanonicalJsonSnapshot(\n result,\n context.bufferLimits.maxToolProgressBytes - context.toolProgressBytes,\n );\n\n return snapshot === undefined\n ? Effect.fail(toolProgressLimitError(context))\n : admitToolProgress(context, snapshot);\n });\n\nconst snapshotStagedProviderEvent = (\n trace: TurnTrace,\n payload: unknown,\n): Effect.Effect<BoundedJsonSnapshot, ModelProtocolError> =>\n Effect.suspend(() => {\n const stagedEventCount =\n trace.providerResultPayloads.length + (trace.turnCompletion === undefined ? 0 : 1);\n\n if (stagedEventCount >= MAX_STAGED_PROVIDER_EVENTS) {\n return Effect.fail(\n ModelProtocolError.make({\n message: `Model response exceeded the ${MAX_STAGED_PROVIDER_EVENTS}-event staged provider event limit`,\n }),\n );\n }\n\n const snapshot = boundedJsonSnapshot(\n payload,\n MAX_STAGED_PROVIDER_BYTES - trace.providerStagedPayloadBytes,\n );\n\n if (snapshot === undefined) {\n return Effect.fail(\n ModelProtocolError.make({\n message: `Model response exceeded the ${MAX_STAGED_PROVIDER_BYTES}-byte staged provider event limit`,\n }),\n );\n }\n\n return Effect.succeed(snapshot);\n });\n\nconst stageProviderResultPayload = (\n trace: TurnTrace,\n payload: ProviderResultEventPayload,\n): Effect.Effect<void, ModelProtocolError> =>\n Effect.gen(function* () {\n const snapshot = yield* snapshotStagedProviderEvent(trace, payload);\n const snapshotObject = snapshot.value;\n\n if (\n snapshotObject === null ||\n typeof snapshotObject !== \"object\" ||\n Array.isArray(snapshotObject) ||\n Object.getPrototypeOf(snapshotObject) !== null\n ) {\n return yield* ModelProtocolError.make({\n message: \"Provider Tool result could not be normalized as JSON\",\n });\n }\n const resultDescriptor = Object.getOwnPropertyDescriptor(snapshotObject, \"result\");\n\n const normalizedResult =\n resultDescriptor !== undefined && \"value\" in resultDescriptor\n ? Schema.decodeUnknownOption(Schema.Json)(resultDescriptor.value)\n : Option.none<Schema.Json>();\n\n if (payload._tag !== \"ToolCallFailed\" && Option.isNone(normalizedResult)) {\n return yield* ModelProtocolError.make({\n message: \"Provider Tool result could not be normalized as JSON\",\n });\n }\n\n const normalized: ProviderResultEventPayload =\n payload._tag === \"ToolCallFailed\"\n ? Object.freeze({ ...payload })\n : Object.freeze({ ...payload, result: Option.getOrThrow(normalizedResult) });\n\n trace.providerResultPayloads.push(normalized);\n trace.providerStagedPayloadBytes += snapshot.bytes;\n });\n\nconst ProviderToolResultSnapshot = Schema.Struct({\n result: Schema.Json,\n metadata: Schema.Record(Schema.String, Schema.Json),\n});\n\nconst snapshotProviderToolResultPart = Effect.fnUntraced(function* (\n trace: TurnTrace,\n part: Response.ToolResultPart<string, unknown, unknown>,\n) {\n const snapshot = boundedJsonSnapshot(\n { result: part.encodedResult, metadata: part.metadata },\n MAX_STAGED_PROVIDER_BYTES - trace.providerStagedPayloadBytes,\n );\n\n if (snapshot === undefined) {\n return yield* ModelProtocolError.make({\n message: `Model response exceeded the ${MAX_STAGED_PROVIDER_BYTES}-byte staged provider event limit`,\n });\n }\n\n const normalized = yield* Schema.decodeUnknownEffect(ProviderToolResultSnapshot)(\n snapshot.value,\n ).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({\n message: \"Provider Tool result could not be normalized as JSON\",\n }),\n ),\n );\n\n trace.providerStagedPayloadBytes += snapshot.bytes;\n\n return normalized;\n});\n\nconst stampProviderResultEvent = (\n context: RunContext,\n turnId: TurnId,\n payload: ProviderResultEventPayload,\n): Effect.Effect<RunEvent, ModelProtocolError> =>\n Effect.gen(function* () {\n if (payload._tag === \"ToolProgress\") {\n // Provider staging already owns and normalizes this value under its 1 MiB aggregate cap.\n // Measure that bounded representation and reuse it without changing provider JSON semantics.\n const text = yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Json))(\n payload.result,\n ).pipe(Effect.mapError(() => toolProgressLimitError(context)));\n\n yield* admitToolProgress(context, { value: payload.result, bytes: utf8ByteLength(text) });\n }\n const base = yield* eventBase(context);\n\n switch (payload._tag) {\n case \"ToolProgress\":\n return ToolProgress.make({ ...base, turnId, ...payload });\n case \"ToolCallSucceeded\":\n return ToolCallSucceeded.make({ ...base, turnId, ...payload });\n case \"ToolCallFailed\":\n return ToolCallFailed.make({\n ...base,\n turnId,\n ...payload,\n failureHandling: \"returned-to-model\",\n });\n }\n });\n\n/**\n * RUN-026: deterministic estimate of the NEXT model call's live context.\n * Anchored on the last provider-reported call when the view has only grown\n * since then; a fresh Run or a just-compacted view falls back to the full\n * chars/4 estimate.\n */\nconst estimateContextTokens = Effect.fn(\"AgentRuntime.estimateContextTokens\")(function* (\n messages: ReadonlyArray<Prompt.Message>,\n messageTokenEstimator?: ContextMessageTokenEstimator,\n) {\n const compactor = yield* ContextCompactor;\n\n const estimate =\n messageTokenEstimator === undefined\n ? Option.some(compactor.estimate(messages))\n : evaluateMessageTokenEstimates(messageTokenEstimator, (estimate) =>\n estimatePromptTokens(messages, estimate),\n );\n\n if (Option.isNone(estimate)) {\n return yield* CompactionError.make({\n message: \"Message token estimator returned an invalid token count\",\n });\n }\n\n return yield* Schema.decodeEffect(Schema.Natural)(estimate.value).pipe(\n Effect.mapError((cause) =>\n CompactionError.make({ message: \"Compactor returned an invalid token estimate\", cause }),\n ),\n );\n});\n\nconst nextContextEstimate = Effect.fn(\"AgentRuntime.nextContextEstimate\")(function* (\n context: RunContext,\n view: ReadonlyArray<Prompt.Message>,\n) {\n const state = context.compaction;\n\n if (\n context.lastInputTokens > 0 &&\n state.lastViewLength >= 0 &&\n state.lastViewLength <= view.length\n ) {\n return (\n context.lastInputTokens +\n context.lastOutputTokens +\n (yield* estimateContextTokens(view.slice(state.lastViewLength)))\n );\n }\n\n return yield* estimateContextTokens(view);\n});\n\nconst snapshotCompactionMessages = Effect.fnUntraced(function* (\n messages: ReadonlyArray<Prompt.Message>,\n) {\n return yield* Effect.try({\n try: () =>\n messages.map((message) =>\n Schema.decodeUnknownSync(Schema.Json)(\n JSON.parse(JSON.stringify(Schema.encodeSync(Prompt.Message)(message))),\n ),\n ),\n catch: (cause) =>\n CompactionError.make({ message: \"Could not snapshot prepared compaction history\", cause }),\n });\n});\n\n/** Text a provider overflow classification matches against (message + reason). */\nconst overflowText = (error: AiError.AiError): string => `${error.message} ${error.reason.message}`;\n\n/** Outcome of one compaction pass: the advisory events to splice into the Run stream. */\ninterface CompactionOutcome {\n readonly events: ReadonlyArray<RunEvent>;\n}\n\n/**\n * Consume the installed strategy under engine-owned bounds. Validate each decision, commit it,\n * then update the disposable view. Summary model calls retain the Run's response-buffer and\n * budget guards; default summaries also obey the captured Model's input allowance. Pricing\n * reads the selected Model's identity inside the same provision scope.\n */\nconst compactContext = <AgentValue extends Agent.Any, HookError, HookRequirements>(\n agent: AgentValue,\n context: RunContext,\n source: Prompt.Prompt,\n turn: number,\n options: RunOptions<HookError, HookRequirements>,\n resolvedModelInputLimit: number | undefined,\n messageTokenEstimator: ContextMessageTokenEstimator | undefined,\n targetTokens: number | undefined,\n trigger: \"pressure\" | \"overflow\" | \"requested\",\n modelCallAllowed = true,\n requested?: ContextRolloverSelection,\n): Effect.Effect<\n CompactionOutcome,\n AgentPolicyError | ModelProtocolError | AiError.AiError | CompactionError | HookError,\n | HookRequirements\n | ContextCompactor\n | ModelUsageAccounting\n | LanguageModel.LanguageModel\n | Model.ProviderName\n | Model.ModelName\n> =>\n Effect.gen(function* () {\n const state = context.compaction;\n const events: Array<RunEvent> = [];\n const messages = source.content;\n const allowance = context.compactionTurn;\n const preparedSource = context.preparedCompactionSource;\n\n const preparedSnapshot =\n preparedSource === undefined ? undefined : yield* snapshotCompactionMessages(messages);\n\n if (preparedSource !== undefined && preparedSnapshot !== undefined) {\n let start = -1;\n let end = 0;\n let mapped = true;\n const positions: Array<number> = [];\n\n const originalPositions = preparedSource.protectedReferences.map((message) =>\n messages.indexOf(message),\n );\n\n const originalMapping = preparedSource.protectedReferences.every((message, position) => {\n const index = originalPositions[position];\n\n return (\n index !== undefined &&\n index >= 0 &&\n index > (originalPositions[position - 1] ?? -1) &&\n messages.lastIndexOf(message) === index &&\n Equal.equals(preparedSnapshot[index], preparedSource.protectedMessages[position])\n );\n });\n\n for (\n let position = 0;\n !originalMapping && position < preparedSource.protectedMessages.length;\n position += 1\n ) {\n const protectedMessage = preparedSource.protectedMessages[position];\n\n const index = preparedSnapshot.findIndex(\n (message, index) => index >= end && Equal.equals(message, protectedMessage),\n );\n\n if (index < 0) {\n mapped = false;\n break;\n }\n if (start < 0) start = index;\n end = index + 1;\n positions.push(index);\n }\n let reverseEnd = preparedSnapshot.length;\n\n for (\n let position = preparedSource.protectedMessages.length - 1;\n !originalMapping && mapped && position >= 0;\n position -= 1\n ) {\n const protectedMessage = preparedSource.protectedMessages[position];\n\n const index = preparedSnapshot.findLastIndex(\n (message, index) => index < reverseEnd && Equal.equals(message, protectedMessage),\n );\n\n if (index !== positions[position]) mapped = false;\n reverseEnd = index;\n }\n if (originalMapping) {\n mapped = true;\n start = originalPositions[0] ?? -1;\n end = (originalPositions.at(-1) ?? -1) + 1;\n }\n if (!mapped) {\n return yield* CompactionError.make({\n message:\n \"Prepared context cannot map the protected instructions and input for compaction\",\n });\n }\n // Durable callers supply the original canonical instructions/input block.\n state.protectedStart = mapped ? start : -1;\n state.protectedEnd = mapped ? end : -1;\n state.protectSystemMessages = true;\n }\n\n const resolvedRequest =\n requested === undefined\n ? undefined\n : { ...requested, through: requested.through ?? Math.max(0, state.protectedStart) };\n\n if (\n requested !== undefined &&\n requested.through === undefined &&\n resolvedRequest !== undefined &&\n (resolvedRequest.through <= (state.replacement?.through ?? 0) ||\n collectCoveredMessages(messages, state, resolvedRequest.through).length === 0)\n ) {\n return { events };\n }\n\n if (allowance.turn !== turn) {\n allowance.turn = turn;\n allowance.summaryCalls = 0;\n allowance.applied.clear();\n }\n if (allowance.applied.has(\"summarize\") || allowance.applied.has(\"rollover\")) {\n return yield* CompactionError.make({\n message: \"Compaction already replaced this Turn's context\",\n });\n }\n\n const before = yield* estimateContextTokens(\n buildCompactedView(messages, state),\n messageTokenEstimator,\n );\n\n const summarize = (summarizerPrompt: Prompt.Prompt, model?: CompactionModelLayer) => {\n const generate = Effect.gen(function* () {\n if (allowance.summaryCalls++ > 0 || !modelCallAllowed) {\n return yield* CompactionError.make({\n message: \"Compaction exceeded its summary-call allowance\",\n });\n }\n if (\n model === undefined &&\n resolvedModelInputLimit !== undefined &&\n (yield* estimateContextTokens(summarizerPrompt.content, messageTokenEstimator)) >\n resolvedModelInputLimit\n ) {\n return yield* CompactionError.make({\n message: \"Compaction summary request exceeds the resolved model input limit\",\n });\n }\n const pieces: Array<string> = [];\n\n const responseUsage: ModelResponseBufferUsage = {\n responsePartCount: 0,\n responsePartBytes: 0,\n };\n\n let summaryUsage: Response.Usage | undefined;\n let summaryResponse: ModelResponseIdentity | undefined;\n let summaryFinishMetadata: Response.FinishPart[\"metadata\"] | undefined;\n let summaryFinished = false;\n let summaryFailure: ModelProtocolError | undefined;\n const textParts = new Map<string, PartLifecycle>();\n const reasoningParts = new Map<string, PartLifecycle>();\n\n const summaryExit = yield* guardBudgetStream(\n LanguageModel.streamText({ prompt: summarizerPrompt }),\n options.budget,\n ).pipe(\n Stream.provideServiceEffect(Tracer.Tracer, modelTelemetryTracer(context)),\n Stream.runForEach((part) =>\n Effect.gen(function* () {\n const owned = yield* ownModelResponsePart(\n part,\n Toolkit.empty,\n responseUsage,\n context.bufferLimits,\n );\n\n yield* consumeModelResponsePart(\n responseUsage,\n owned.retainedBytes,\n context.bufferLimits,\n );\n const ownedPart = owned.ownedPart;\n\n if (ownedPart.type === \"text-delta\") {\n pieces.push(ownedPart.delta);\n } else if (ownedPart.type === \"finish\") {\n if (summaryUsage === undefined) {\n summaryUsage = ownedPart.usage;\n summaryFinishMetadata = ownedPart.metadata;\n }\n } else if (ownedPart.type === \"response-metadata\") {\n summaryResponse = yield* responseIdentity(ownedPart, summaryResponse);\n }\n // Drain malformed responses within the buffer bounds so reported usage is charged.\n yield* Effect.gen(function* () {\n if (summaryFinished) {\n return yield* ModelProtocolError.make({\n message: \"Compaction response emitted content after its finish part\",\n });\n }\n switch (ownedPart.type) {\n case \"text-start\":\n return yield* startPart(textParts, ownedPart.id, \"compaction text\");\n case \"text-delta\":\n return yield* continuePart(textParts, ownedPart.id, \"compaction text delta\");\n case \"text-end\":\n return yield* endPart(textParts, ownedPart.id, \"compaction text\");\n case \"reasoning-start\":\n return yield* startPart(reasoningParts, ownedPart.id, \"compaction reasoning\");\n case \"reasoning-delta\":\n return yield* continuePart(\n reasoningParts,\n ownedPart.id,\n \"compaction reasoning delta\",\n );\n case \"reasoning-end\":\n return yield* endPart(reasoningParts, ownedPart.id, \"compaction reasoning\");\n case \"finish\": {\n summaryFinished = true;\n if (\n ownedPart.reason !== \"stop\" ||\n [...textParts.values(), ...reasoningParts.values()].includes(\"open\")\n ) {\n return yield* ModelProtocolError.make({\n message:\n \"Compaction response did not finish with complete text and a stop reason\",\n });\n }\n\n return;\n }\n case \"tool-params-start\":\n case \"tool-params-delta\":\n case \"tool-params-end\":\n case \"tool-approval-request\":\n case \"error\":\n return yield* ModelProtocolError.make({\n message: `Compaction response contained an unusable ${ownedPart.type} part`,\n });\n case \"file\":\n case \"response-metadata\":\n case \"source\":\n return;\n }\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n summaryFailure ??= error;\n }),\n ),\n );\n }),\n ),\n Effect.exit,\n );\n\n if (summaryUsage === undefined) {\n yield* noteIncompleteUsage(context, turn);\n if (Exit.isFailure(summaryExit)) return yield* Effect.failCause(summaryExit.cause);\n if (!summaryFinished)\n return yield* ModelProtocolError.make({\n message: \"Compaction response ended without a finish part\",\n });\n }\n const wasFinalizing = context.finalizing;\n const priorSummaryModelCalls = context.modelCalls;\n\n context.finalizing = true;\n\n const consumedExit = yield* consumeUsage(agent, context, summaryUsage, 0, turn, options, {\n response: summaryResponse,\n finishMetadata: summaryFinishMetadata,\n purpose: \"summary\",\n }).pipe(\n Effect.tapCause(() =>\n summaryUsage !== undefined && context.modelCalls === priorSummaryModelCalls\n ? noteIncompleteUsage(context, turn)\n : Effect.void,\n ),\n Effect.ensuring(\n Effect.sync(() => {\n context.finalizing = wasFinalizing;\n }),\n ),\n Effect.exit,\n );\n\n if (Exit.isFailure(summaryExit)) return yield* Effect.failCause(summaryExit.cause);\n if (Exit.isFailure(consumedExit)) return yield* Effect.failCause(consumedExit.cause);\n events.push(...consumedExit.value.warnings);\n if (!summaryFinished) {\n return yield* ModelProtocolError.make({\n message: \"Compaction response ended without a finish part\",\n });\n }\n const summary = pieces.join(\"\").trim();\n\n if (summaryFailure !== undefined) return yield* summaryFailure;\n if (summary.length === 0) {\n return yield* ModelProtocolError.make({\n message: \"Compaction response requires non-whitespace text and a valid finish part\",\n });\n }\n\n return summary;\n });\n\n return model === undefined ? generate : Effect.provide(generate, model);\n };\n\n const applied = allowance.applied;\n\n const compactor = yield* ContextCompactor;\n\n yield* compactor\n .compact({\n source,\n state: Object.freeze({\n ...state,\n replacement:\n state.replacement === undefined ? undefined : Object.freeze({ ...state.replacement }),\n }),\n policy: agent.definition.policy.compaction,\n targetTokens,\n threadId: context.threadId,\n runId: context.runId,\n turn,\n trigger,\n modelCallAllowed,\n ...(messageTokenEstimator === undefined\n ? {}\n : { estimateMessageTokens: messageTokenEstimator }),\n ...(resolvedRequest === undefined ? {} : { requested: resolvedRequest }),\n summarize,\n })\n .pipe(\n Stream.runForEach((candidate) =>\n Effect.gen(function* () {\n const decision = yield* Schema.decodeEffect(CompactionDecision)(candidate).pipe(\n Effect.mapError((cause) =>\n CompactionError.make({ message: \"Invalid compaction decision\", cause }),\n ),\n );\n\n if (applied.has(decision.kind) || applied.has(\"summarize\") || applied.has(\"rollover\")) {\n return yield* CompactionError.make({\n message: \"Compaction exceeded its decision allowance\",\n });\n }\n const next = { ...state, lastViewLength: -1 };\n\n if (\n resolvedRequest !== undefined &&\n (decision.kind !== \"rollover\" || decision.through !== resolvedRequest.through)\n ) {\n return yield* CompactionError.make({\n message: \"Requested rollover must cover exactly its selected source boundary\",\n });\n }\n if (decision.kind === \"rollover\") {\n if (\n decision.through <= (state.replacement?.through ?? 0) ||\n decision.through > messages.length ||\n messages[decision.through]?.role === \"tool\" ||\n collectCoveredMessages(messages, state, decision.through).length === 0\n ) {\n return yield* CompactionError.make({\n message:\n \"Rollover must advance coverage without splitting Tool pairs or discarding protected input\",\n });\n }\n next.replacement = {\n kind: \"rollover\",\n through: decision.through,\n windowId: contextWindowId(context.runId, turn),\n ...(decision.handoff === undefined ? {} : { handoff: decision.handoff }),\n };\n } else if (decision.kind === \"summarize\") {\n if (utf8ByteLength(decision.summary) > context.bufferLimits.maxModelResponseBytes) {\n return yield* CompactionError.make({\n message: \"Compaction summary exceeded the response-buffer limit\",\n });\n }\n if (\n decision.through <= (state.replacement?.through ?? 0) ||\n decision.through >= messages.length ||\n messages[decision.through]?.role === \"tool\" ||\n collectCoveredMessages(messages, state, decision.through).length === 0\n ) {\n return yield* CompactionError.make({\n message:\n \"Compaction must advance coverage without splitting Tool pairs or removing the recent tail\",\n });\n }\n next.replacement = {\n kind: \"summarize\",\n through: decision.through,\n summary: decision.summary,\n };\n } else {\n const newestTool = messages.findLastIndex((message) => message.role === \"tool\");\n\n if (decision.through <= state.clearedThrough || decision.through > newestTool) {\n return yield* CompactionError.make({\n message: \"Compaction must advance pruning while retaining the newest Tool result\",\n });\n }\n next.clearedThrough = decision.through;\n }\n\n const after = yield* estimateContextTokens(\n buildCompactedView(messages, next),\n messageTokenEstimator,\n );\n\n if (decision.kind === \"rollover\" && trigger !== \"requested\" && after >= before) {\n return yield* CompactionError.make({\n message: \"Automatic rollover did not reduce context\",\n });\n }\n\n const commit: RunCompactionCommit = {\n turn,\n source,\n through: decision.through,\n kind: decision.kind,\n ...(decision.kind === \"summarize\" ? { summary: decision.summary } : {}),\n ...(decision.kind === \"rollover\" && decision.handoff !== undefined\n ? { handoff: decision.handoff }\n : {}),\n tokensBeforeEstimate: before,\n tokensAfterEstimate: after,\n };\n\n if (options.durability !== undefined)\n yield* options.durability.commitCompaction(commit);\n Object.assign(state, next);\n if (next.replacement?.kind === \"rollover\") context.windowId = next.replacement.windowId;\n if (preparedSource !== undefined && preparedSnapshot !== undefined) {\n preparedSource.prefix = preparedSnapshot.slice(\n 0,\n Math.max(next.clearedThrough, next.replacement?.through ?? 0),\n );\n }\n applied.add(decision.kind);\n events.push(\n CompactionPerformed.make({\n ...(yield* eventBase(context)),\n turn,\n kind: decision.kind,\n tokensBeforeEstimate: before,\n tokensAfterEstimate: after,\n }),\n );\n }),\n ),\n );\n\n if (requested !== undefined && !applied.has(\"rollover\")) {\n return yield* CompactionError.make({\n message: \"Compaction strategy did not honor the requested rollover\",\n });\n }\n\n return { events };\n });\n\nconst decodeInput = Effect.fn(\"AgentRuntime.decodeInput\")(\n <AgentValue extends Agent.Any>(\n agent: AgentValue,\n input: unknown,\n ): Effect.Effect<\n Agent.Input<AgentValue>,\n AgentInputError,\n AgentValue[\"definition\"][\"input\"][\"DecodingServices\"]\n > =>\n Schema.decodeUnknownEffect(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({\n message: cause.message,\n }),\n ),\n ),\n);\n\nconst evaluateInstructions = Effect.fn(\"AgentRuntime.evaluateInstructions\")(\n <Input, Error, Services>(\n instructions: InstructionSource<Input, Error, Services>,\n input: Input,\n ): Effect.Effect<Prompt.RawInput, Error, Services> =>\n Effect.suspend(() => {\n const result = typeof instructions === \"function\" ? instructions(input) : instructions;\n\n return Effect.isEffect(result) ? result : Effect.succeed(result);\n }),\n);\n\nconst encodeInput = Effect.fn(\"AgentRuntime.encodeInput\")(\n <AgentValue extends Agent.Any>(\n agent: AgentValue,\n input: Agent.Input<AgentValue>,\n ): Effect.Effect<\n AgentValue[\"definition\"][\"input\"][\"Encoded\"],\n AgentInputError,\n AgentValue[\"definition\"][\"input\"][\"EncodingServices\"]\n > =>\n Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({\n message: `Unable to encode Agent input: ${cause.message}`,\n }),\n ),\n ),\n);\n\nconst renderInputPromptEffect = Effect.fn(\"AgentRuntime.renderInputPrompt\")(\n <Input, Error, Services>(\n inputPrompt: InputPromptSource<Input, Error, Services> | undefined,\n decodedInput: Input,\n encodedInput: unknown,\n ): Effect.Effect<Prompt.RawInput, Error | AgentInputError, Services> =>\n inputPrompt === undefined\n ? Effect.try({\n try: () => {\n const encoded = JSON.stringify(encodedInput);\n\n if (encoded === undefined) {\n throw new Error(\"Agent input cannot be represented as JSON\");\n }\n\n return encoded;\n },\n catch: (cause) =>\n AgentInputError.make({\n message: `Unable to materialize Agent input: ${errorMessage(cause)}`,\n }),\n })\n : Effect.suspend(() => {\n const result = inputPrompt(decodedInput);\n\n return Effect.isEffect(result) ? result : Effect.succeed(result);\n }),\n);\n\n/** Render decoded Agent input for model visibility, preserving the legacy JSON default. */\nexport function renderInputPrompt<\n Input,\n InputPromptValue extends InputPromptSource<NoInfer<Input>, unknown, unknown> | undefined,\n>(\n inputPrompt: InputPromptValue,\n decodedInput: Input,\n encodedInput: unknown,\n): Effect.Effect<\n Prompt.RawInput,\n AgentInputError | InputPromptErrorOf<InputPromptValue, Input>,\n InputPromptRequirementsOf<InputPromptValue, Input>\n>;\n\nexport function renderInputPrompt<Input>(\n inputPrompt: InputPromptSource<Input, unknown, unknown> | undefined,\n decodedInput: Input,\n encodedInput: unknown,\n): Effect.Effect<Prompt.RawInput, unknown, unknown> {\n return renderInputPromptEffect(inputPrompt, decodedInput, encodedInput);\n}\n\nconst makeInitialPrompt = Effect.fn(\"AgentRuntime.makeInitialPrompt\")(\n (\n instructions: Prompt.RawInput,\n inputPrompt: Prompt.RawInput,\n history: Prompt.Prompt,\n ): Effect.Effect<Prompt.Prompt, AgentInputError> =>\n Effect.try({\n try: () => {\n const instructionPrompt =\n typeof instructions === \"string\"\n ? Prompt.fromMessages([\n Prompt.makeMessage(\"system\", {\n content: instructions,\n }),\n ])\n : Prompt.make(instructions);\n\n return Prompt.fromMessages([\n ...history.content,\n ...instructionPrompt.content,\n ...Prompt.make(inputPrompt).content,\n ]);\n },\n catch: (cause) =>\n AgentInputError.make({\n message: `Unable to materialize Agent input: ${errorMessage(cause)}`,\n }),\n }),\n);\n\nconst decodeToolCallId = Effect.fn((id: string) =>\n Schema.decodeEffect(ToolCallId)(id).pipe(\n Effect.mapError((cause) =>\n ModelProtocolError.make({\n message: `Invalid Tool Call ID: ${cause.message}`,\n }),\n ),\n ),\n);\n\nconst decodeProviderToolCallId = Effect.fn((id: string) =>\n Schema.decodeEffect(ProviderToolCallId)(id).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({\n message:\n \"Model supplied an invalid Tool Call ID; expected 1-128 ASCII letters, digits, dots, underscores, colons, or hyphens\",\n }),\n ),\n ),\n);\n\nconst decodeProviderResponsePartId = Effect.fn((id: string) =>\n Schema.decodeEffect(ProviderResponsePartId)(id).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({\n message:\n \"Model supplied an invalid response part ID; expected 1-128 ASCII letters, digits, dots, underscores, colons, or hyphens\",\n }),\n ),\n ),\n);\n\nconst validateProviderPartIdentifiers = Effect.fnUntraced(function* (part: Response.AnyPart) {\n switch (part.type) {\n case \"text-start\":\n case \"text-delta\":\n case \"text-end\":\n case \"reasoning-start\":\n case \"reasoning-delta\":\n case \"reasoning-end\":\n case \"source\":\n yield* decodeProviderResponsePartId(part.id);\n\n return;\n case \"response-metadata\":\n if (part.id !== undefined) yield* decodeProviderResponsePartId(part.id);\n\n return;\n case \"tool-params-start\":\n case \"tool-params-delta\":\n case \"tool-params-end\":\n case \"tool-call\":\n case \"tool-result\":\n yield* decodeProviderToolCallId(part.id);\n\n return;\n case \"tool-approval-request\":\n yield* decodeProviderResponsePartId(part.approvalId);\n yield* decodeProviderToolCallId(part.toolCallId);\n\n return;\n case \"error\":\n case \"file\":\n case \"finish\":\n case \"reasoning\":\n case \"text\":\n return;\n }\n});\n\nconst responseIdentity = (part: Response.ResponseMetadataPart, previous?: ModelResponseIdentity) =>\n Schema.decodeEffect(ModelResponseIdentity)({\n ...previous,\n ...(part.id === undefined ? {} : { id: part.id }),\n ...(part.modelId === undefined ? {} : { model: part.modelId }),\n }).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({ message: \"Invalid provider response identity\" }),\n ),\n Effect.filterOrFail(\n () =>\n !(\n (previous?.id !== undefined && part.id !== undefined && previous.id !== part.id) ||\n (previous?.model !== undefined &&\n part.modelId !== undefined &&\n previous.model !== part.modelId)\n ),\n () =>\n ModelProtocolError.make({\n message: \"Provider response identity changed within one call\",\n }),\n ),\n );\n\nconst decodeEventJson = Effect.fn(\"AgentRuntime.decodeEventJson\")(\n (value: unknown, label: string): Effect.Effect<Schema.Json, ModelProtocolError> =>\n Schema.decodeUnknownEffect(Schema.Json)(value).pipe(\n Effect.mapError((cause) =>\n ModelProtocolError.make({\n message: `${label} is not JSON: ${cause.message}`,\n }),\n ),\n ),\n);\n\n/**\n * Preserves provider-executed results as assistant content while application\n * handler results remain Tool messages for the next model request.\n */\nconst promptFromTurnParts = (trace: TurnTrace): Prompt.Prompt => {\n if (trace.replayedResponse !== undefined) return trace.replayedResponse;\n\n const responsePrompt = Prompt.fromResponseParts(\n trace.parts.filter((part) => !(part.type === \"tool-result\" && part.providerExecuted)),\n );\n\n const providerResults = trace.parts.flatMap((part) =>\n part.type === \"tool-result\" && part.providerExecuted && !part.preliminary\n ? [\n Prompt.makePart(\"tool-result\", {\n id: part.id,\n name: part.name,\n isFailure: part.isFailure,\n result: part.encodedResult,\n providerExecuted: true,\n }),\n ]\n : [],\n );\n\n if (providerResults.length === 0) {\n return responsePrompt;\n }\n\n const messages: Array<Prompt.Message> = [];\n let attachedProviderResults = false;\n\n for (const message of responsePrompt.content) {\n if (message.role === \"assistant\") {\n messages.push(\n Prompt.makeMessage(\"assistant\", {\n content: [...message.content, ...providerResults],\n options: message.options,\n }),\n );\n attachedProviderResults = true;\n continue;\n }\n if (message.role === \"tool\") {\n // Application results are added by the engine after scheduling. Provider\n // results are retained as assistant content above, never as a tool turn.\n continue;\n }\n messages.push(message);\n }\n if (!attachedProviderResults) {\n messages.push(Prompt.makeMessage(\"assistant\", { content: providerResults }));\n }\n\n return Prompt.fromMessages(messages);\n};\n\n// `Effect.fnUntraced`: this dispatcher runs for every streamed Response Part,\n// so a named span here would emit one span per TextDelta/ReasoningDelta. The\n// enclosing model request keeps its `AgentRuntime.model` stream span.\nconst eventsForPart = Effect.fnUntraced(function* <Tools extends Record<string, Tool.Any>>(\n context: RunContext,\n turnId: TurnId,\n turn: number,\n tools: Tools,\n trace: TurnTrace,\n part: Response.AnyPart,\n retainedBytes: number,\n): Effect.fn.Return<\n ReadonlyArray<RunEvent>,\n ModelProtocolError,\n | Tool.HandlerServices<ToolUnion<Tools>>\n | Tool.ParametersSchema<ToolUnion<Tools>>[\"EncodingServices\"]\n> {\n yield* consumeModelResponsePart(trace, retainedBytes, context.bufferLimits);\n // Capture reported accounting before lifecycle validation can reject the response.\n if (part.type === \"finish\" && trace.usage === undefined) {\n trace.usage = part.usage;\n trace.finishMetadata = part.metadata;\n }\n if (trace.finished) {\n return yield* ModelProtocolError.make({\n message: \"Model response emitted content after its finish part\",\n });\n }\n // Provider/model identifiers are untrusted correlation keys. Reject them before they enter\n // the Turn trace, lifecycle maps, canonical event stream, diagnostics, or Tool scheduler.\n yield* validateProviderPartIdentifiers(part);\n if (part.type === \"response-metadata\")\n trace.response = yield* responseIdentity(part, trace.response);\n if (part.type !== \"tool-call\" && part.type !== \"tool-result\") trace.parts.push(part);\n switch (part.type) {\n case \"text-start\": {\n yield* startPart(trace.textParts, part.id, \"text\");\n\n return [];\n }\n case \"text-delta\": {\n yield* continuePart(trace.textParts, part.id, \"text delta\");\n trace.text.push(part.delta);\n\n return [\n TextDelta.make({\n ...(yield* eventBase(context)),\n turnId,\n text: part.delta,\n }),\n ];\n }\n case \"text-end\": {\n yield* endPart(trace.textParts, part.id, \"text\");\n\n return [];\n }\n case \"reasoning-start\": {\n yield* startPart(trace.reasoningParts, part.id, \"reasoning\");\n\n return [];\n }\n case \"reasoning-delta\": {\n yield* continuePart(trace.reasoningParts, part.id, \"reasoning delta\");\n\n return [\n ReasoningDelta.make({\n ...(yield* eventBase(context)),\n turnId,\n text: part.delta,\n }),\n ];\n }\n case \"reasoning-end\": {\n yield* endPart(trace.reasoningParts, part.id, \"reasoning\");\n\n return [];\n }\n case \"tool-params-start\": {\n if (trace.toolParameterParts.has(part.id)) {\n return yield* ModelProtocolError.make({\n message: `Model response repeated Tool parameter start for ${part.id}`,\n });\n }\n trace.toolParameterParts.set(part.id, {\n name: part.name,\n providerExecuted: part.providerExecuted,\n state: \"open\",\n });\n\n return [];\n }\n case \"tool-params-delta\": {\n const parameterPart = trace.toolParameterParts.get(part.id);\n\n if (parameterPart?.state !== \"open\") {\n return yield* ModelProtocolError.make({\n message: `Model response emitted Tool parameter delta for inactive part ${part.id}`,\n });\n }\n\n return [];\n }\n case \"tool-params-end\": {\n const parameterPart = trace.toolParameterParts.get(part.id);\n\n if (parameterPart?.state !== \"open\") {\n return yield* ModelProtocolError.make({\n message: `Model response emitted Tool parameter end for inactive part ${part.id}`,\n });\n }\n parameterPart.state = \"closed\";\n\n return [];\n }\n case \"tool-call\": {\n if (!hasTool(tools, part.name)) {\n return yield* ModelProtocolError.make({\n message: `Model requested unknown Tool ${part.name}`,\n });\n }\n if (trace.toolCalls.has(part.id)) {\n return yield* ModelProtocolError.make({\n message: `Model response repeated Tool Call ID ${part.id}`,\n });\n }\n const parameterPart = trace.toolParameterParts.get(part.id);\n\n if (parameterPart?.state === \"open\") {\n return yield* ModelProtocolError.make({\n message: `Model response declared Tool Call ${part.id} before its parameters completed`,\n });\n }\n if (\n parameterPart !== undefined &&\n (parameterPart.name !== part.name ||\n parameterPart.providerExecuted !== part.providerExecuted)\n ) {\n return yield* ModelProtocolError.make({\n message: `Completed Tool parameters did not match Tool Call ${part.id}`,\n });\n }\n const toolCallId = yield* decodeToolCallId(part.id);\n const tool = tools[part.name] as ToolUnion<Tools>;\n\n const decoded = yield* Effect.result(\n decodeToolCallParameters<Tools>(tool, part.name, part.params, \"model\"),\n );\n\n let parameters: Schema.Json;\n\n if (Result.isFailure(decoded)) {\n if (part.providerExecuted || tool.failureMode !== \"return\") return yield* decoded.failure;\n parameters = yield* decodeEventJson(part.params, \"Tool parameters\");\n\n // Approval needs decoded arguments, so validation precedes Toolkit.handle. Use\n // Effect's native error and codec; calling the handler to discover this failure\n // would cross the authorization boundary if a decoder changed its answer.\n const error = AiError.make({\n module: \"Toolkit\",\n method: `${part.name}.handle`,\n reason: new AiError.ToolParameterValidationError({\n toolName: part.name,\n description: decoded.failure.message,\n }),\n });\n\n const encodedError = yield* Schema.encodeEffect(Schema.toCodecJson(AiError.AiError))(\n error,\n ).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({ message: \"Unable to encode parameter rejection\" }),\n ),\n );\n\n const rejection = yield* Schema.decodeUnknownEffect(ToolParameterRejection)({\n toolCallId,\n parameters,\n error: encodedError,\n }).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({ message: \"Invalid parameter rejection evidence\" }),\n ),\n );\n\n trace.toolParameterRejections.set(part.id, rejection);\n } else {\n parameters = yield* encodeToolCallParameters<Tools>(tool, part.name, decoded.success).pipe(\n Effect.flatMap((encoded) => decodeEventJson(encoded, \"Tool parameters\")),\n );\n }\n\n const canonicalCall = Response.makePart(\"tool-call\", {\n id: part.id,\n name: part.name,\n params: parameters,\n providerExecuted: part.providerExecuted,\n metadata: part.metadata,\n });\n\n trace.parts.push(canonicalCall);\n trace.toolCalls.set(part.id, {\n name: part.name,\n providerExecuted: part.providerExecuted,\n });\n if (!part.providerExecuted) {\n trace.applicationToolCalls.push(canonicalCall);\n trace.applicationCallDescriptors.push({\n toolCallId,\n toolName: part.name,\n parameters,\n executionClass: getToolExecutionClass(tool),\n executionKind: getToolExecutionKind(tool.annotations),\n });\n }\n\n const declared = ToolCallDeclared.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: part.name,\n parameters,\n providerExecuted: part.providerExecuted,\n });\n\n return [declared];\n }\n case \"tool-result\": {\n const declaredCall = trace.toolCalls.get(part.id);\n\n if (declaredCall === undefined) {\n return yield* ModelProtocolError.make({\n message: `Model response returned an unrequested Tool result ${part.id}`,\n });\n }\n if (declaredCall.name !== part.name) {\n return yield* ModelProtocolError.make({\n message: `Tool result name did not match Tool Call ${part.id}: expected ${declaredCall.name}, received ${part.name}`,\n });\n }\n if (declaredCall.providerExecuted !== part.providerExecuted) {\n return yield* ModelProtocolError.make({\n message: `Tool result execution boundary did not match Tool Call ${part.id}`,\n });\n }\n if (!part.providerExecuted) {\n return yield* ModelProtocolError.make({\n message: `Model response included an application Tool result before engine execution for ${part.id}`,\n });\n }\n const toolCallId = yield* decodeToolCallId(part.id);\n const normalized = yield* snapshotProviderToolResultPart(trace, part);\n const result = normalized.result;\n\n if (part.preliminary === true) {\n yield* stageProviderResultPayload(trace, {\n _tag: \"ToolProgress\",\n toolCallId,\n toolName: part.name,\n result,\n providerExecuted: true,\n });\n trace.parts.push(\n Response.toolResultPart({\n id: part.id,\n name: part.name,\n isFailure: part.isFailure,\n result,\n encodedResult: result,\n providerExecuted: true,\n preliminary: true,\n metadata: normalized.metadata,\n }),\n );\n\n return [];\n }\n if (trace.finalToolResultIds.has(part.id)) {\n return yield* ModelProtocolError.make({\n message: `Tool Call ${part.id} produced more than one terminal result`,\n });\n }\n if (part.isFailure) {\n yield* stageProviderResultPayload(trace, {\n _tag: \"ToolCallFailed\",\n toolCallId,\n toolName: part.name,\n errorTag: errorTag(result),\n message: errorMessage(result),\n providerExecuted: true,\n });\n } else {\n yield* stageProviderResultPayload(trace, {\n _tag: \"ToolCallSucceeded\",\n toolCallId,\n toolName: part.name,\n result,\n providerExecuted: true,\n });\n }\n trace.finalToolResultIds.add(part.id);\n trace.parts.push(\n Response.toolResultPart({\n id: part.id,\n name: part.name,\n isFailure: part.isFailure,\n result,\n encodedResult: result,\n providerExecuted: true,\n preliminary: false,\n metadata: normalized.metadata,\n }),\n );\n\n return [];\n }\n case \"finish\": {\n const openPart = firstOpenPart(trace);\n\n if (openPart !== undefined) {\n return yield* ModelProtocolError.make({\n message: `Model response finished before completing ${openPart}`,\n });\n }\n trace.finished = true;\n trace.finishReason = part.reason;\n trace.usage = part.usage;\n if (Array.from(trace.toolCalls.values()).some(({ providerExecuted }) => providerExecuted)) {\n const turnCompletion = { finishReason: part.reason };\n\n const snapshot = yield* snapshotStagedProviderEvent(trace, {\n _tag: \"TurnCompleted\",\n ...turnCompletion,\n });\n\n trace.turnCompletion = turnCompletion;\n trace.providerStagedPayloadBytes += snapshot.bytes;\n\n return [];\n }\n\n return [\n TurnCompleted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n finishReason: part.reason,\n }),\n ];\n }\n case \"error\": {\n return yield* ModelProtocolError.make({\n message: `Model response failed: ${errorMessage(part.error)}`,\n });\n }\n case \"file\":\n case \"reasoning\":\n case \"response-metadata\":\n case \"source\":\n case \"text\":\n case \"tool-approval-request\": {\n return [];\n }\n }\n});\n\nconst decodeFinalOutput = Effect.fn(\"AgentRuntime.decodeFinalOutput\")(function* <\n AgentValue extends Agent.Any,\n>(\n agent: AgentValue,\n text: string,\n): Effect.fn.Return<\n { readonly encoded: Schema.Json; readonly decoded: Agent.Output<AgentValue> },\n AgentOutputError,\n Agent.OutputSchema<AgentValue>[\"DecodingServices\"]\n> {\n const eventJson = isTextOutput(agent.definition.output)\n ? text\n : yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(text).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: `Agent output is not valid JSON: ${cause.message}`,\n }),\n ),\n );\n\n const candidateOutput: unknown = eventJson;\n\n const decoded = yield* Schema.decodeUnknownEffect(agent.definition.output)(candidateOutput).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: cause.message,\n }),\n ),\n );\n\n return { encoded: eventJson, decoded };\n});\n\nconst encodeOutputCandidate = Effect.fn(\"AgentRuntime.encodeOutputCandidate\")(function* <\n AgentValue extends Agent.Any,\n>(agent: AgentValue, candidate: unknown) {\n const encoded = yield* Schema.encodeUnknownEffect(agent.definition.output)(candidate).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: `Completion Tool output failed Schema encoding: ${cause.message}`,\n }),\n ),\n );\n\n const decoded = yield* Schema.decodeUnknownEffect(agent.definition.output)(encoded).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: `Completion Tool output failed canonical decoding: ${cause.message}`,\n }),\n ),\n );\n\n const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: `Completion Tool output did not encode as durable JSON: ${cause.message}`,\n }),\n ),\n );\n\n return { encoded: json, decoded };\n});\n\nconst projectToolResult = Effect.fn(\"AgentRuntime.projectToolResult\")(function* <\n AgentValue extends Agent.Any,\n>(\n agent: AgentValue,\n declaration: CompletionToolDeclaration | CompletionFromToolDeclaration,\n parameters: unknown,\n result: unknown,\n): Effect.fn.Return<\n unknown,\n AgentOutputError | ModelProtocolError,\n AgentCompletionProjectionRequirements<AgentValue>\n> {\n const tool = agent.definition.toolkit.tools[declaration.tool];\n\n if (tool === undefined) {\n return yield* ModelProtocolError.make({\n message: `Agent completion declaration references unknown Tool ${declaration.tool}`,\n });\n }\n\n const decodedParameters = yield* Schema.decodeUnknownEffect(tool.parametersSchema)(\n parameters,\n ).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: `Completion Tool parameters failed canonical decoding: ${cause.message}`,\n }),\n ),\n );\n\n const decodedResult = yield* Schema.decodeUnknownEffect(tool.successSchema)(result).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: `Completion Tool result failed canonical decoding: ${cause.message}`,\n }),\n ),\n );\n\n const projected = yield* Effect.try({\n try: () => declaration.project({ parameters: decodedParameters, result: decodedResult }),\n catch: (cause) =>\n AgentOutputError.make({\n message: `Completion Tool projector failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n }),\n });\n\n return projected;\n});\n\nconst projectCompletionOutput = Effect.fn(\"AgentRuntime.projectCompletionOutput\")(function* <\n AgentValue extends Agent.Any,\n>(agent: AgentValue, declaration: CompletionToolDeclaration, parameters: unknown, result: unknown) {\n return yield* encodeOutputCandidate(\n agent,\n yield* projectToolResult(agent, declaration, parameters, result),\n );\n});\n\n/** Reconstruct optional action completion identically for live execution and canonical recovery. */\nconst projectCompletionFromToolOutput = Effect.fn(\"AgentRuntime.projectCompletionFromToolOutput\")(\n function* <AgentValue extends Agent.Any>(\n agent: AgentValue,\n declaration: CompletionFromToolDeclaration,\n parameters: unknown,\n result: unknown,\n ) {\n const projected = yield* projectToolResult(agent, declaration, parameters, result);\n\n if (!Option.isOption(projected)) {\n return yield* AgentOutputError.make({\n message: \"Action completion projector did not return an Option\",\n });\n }\n if (Option.isNone(projected)) return Option.none();\n\n return Option.some(yield* encodeOutputCandidate(agent, projected.value));\n },\n);\n\nconst encodeRunDispositionCandidate = Effect.fn(\"AgentRuntime.encodeRunDisposition\")(function* <\n Output,\n DispositionSchema extends Schema.Top,\n>(\n declaration: RunDispositionDeclaration<Output, DispositionSchema>,\n output: Output,\n): Effect.fn.Return<\n Schema.Json | undefined,\n AgentRunDispositionError,\n DispositionSchema[\"EncodingServices\"]\n> {\n const selected = yield* Effect.try({\n try: () => declaration.fromOutput(output),\n catch: (cause) =>\n AgentRunDispositionError.make({\n cause,\n message: \"Run disposition selector failed\",\n }),\n });\n\n if (selected === undefined) return undefined;\n\n const encoded = yield* Schema.encodeUnknownEffect(declaration.schema)(selected).pipe(\n Effect.mapError((cause) =>\n AgentRunDispositionError.make({\n cause,\n message: \"Run disposition failed Schema encoding\",\n }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError((cause) =>\n AgentRunDispositionError.make({\n cause,\n message: \"Run disposition did not encode as durable JSON\",\n }),\n ),\n );\n});\n\nfunction encodeRunDisposition<AgentValue extends Agent.Any>(\n agent: AgentValue,\n output: Agent.Output<AgentValue>,\n): Effect.Effect<\n Schema.Json | undefined,\n Agent.RunDispositionFailure<AgentValue>,\n Agent.RunDispositionSchema<AgentValue>[\"EncodingServices\"]\n>;\nfunction encodeRunDisposition<Output, DispositionSchema extends Schema.Top>(\n agent: {\n readonly definition: {\n readonly runDisposition?: RunDispositionDeclaration<Output, DispositionSchema> | undefined;\n };\n },\n output: Output,\n): Effect.Effect<\n Schema.Json | void,\n AgentRunDispositionError,\n DispositionSchema[\"EncodingServices\"]\n> {\n const declaration = agent.definition.runDisposition;\n\n return declaration === undefined\n ? Effect.void\n : encodeRunDispositionCandidate(declaration, output);\n}\n\nconst decodeRunDispositionCandidate = Effect.fn(\"AgentRuntime.decodeRunDisposition\")(function* <\n Output,\n DispositionSchema extends Schema.Top,\n>(\n declaration: RunDispositionDeclaration<Output, DispositionSchema>,\n encoded: Schema.Json,\n): Effect.fn.Return<\n DispositionSchema[\"Type\"],\n AgentRunDispositionError,\n DispositionSchema[\"DecodingServices\"]\n> {\n return yield* Schema.decodeEffect(declaration.schema)(encoded).pipe(\n Effect.mapError((cause) =>\n AgentRunDispositionError.make({\n cause,\n message: cause.message,\n }),\n ),\n );\n});\n\nfunction decodeRunDisposition<AgentValue extends Agent.Any>(\n agent: AgentValue,\n encoded: Schema.Json,\n): Effect.Effect<\n Agent.RunDisposition<AgentValue>,\n Agent.RunDispositionFailure<AgentValue> | ModelProtocolError,\n Agent.RunDispositionSchema<AgentValue>[\"DecodingServices\"]\n>;\nfunction decodeRunDisposition<DispositionSchema extends Schema.Top>(\n agent: {\n readonly definition: {\n readonly runDisposition?: RunDispositionDeclaration<never, DispositionSchema> | undefined;\n };\n },\n encoded: Schema.Json,\n): Effect.Effect<\n DispositionSchema[\"Type\"],\n AgentRunDispositionError | ModelProtocolError,\n DispositionSchema[\"DecodingServices\"]\n> {\n const declaration = agent.definition.runDisposition;\n\n return declaration === undefined\n ? Effect.fail(\n ModelProtocolError.make({\n message: \"RunCompleted declared a run disposition without a definition-owned Schema\",\n }),\n )\n : decodeRunDispositionCandidate(declaration, encoded);\n}\n\n/** Internal control output consumed by the driver before RunEvent publication. */\ninterface NextTurn {\n readonly _tag: \"NextTurn\";\n readonly prompt: Prompt.Prompt;\n readonly turn: number;\n readonly toolCalls: number;\n}\n\ntype TurnOutput = RunEvent | NextTurn;\n\nconst nextTurn = (\n prompt: Prompt.Prompt,\n turn: number,\n toolCalls: number,\n): Stream.Stream<TurnOutput> => Stream.succeed({ _tag: \"NextTurn\", prompt, turn, toolCalls });\n\nconst makeTurn = <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n HookError,\n HookRequirements,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 agent: RuntimeProgram<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n context: RunContext,\n prompt: Prompt.Prompt,\n turn: number,\n priorToolCalls: number,\n options: RunOptions<HookError, HookRequirements>,\n): Stream.Stream<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const policy = agent.definition.policy;\n const bounds = effectiveRunBounds(policy, options);\n\n if (options.beforeTurn !== undefined) yield* options.beforeTurn();\n const now = yield* Clock.currentTimeMillis;\n\n if (now >= context.durationDeadlineMillis) {\n return failRunEventStream(durationLimitError(agent.definition.policy));\n }\n // Fail-mode work never starts beyond the Turn ceiling. Most Tool paths\n // reject at declaration admission; this preflight also covers a\n // final-Turn completion Tool whose canonical returned result is a\n // failure and therefore needs another model Turn.\n if (policy.onExhaustion === \"fail\" && turn > bounds.maxTurns) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"turns\",\n message: `Agent exceeded its ${bounds.maxTurns} Turn limit`,\n }),\n );\n }\n if (context.finalizationUsed) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit:\n turn > bounds.maxTurns\n ? \"turns\"\n : priorToolCalls + context.programmaticToolCalls > bounds.maxToolCalls\n ? \"tool-calls\"\n : \"tokens\",\n message: \"Agent already used its one grace finalization\",\n }),\n );\n }\n const ids = yield* IdGenerator;\n const turnId = yield* ids.nextTurnId;\n // Model-visible final-output contract (RUN-028):\n // derived before context preparation so a limit-targeting adapter can\n // reserve the contract's overhead in its window calculation, applied to\n // the request after preparation so compaction cannot drop it, and never\n // entered into official history, so canonical records are unchanged.\n // An unrenderable output Schema falls back to the prior behavior with\n // one Turn-1 diagnostic.\n const outputContract = outputSchemaContract(agent.definition);\n\n const outputContractMessage =\n outputContract._tag === \"rendered\" ? outputContract.message : undefined;\n\n const contextRequest = {\n threadId: context.threadId,\n runId: context.runId,\n turnId,\n turn,\n source: prompt,\n // Omit the key entirely when no contract renders so hooks keep the\n // same exact request shape as the preparation hook.\n ...(outputContractMessage === undefined ? {} : { outputContract: outputContractMessage }),\n };\n\n const modelContext: PreparedRunContext =\n options.context === undefined ? { prompt } : yield* options.context.prepare(contextRequest);\n\n const callContext =\n modelContext.modelCall === undefined\n ? undefined\n : yield* Schema.decodeEffect(ModelCallContext)(modelContext.modelCall.context).pipe(\n Effect.mapError((cause) =>\n CompactionError.make({ message: \"Invalid resolved model context bounds\", cause }),\n ),\n );\n\n const contextTokenLimit =\n callContext === undefined\n ? policy.contextTokenLimit\n : Math.max(\n 0,\n Math.min(\n policy.contextTokenLimit ?? Infinity,\n callContext.maxInputTokens ?? Infinity,\n callContext.contextCapacity - callContext.outputReserveTokens,\n ) - callContext.uncountedOverheadTokens,\n );\n\n context.windowContextTokenLimit = contextTokenLimit;\n const toolSchemaTransformer = modelContext.modelCall?.toolSchemaTransformer;\n const messageTokenEstimator = modelContext.modelCall?.estimateMessageTokens;\n const visibility = yield* RunToolVisibility;\n\n const catalog = yield* eligibleCatalog(\n agent.definition,\n { threadId: context.threadId, runId: context.runId, turn, input: context.input },\n options.subagentGrant,\n options.delegationDepth ?? options.parentLink?.depth ?? 0,\n );\n\n if (modelContext.toolSelection !== undefined)\n context.toolSelection = yield* validateSelection(\n modelContext.toolSelection,\n agent.definition,\n catalog,\n );\n\n let snapshot =\n agent.definition.toolExposure === undefined &&\n context.toolSelection === undefined &&\n visibility === undefined\n ? undefined\n : yield* exposureSnapshot(\n agent.definition,\n context.toolSelection,\n catalog,\n toolSchemaTransformer,\n );\n\n const selectionSnapshot = snapshot;\n\n context.toolSchemaTransformer = toolSchemaTransformer;\n context.toolCatalog = catalog;\n context.toolExposure = snapshot;\n\n const modelToolkit = Toolkit.make(\n ...(snapshot === undefined\n ? catalog.filter((entry) => entry.kind === \"native\").map((entry) => entry.tool)\n : catalog\n .filter(\n (entry) =>\n entry.kind === \"native\" &&\n snapshot?.exposedToolNames.includes(entry.nativeToolName),\n )\n .map((entry) => entry.tool)),\n ) as unknown as Toolkit.Toolkit<Tools>;\n\n if (options.durability !== undefined && snapshot !== undefined) {\n if (\n options.durability.noteToolExposure === undefined &&\n context.toolSelection !== undefined\n )\n return yield* ModelProtocolError.make({\n message: \"Durable Tool exposure requires a request snapshot staging hook\",\n });\n }\n\n const estimateCallTokens = (messages: ReadonlyArray<Prompt.Message>) =>\n estimateContextTokens(messages, messageTokenEstimator);\n\n const modelServices =\n modelContext.modelCall === undefined\n ? undefined\n : yield* Layer.build(Layer.fresh(modelContext.modelCall.model));\n\n const withCallModel = <A, E, R>(operation: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n modelServices === undefined ? operation : Effect.provide(operation, modelServices);\n\n const priorCompactionPrefix = context.preparedCompactionSource?.prefix;\n\n if (priorCompactionPrefix !== undefined && priorCompactionPrefix.length > 0) {\n const preparedPrefix = yield* snapshotCompactionMessages(\n modelContext.prompt.content.slice(0, priorCompactionPrefix.length),\n );\n\n if (!Equal.equals(preparedPrefix, priorCompactionPrefix)) {\n return yield* CompactionError.make({\n message: \"Prepared context changed a prefix already covered by compaction\",\n });\n }\n }\n\n const trace: TurnTrace = {\n responsePartCount: 0,\n responsePartBytes: 0,\n parts: [],\n text: [],\n textParts: new Map(),\n reasoningParts: new Map(),\n toolParameterParts: new Map(),\n toolCalls: new Map(),\n finalToolResultIds: new Set(),\n providerResultPayloads: [],\n providerStagedPayloadBytes: 0,\n turnCompletion: undefined,\n applicationToolCalls: [],\n toolParameterRejections: new Map(),\n applicationCallDescriptors: [],\n applicationToolResults: [],\n finished: false,\n finishReason: undefined,\n usage: undefined,\n };\n\n const started = Stream.fromEffect(\n Effect.gen(function* () {\n yield* Metric.update(modelCounter, 1);\n yield* Effect.logDebug(\"agent model call started\").pipe(\n Effect.annotateLogs({\n agentId: context.agentId,\n runId: context.runId,\n turnId,\n }),\n );\n\n return [\n TurnStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n }),\n ModelStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n }),\n ] satisfies ReadonlyArray<RunEvent>;\n }).pipe(Effect.withLogSpan(\"AgentRuntime.model\")),\n ).pipe(Stream.flatMap(Stream.fromIterable));\n\n // Final-answer mode (RUN-018/RUN-019, extended to tokens by RUN-025):\n // once the Turn, Tool Call, or token budget is\n // exhausted, the model keeps its toolkit declaration but may not call\n // it. Turn and Tool Call conditions are pure derivations of committed\n // state (`turn`, `priorToolCalls`, `programmaticToolCalls`); the token\n // condition is the one-shot `tokenExhausted` flag consumeUsage stamps\n // when the cumulative budget breaches under `\"final-answer\"` (durable\n // resume re-seeds the counters, so the derivation survives ownership\n // changes). Strict `>` keeps an exact-cap Run on today's unconstrained\n // path byte-for-byte.\n let finalAnswerOnly =\n policy.onExhaustion !== \"fail\" &&\n (turn > bounds.maxTurns ||\n priorToolCalls + context.programmaticToolCalls > bounds.maxToolCalls ||\n context.tokenExhausted);\n\n const modelToolChoice = (): LanguageModel.ToolChoice<string> | undefined => {\n const terminalToolChoiceOnly =\n finalAnswerOnly ||\n (agent.definition.completion?.required === true &&\n policy.onExhaustion === \"fail\" &&\n turn === bounds.maxTurns);\n\n return terminalToolChoiceOnly\n ? agent.definition.completion === undefined ||\n (agent.definition.completion.required !== true &&\n !catalog.some(\n (entry) =>\n entry.kind === \"native\" &&\n entry.nativeToolName === agent.definition.completion?.tool,\n ))\n ? \"none\"\n : agent.definition.completion.required === true\n ? { tool: agent.definition.completion.tool }\n : { mode: \"auto\", oneOf: [agent.definition.completion.tool] }\n : agent.definition.completion?.required === true\n ? \"required\"\n : undefined;\n };\n\n if (finalAnswerOnly && context.exhaustedDimension === undefined) {\n // First-cause dimension marker (the RUN-021 grant-flow marker).\n context.exhaustedDimension =\n turn > bounds.maxTurns\n ? \"turns\"\n : priorToolCalls + context.programmaticToolCalls > bounds.maxToolCalls\n ? \"tool-calls\"\n : \"tokens\";\n }\n if (outputContract._tag === \"unrenderable\" && turn === 1) {\n yield* Effect.logWarning(\n \"Agent output schema cannot render to JSON Schema; the model-visible final output contract is omitted\",\n ).pipe(\n Effect.annotateLogs({\n agentId: context.agentId,\n runId: context.runId,\n reason: outputContract.reason,\n }),\n );\n }\n\n // The output contract (RUN-028) rides every outgoing request after\n // compaction, so the view must fit the limit with the contract the\n // engine will append.\n const admissionRequired =\n contextTokenLimit !== undefined ||\n (!context.finalizing && !finalAnswerOnly && policy.tokenBudget !== undefined);\n\n const outputContractTokens =\n !admissionRequired || outputContractMessage === undefined\n ? 0\n : yield* estimateCallTokens([\n Prompt.makeMessage(\"system\", { content: outputContractMessage }),\n ]);\n\n const canonicalDecoration = !admissionRequired\n ? Prompt.empty\n : yield* outgoingModelPrompt(policy, context, Prompt.empty, turn, priorToolCalls);\n\n const estimateToolSchemaTokens = Effect.suspend(() => {\n const choice = modelToolChoice();\n\n const tools =\n typeof choice === \"object\" && \"oneOf\" in choice\n ? catalog\n .filter(\n (entry) => entry.kind === \"native\" && choice.oneOf.includes(entry.nativeToolName),\n )\n .map((entry) => entry.tool)\n : Object.values(modelToolkit.tools);\n\n return callContext === undefined || tools.length === 0\n ? Effect.succeed(0)\n : Effect.try({\n try: () =>\n JSON.stringify(\n tools.map((tool) =>\n Tool.isProviderDefined(tool)\n ? { type: tool.providerName, args: tool.args }\n : {\n name: tool.name,\n description: Tool.getDescription(tool),\n // Providers receive the original Tool; pre-encoding its schema can\n // discard definitions and annotations their transformer preserves.\n parameters: Tool.getJsonSchema(tool, {\n transformer: toolSchemaTransformer,\n }),\n },\n ),\n ),\n catch: (cause) =>\n CompactionError.make({\n message: \"Could not estimate native Tool schemas\",\n cause,\n }),\n }).pipe(\n Effect.flatMap((content) =>\n estimateCallTokens([Prompt.makeMessage(\"system\", { content })]),\n ),\n );\n });\n\n let toolSchemaTokens = yield* estimateToolSchemaTokens;\n\n const canonicalDecorationPromptTokens = !admissionRequired\n ? 0\n : outputContractTokens + (yield* estimateCallTokens(canonicalDecoration.content));\n\n const canonicalDecorationTokens = () => toolSchemaTokens + canonicalDecorationPromptTokens;\n\n // Preparation may replace an existing prefix, and transient context may\n // change independently of history. Only ordinary append-only history can\n // reuse the last provider-reported input as an estimation anchor.\n const estimateSourceContext = (view: ReadonlyArray<Prompt.Message>) =>\n options.context === undefined && options.transientContext === undefined\n ? nextContextEstimate(context, view)\n : estimateCallTokens(view);\n\n let prepared = buildCompactedView(modelContext.prompt.content, context.compaction);\n let sourceTokens: number | undefined;\n\n const preparedSourceTokens = Effect.suspend(() =>\n sourceTokens === undefined\n ? estimateSourceContext(prepared).pipe(\n Effect.tap((tokens) =>\n Effect.sync(() => {\n sourceTokens = tokens;\n }),\n ),\n )\n : Effect.succeed(sourceTokens),\n );\n\n const refreshPrepared = () => {\n prepared = buildCompactedView(modelContext.prompt.content, context.compaction);\n sourceTokens = undefined;\n };\n\n let preEvents: ReadonlyArray<RunEvent> = [];\n\n if (modelContext.rollover !== undefined) {\n if (context.pendingContextToolCallId !== undefined) {\n return yield* CompactionError.make({\n message: \"Host and Tool rollover requests cannot share a Turn\",\n });\n }\n\n const requested = yield* Schema.decodeEffect(ContextRolloverSelection)(\n modelContext.rollover,\n ).pipe(\n Effect.mapError((cause) =>\n CompactionError.make({ message: \"Invalid host context rollover\", cause }),\n ),\n );\n\n const outcome = yield* compactContext(\n agent,\n context,\n modelContext.prompt,\n turn,\n options,\n callContext === undefined ? undefined : contextTokenLimit,\n messageTokenEstimator,\n contextTokenLimit === undefined\n ? undefined\n : Math.max(0, contextTokenLimit - canonicalDecorationTokens()),\n \"requested\",\n false,\n requested,\n ).pipe(withCallModel);\n\n if (outcome.events.some((event) => event._tag === \"CompactionPerformed\"))\n context.compaction.lastCompactionTurn = turn;\n preEvents = outcome.events;\n refreshPrepared();\n }\n\n const lastToolIndex =\n context.pendingContextToolCallId === undefined\n ? -1\n : modelContext.prompt.content.findLastIndex(\n (message) =>\n message.role === \"tool\" &&\n message.content.some(\n (part) =>\n part.type === \"tool-result\" && part.id === context.pendingContextToolCallId,\n ),\n );\n\n if (context.pendingContextToolCallId !== undefined && lastToolIndex < 0) {\n return yield* CompactionError.make({\n message: \"Prepared context omitted the pending context Tool result\",\n });\n }\n const lastTool = modelContext.prompt.content[lastToolIndex];\n\n if (\n context.pendingContextToolCallId !== undefined &&\n (lastTool?.role !== \"tool\" || lastTool.content.length !== 1)\n ) {\n return yield* CompactionError.make({\n message: \"Prepared context changed the pending context Tool batch\",\n });\n }\n if (lastTool?.role === \"tool\" && lastTool.content.length === 1) {\n const result = lastTool.content[0];\n\n if (\n result?.type === \"tool-result\" &&\n !result.isFailure &&\n result.providerExecuted !== true &&\n result.id === context.pendingContextToolCallId &&\n hasTool(agent.definition.toolkit.tools, result.name) &&\n Context.get(agent.definition.toolkit.tools[result.name].annotations, ContextRolloverTool)\n ) {\n const request = yield* Schema.decodeUnknownEffect(ContextRolloverRequest, {\n onExcessProperty: \"error\",\n })(result.result).pipe(\n Effect.mapError((cause) =>\n CompactionError.make({ message: \"Invalid context rollover Tool result\", cause }),\n ),\n );\n\n const outcome = yield* compactContext(\n agent,\n context,\n modelContext.prompt,\n turn,\n options,\n callContext === undefined ? undefined : contextTokenLimit,\n messageTokenEstimator,\n contextTokenLimit === undefined\n ? undefined\n : Math.max(0, contextTokenLimit - canonicalDecorationTokens()),\n \"requested\",\n false,\n { ...request, through: lastToolIndex + 1 },\n ).pipe(withCallModel);\n\n context.compaction.lastCompactionTurn = turn;\n preEvents = outcome.events;\n refreshPrepared();\n }\n }\n\n context.pendingContextToolCallId = undefined;\n if (!context.finalizing && admissionRequired) {\n const consumedTokens = context.inputTokens + context.outputTokens;\n\n const tokenCallTarget =\n policy.tokenBudget === undefined || finalAnswerOnly\n ? undefined\n : Math.max(0, policy.tokenBudget - consumedTokens - policy.completionReserveTokens);\n\n const contextCallTarget = contextTokenLimit;\n\n const fullTarget =\n tokenCallTarget === undefined\n ? contextCallTarget\n : contextCallTarget === undefined\n ? tokenCallTarget\n : Math.min(tokenCallTarget, contextCallTarget);\n\n const sourceTarget =\n fullTarget === undefined\n ? undefined\n : Math.max(0, fullTarget - canonicalDecorationTokens());\n\n const estimate = (yield* preparedSourceTokens) + canonicalDecorationTokens();\n const contextPressure = contextCallTarget !== undefined && estimate > contextCallTarget;\n const tokenPressure = tokenCallTarget !== undefined && estimate > tokenCallTarget;\n\n if (\n (contextPressure || tokenPressure) &&\n sourceTarget !== undefined &&\n sourceTarget > 0 &&\n context.compaction.lastCompactionTurn !== turn\n ) {\n // Loop guard: at most one threshold compaction per Turn. The target\n // is checked below before provider I/O, so a non-progressing pass\n // fails typed rather than relying on a provider rejection.\n context.compaction.lastCompactionTurn = turn;\n\n const outcome = yield* compactContext(\n agent,\n context,\n modelContext.prompt,\n turn,\n options,\n callContext === undefined ? undefined : contextTokenLimit,\n messageTokenEstimator,\n sourceTarget,\n \"pressure\",\n !tokenPressure,\n ).pipe(withCallModel);\n\n preEvents = [...preEvents, ...outcome.events];\n if (outcome.events.some((event) => event._tag === \"CompactionPerformed\"))\n refreshPrepared();\n }\n\n // A summarizing compaction is itself a priced model call. Recompute\n // admission from its reported usage instead of carrying the stale\n // pre-compaction balance into the research call that follows.\n if (context.tokenExhausted) {\n finalAnswerOnly = true;\n toolSchemaTokens = yield* estimateToolSchemaTokens;\n }\n\n const preparedTokenCallTarget =\n policy.tokenBudget === undefined || finalAnswerOnly\n ? undefined\n : Math.max(\n 0,\n policy.tokenBudget -\n (context.inputTokens + context.outputTokens) -\n policy.completionReserveTokens,\n );\n\n let preparedEstimate = (yield* preparedSourceTokens) + canonicalDecorationTokens();\n\n if (\n (callContext !== undefined ||\n contextCallTarget === undefined ||\n preparedEstimate <= contextCallTarget) &&\n preparedTokenCallTarget !== undefined &&\n preparedEstimate > preparedTokenCallTarget\n ) {\n const error = AgentPolicyError.make({\n limit: \"tokens\",\n message: `The next research call would consume this Run's ${policy.completionReserveTokens} token completion reserve`,\n });\n\n if (policy.onExhaustion === \"fail\") {\n return yield* error;\n }\n context.tokenExhausted = true;\n context.exhaustedDimension ??= \"tokens\";\n finalAnswerOnly = true;\n toolSchemaTokens = yield* estimateToolSchemaTokens;\n preparedEstimate = (yield* preparedSourceTokens) + canonicalDecorationTokens();\n }\n if (contextCallTarget !== undefined && preparedEstimate > contextCallTarget) {\n return yield* ContextBudgetError.make({\n message: `Compaction could not fit the next model prompt inside the ${contextCallTarget} token context target`,\n estimatedTokens: preparedEstimate,\n targetTokens: contextCallTarget,\n completionReserveTokens: policy.completionReserveTokens,\n });\n }\n }\n\n const transientContext =\n options.transientContext === undefined\n ? Prompt.empty\n : yield* options.transientContext\n .load(contextRequest)\n .pipe(Effect.flatMap(transientInputToPrompt));\n\n const derivedPrompt =\n options.transientContext === undefined\n ? canonicalDecoration\n : yield* outgoingModelPrompt(policy, context, transientContext, turn, priorToolCalls);\n\n const derivedPromptContentTokens = !admissionRequired\n ? 0\n : options.transientContext === undefined\n ? canonicalDecorationPromptTokens\n : outputContractTokens + (yield* estimateCallTokens(derivedPrompt.content));\n\n const derivedPromptTokens = () => toolSchemaTokens + derivedPromptContentTokens;\n\n if (!context.finalizing && admissionRequired && options.transientContext !== undefined) {\n const tokenCallTarget =\n policy.tokenBudget === undefined || finalAnswerOnly\n ? undefined\n : Math.max(\n 0,\n policy.tokenBudget -\n (context.inputTokens + context.outputTokens) -\n policy.completionReserveTokens,\n );\n\n const fullTarget =\n tokenCallTarget === undefined\n ? contextTokenLimit\n : contextTokenLimit === undefined\n ? tokenCallTarget\n : Math.min(tokenCallTarget, contextTokenLimit);\n\n const sourceTarget =\n fullTarget === undefined ? undefined : Math.max(0, fullTarget - derivedPromptTokens());\n\n let preparedEstimate = (yield* preparedSourceTokens) + derivedPromptTokens();\n\n const contextPressure =\n contextTokenLimit !== undefined && preparedEstimate > contextTokenLimit;\n\n const tokenPressure = tokenCallTarget !== undefined && preparedEstimate > tokenCallTarget;\n const currentCompactionAllowance = context.compactionTurn.turn === turn;\n\n const summarizedThisTurn =\n currentCompactionAllowance &&\n (context.compactionTurn.applied.has(\"summarize\") ||\n context.compactionTurn.applied.has(\"rollover\"));\n\n const prunedThisTurn =\n currentCompactionAllowance && context.compactionTurn.applied.has(\"clear-tool-results\");\n\n const canCompact =\n !summarizedThisTurn &&\n (!prunedThisTurn || (!tokenPressure && policy.compaction.mode !== \"prune\"));\n\n if (\n (contextPressure || tokenPressure) &&\n sourceTarget !== undefined &&\n sourceTarget > 0 &&\n canCompact\n ) {\n context.compaction.lastCompactionTurn = turn;\n\n const outcome = yield* compactContext(\n agent,\n context,\n modelContext.prompt,\n turn,\n options,\n callContext === undefined ? undefined : contextTokenLimit,\n messageTokenEstimator,\n sourceTarget,\n \"pressure\",\n !tokenPressure,\n ).pipe(withCallModel);\n\n preEvents = [...preEvents, ...outcome.events];\n if (outcome.events.some((event) => event._tag === \"CompactionPerformed\"))\n refreshPrepared();\n preparedEstimate = (yield* preparedSourceTokens) + derivedPromptTokens();\n }\n if (context.tokenExhausted) {\n finalAnswerOnly = true;\n toolSchemaTokens = yield* estimateToolSchemaTokens;\n }\n\n const preparedTokenCallTarget =\n policy.tokenBudget === undefined || finalAnswerOnly\n ? undefined\n : Math.max(\n 0,\n policy.tokenBudget -\n (context.inputTokens + context.outputTokens) -\n policy.completionReserveTokens,\n );\n\n if (\n (callContext !== undefined ||\n contextTokenLimit === undefined ||\n preparedEstimate <= contextTokenLimit) &&\n preparedTokenCallTarget !== undefined &&\n preparedEstimate > preparedTokenCallTarget\n ) {\n const error = AgentPolicyError.make({\n limit: \"tokens\",\n message: `The next research call would consume this Run's ${policy.completionReserveTokens} token completion reserve`,\n });\n\n if (policy.onExhaustion === \"fail\") {\n return yield* error;\n }\n context.tokenExhausted = true;\n context.exhaustedDimension ??= \"tokens\";\n finalAnswerOnly = true;\n toolSchemaTokens = yield* estimateToolSchemaTokens;\n }\n preparedEstimate = (yield* preparedSourceTokens) + derivedPromptTokens();\n if (contextTokenLimit !== undefined && preparedEstimate > contextTokenLimit) {\n return yield* ContextBudgetError.make({\n message: `Transient context could not fit the next model prompt inside the ${contextTokenLimit} token context target`,\n estimatedTokens: preparedEstimate,\n targetTokens: contextTokenLimit,\n completionReserveTokens: policy.completionReserveTokens,\n });\n }\n }\n if (finalAnswerOnly) {\n yield* context.policyReservations.withPermit(\n Effect.gen(function* () {\n context.finalizationUsed = true;\n if (options.durability?.reservePolicyUsage !== undefined) {\n yield* options.durability.reservePolicyUsage({\n programmaticToolCalls: context.programmaticToolCalls,\n finalizationUsed: true,\n });\n }\n }),\n );\n }\n\n /** The model-visible view of the Turn basis under current compaction state. */\n const compactedOutgoing = (): Prompt.Prompt => {\n context.compaction.lastViewLength = prepared.length;\n\n return Prompt.fromMessages(prepared);\n };\n\n const consumeTurnUsage = (toolCallCount: number) =>\n Effect.suspend(() => {\n trace.usageConsumed = true;\n const priorModelCalls = context.modelCalls;\n\n return consumeUsage(agent, context, trace.usage, toolCallCount, turn, options, {\n response: trace.response,\n finishMetadata: trace.finishMetadata,\n purpose: \"turn\",\n }).pipe(\n withCallModel,\n Effect.tapCause(() =>\n context.modelCalls === priorModelCalls\n ? noteIncompleteUsage(context, turn)\n : Effect.void,\n ),\n );\n });\n\n // Failure accounting observes the already-selected failure; a secondary\n // budget/estimator failure must not replace that native outcome.\n const retainFailedUsage = Effect.fn(\"AgentRuntime.retainFailedUsage\")(function* () {\n if (trace.usageConsumed) return;\n trace.usageConsumed = true;\n if (trace.usage === undefined) {\n return yield* noteIncompleteUsage(context, turn);\n }\n yield* consumeTurnUsage(0).pipe(Effect.exit);\n });\n\n const attempt = (basis: Prompt.Prompt) =>\n Stream.unwrap(\n outgoingModelPrompt(\n policy,\n context,\n Prompt.fromMessages([...basis.content, ...transientContext.content]),\n turn,\n priorToolCalls,\n ).pipe(\n Effect.flatMap((outgoing) =>\n Effect.gen(function* () {\n const toolChoice = modelToolChoice();\n\n let requestToolkit = modelToolkit;\n\n snapshot = selectionSnapshot;\n if (\n selectionSnapshot !== undefined &&\n typeof toolChoice === \"object\" &&\n \"oneOf\" in toolChoice\n ) {\n const finalSelection = yield* validateSelection(\n { toolNames: toolChoice.oneOf },\n agent.definition,\n catalog,\n );\n\n const selected = yield* exposureSnapshot(\n agent.definition,\n finalSelection,\n catalog,\n toolSchemaTransformer,\n toolChoice.oneOf,\n );\n\n requestToolkit = Toolkit.make(\n ...catalog\n .filter(\n (entry) =>\n entry.kind === \"native\" &&\n selected.exposedToolNames.includes(entry.nativeToolName),\n )\n .map((entry) => entry.tool),\n ) as unknown as Toolkit.Toolkit<Tools>;\n snapshot = Object.freeze(\n Snapshot.make({\n ...selectionSnapshot,\n exposedToolNames: selected.exposedToolNames,\n }),\n );\n }\n context.toolExposure = snapshot;\n\n const providerPrompt =\n outputContract._tag !== \"rendered\"\n ? outgoing\n : insertOutputContract(outgoing, outputContract.part);\n\n // Prepared and transient context can change at every Turn. A\n // final full-prompt check closes the per-call boundary for grace\n // finalization and any future path that bypasses research\n // compaction admission. Runs without either hook keep their\n // provider-reported incremental estimate.\n\n return yield* estimateCallTokens(providerPrompt.content).pipe(\n Effect.map((tokens) => tokens + toolSchemaTokens),\n Effect.tap((estimatedTokens) =>\n contextTokenLimit !== undefined &&\n (options.context !== undefined || options.transientContext !== undefined) &&\n estimatedTokens > contextTokenLimit\n ? ContextBudgetError.make({\n message: `Prepared context could not fit the next model prompt inside the ${contextTokenLimit} token context target`,\n estimatedTokens,\n targetTokens: contextTokenLimit,\n completionReserveTokens: policy.completionReserveTokens,\n })\n : Effect.void,\n ),\n Effect.tap((tokens) =>\n Effect.sync(() => {\n context.windowTokens = tokens;\n }),\n ),\n Effect.tap(() =>\n snapshot === undefined || options.durability?.noteToolExposure === undefined\n ? Effect.void\n : options.durability.noteToolExposure(turn, snapshot),\n ),\n Effect.as(\n guardBudgetStream(\n LanguageModel.streamText({\n // The contract joins the final outgoing prompt (after\n // compaction and the run-status append), so every attempt —\n // including the overflow retry — carries it at the last\n // system block.\n prompt: providerPrompt,\n toolkit: deferredToolParameterToolkit(requestToolkit),\n disableToolCallResolution: true,\n // Exact required Tool selection preserves the toolkit. A oneOf\n // subset can drop other schemas and break the cached prefix.\n ...(toolChoice === undefined ? {} : { toolChoice }),\n }),\n options.budget,\n ).pipe(\n Stream.provideServiceEffect(\n Tracer.Tracer,\n modelTelemetryTracer(context, turnId),\n ),\n Stream.onStart(\n Effect.sync(() => {\n trace.usageConsumed = false;\n }),\n ),\n Stream.mapEffect((part) =>\n ownModelResponsePart(\n part,\n agent.definition.toolkit,\n trace,\n context.bufferLimits,\n ).pipe(\n Effect.flatMap((owned) =>\n eventsForPart(\n context,\n turnId,\n turn,\n agent.definition.toolkit.tools,\n trace,\n owned.ownedPart,\n owned.retainedBytes,\n ),\n ),\n ),\n ),\n Stream.flatMap(Stream.fromIterable),\n Stream.tapCause(() => retainFailedUsage()),\n ),\n ),\n );\n }),\n ),\n ),\n );\n\n // RUN-027: one summarize-and-retry for a classified provider context\n // overflow when compaction is configured; every other provider error\n // propagates unchanged. A response that already streamed parts mutated\n // the trace, so it is never retried.\n const response = attempt(compactedOutgoing()).pipe(\n Stream.catch(\n (\n error,\n ): Stream.Stream<\n RunEvent,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n > => {\n if (\n !(error instanceof AiError.AiError) ||\n !isContextOverflowMessage(overflowText(error))\n ) {\n return Stream.fail(error);\n }\n const message = overflowText(error);\n\n if (trace.parts.length > 0 || contextTokenLimit === undefined) {\n return Stream.fail(ContextOverflowError.make({ message, retried: false }));\n }\n if (context.compaction.overflowRetryTurn === turn) {\n return Stream.fail(ContextOverflowError.make({ message, retried: true }));\n }\n context.compaction.overflowRetryTurn = turn;\n context.compaction.lastCompactionTurn = turn;\n type TurnStream = Stream.Stream<\n RunEvent,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n >;\n\n return Stream.unwrap(\n Effect.gen(function* () {\n const outcome = yield* compactContext(\n agent,\n context,\n modelContext.prompt,\n turn,\n options,\n callContext === undefined ? undefined : contextTokenLimit,\n messageTokenEstimator,\n Math.max(0, contextTokenLimit - derivedPromptTokens()),\n \"overflow\",\n )\n .pipe(withCallModel)\n .pipe(\n Effect.mapError(\n (inner): AgentRuntimeFailure<typeof agent, HookError, InstructionError> =>\n inner instanceof AiError.AiError &&\n isContextOverflowMessage(overflowText(inner))\n ? ContextOverflowError.make({\n message: overflowText(inner),\n retried: true,\n })\n : inner,\n ),\n );\n\n if (outcome.events.some((event) => event._tag === \"CompactionPerformed\"))\n refreshPrepared();\n\n const retryEstimate = (yield* preparedSourceTokens) + derivedPromptTokens();\n\n if (retryEstimate > contextTokenLimit) {\n return yield* ContextBudgetError.make({\n message: `Overflow compaction could not fit the retry inside the ${contextTokenLimit} token context target`,\n estimatedTokens: retryEstimate,\n targetTokens: contextTokenLimit,\n completionReserveTokens: policy.completionReserveTokens,\n });\n }\n\n // The retried call is outside the outer catch: a second\n // classified overflow converts here, typed, no retry.\n const retried: TurnStream = attempt(compactedOutgoing()).pipe(\n Stream.catch((again): TurnStream =>\n again instanceof AiError.AiError &&\n isContextOverflowMessage(overflowText(again))\n ? Stream.fail(\n ContextOverflowError.make({\n message: overflowText(again),\n retried: true,\n }),\n )\n : Stream.fail(again),\n ),\n );\n\n const events: TurnStream = Stream.fromIterable(outcome.events);\n\n return events.pipe(Stream.concat(retried));\n }),\n );\n },\n ),\n Stream.withSpan(\"AgentRuntime.model\", {\n attributes: {\n agentId: context.agentId,\n runId: context.runId,\n turnId,\n },\n }),\n );\n\n const continuation = Stream.unwrap(\n Effect.sync(() => {\n if (!trace.finished) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"Model response ended without a finish part\",\n }),\n );\n }\n\n const hasProviderCalls = Array.from(trace.toolCalls.values()).some(\n ({ providerExecuted }) => providerExecuted,\n );\n\n const turnCompletion = trace.turnCompletion;\n\n if (hasProviderCalls && turnCompletion === undefined) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"Model response omitted staged Turn completion\",\n }),\n );\n }\n const completionTool = agent.definition.completion?.tool;\n\n const declaresCompletion =\n completionTool !== undefined &&\n trace.applicationToolCalls.some((call) => call.name === completionTool);\n\n const declaresActionCompletion = trace.applicationToolCalls.some((call) =>\n agent.definition.completionFromTools?.some(\n (declaration) => declaration.tool === call.name,\n ),\n );\n\n const declaresRollover = trace.applicationToolCalls.some(\n (call) =>\n hasTool(agent.definition.toolkit.tools, call.name) &&\n Context.get(\n agent.definition.toolkit.tools[call.name].annotations,\n ContextRolloverTool,\n ),\n );\n\n if (\n declaresRollover &&\n (trace.toolCalls.size !== 1 || declaresCompletion || declaresActionCompletion)\n ) {\n return failRunEventStream(\n ModelProtocolError.make({\n message:\n \"A context rollover Tool must be the only Tool Call and cannot complete the Run\",\n }),\n );\n }\n\n const completionBatchError =\n (declaresCompletion || declaresActionCompletion) &&\n trace.applicationToolCalls.length !== 1\n ? ModelProtocolError.make({\n message: declaresCompletion\n ? `Completion Tool ${completionTool} must be the only application Tool Call in its batch`\n : \"An action completion Tool must be the only application Tool Call in its batch\",\n })\n : undefined;\n\n // Finalization cannot grant another correction turn. Completed provider work\n // is retained separately; only unexecuted application calls can be rejected.\n if (completionBatchError !== undefined && finalAnswerOnly) {\n return failRunEventStream(completionBatchError);\n }\n\n const completionBatch = declaresCompletion && trace.applicationToolCalls.length === 1;\n\n // Fail-closed (RUN-020): final-answer mode advertises either no\n // Tool or exactly the Definition-owned completion Tool. Any other\n // declaration is a protocol violation, never another rejection\n // round.\n if (\n finalAnswerOnly &&\n trace.toolCalls.size > 0 &&\n (hasProviderCalls || !completionBatch)\n ) {\n return failRunEventStream(\n ModelProtocolError.make({\n message:\n completionTool === undefined\n ? `Model declared ${trace.toolCalls.size} Tool Call(s) under toolChoice \"none\" after budget exhaustion`\n : `Model declared ${trace.toolCalls.size} non-completion Tool Call(s) after budget exhaustion`,\n }),\n );\n }\n\n const providerOnly =\n trace.toolCalls.size > 0 &&\n Array.from(trace.toolCalls.values()).every(({ providerExecuted }) => providerExecuted);\n\n const missingProviderResult = Array.from(trace.toolCalls.entries()).find(\n ([id, call]) => call.providerExecuted && !trace.finalToolResultIds.has(id),\n );\n\n if (missingProviderResult !== undefined) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Provider-executed Tool Call ${missingProviderResult[0]} completed without a terminal result`,\n }),\n );\n }\n const toolCalls = priorToolCalls + trace.toolCalls.size;\n const overToolBudget = toolCalls + context.programmaticToolCalls > bounds.maxToolCalls;\n\n if (overToolBudget && policy.onExhaustion === \"fail\") {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"tool-calls\",\n message: `Agent exceeded its ${bounds.maxToolCalls} Tool Call limit`,\n }),\n );\n }\n if (agent.definition.completion?.required === true && trace.toolCalls.size === 0) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Model stopped without required completion Tool ${agent.definition.completion.tool}`,\n }),\n );\n }\n\n const stagedResponse = Stream.fromIterable(trace.providerResultPayloads).pipe(\n Stream.mapEffect((payload) => stampProviderResultEvent(context, turnId, payload)),\n Stream.concat(\n turnCompletion === undefined\n ? Stream.empty\n : Stream.fromEffect(\n Effect.map(eventBase(context), (base) =>\n TurnCompleted.make({\n ...base,\n turnId,\n turn,\n finishReason: turnCompletion.finishReason,\n }),\n ),\n ),\n ),\n );\n\n /** Official history advanced through this Turn's response, plus any Tool message. */\n const historyWithResponse = (...additions: ReadonlyArray<Prompt.Message>) =>\n Prompt.fromMessages([\n ...prompt.content,\n ...promptFromTurnParts(trace).content,\n ...additions,\n ]);\n\n /**\n * Post-validation seam: charge the response's usage (RUN-023), stage\n * it for the Turn's canonical commit, emit one-shot `BudgetWarning`\n * advisories (RUN-025), and resolve a token-budget breach before\n * `next` continues the Run. Only the token dimension surfaces as a\n * `consumed.breach` — fail-mode and cost breaches already failed\n * inside `consumeUsage`. A breaching stop response that decodes as\n * the final output completes directly (the answer exists, so no\n * grace call is spent); a breaching Tool-declaring response settles\n * its batch synthetically through the RUN-018 path and the next\n * Turn is final-answer constrained via `tokenExhausted`.\n */\n type TurnEvents = Stream.Stream<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n >;\n\n const afterValidatedResponse = (\n next: Effect.Effect<\n TurnEvents,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n >,\n ): TurnEvents =>\n stagedResponse.pipe(\n Stream.concat(\n Stream.unwrap(\n Effect.gen(function* () {\n const consumed = yield* consumeTurnUsage(trace.toolCalls.size);\n\n const pre: Array<RunEvent> = [...consumed.warnings];\n\n if (\n !context.warnedLimits.has(\"tool-calls\") &&\n nearingLimit(toolCalls + context.programmaticToolCalls, bounds.maxToolCalls)\n ) {\n context.warnedLimits.add(\"tool-calls\");\n pre.push(\n BudgetWarning.make({\n ...(yield* eventBase(context)),\n limit: \"tool-calls\",\n consumed: toolCalls + context.programmaticToolCalls,\n limitValue: bounds.maxToolCalls,\n }),\n );\n }\n if (!context.warnedLimits.has(\"turns\") && nearingLimit(turn, bounds.maxTurns)) {\n context.warnedLimits.add(\"turns\");\n pre.push(\n BudgetWarning.make({\n ...(yield* eventBase(context)),\n limit: \"turns\",\n consumed: turn,\n limitValue: bounds.maxTurns,\n }),\n );\n }\n\n const emitThen = <NextError, NextRequirements>(\n nextStream: Stream.Stream<TurnOutput, NextError, NextRequirements>,\n ): Stream.Stream<TurnOutput, NextError, NextRequirements> =>\n pre.length === 0\n ? nextStream\n : Stream.fromIterable(pre).pipe(Stream.concat(nextStream));\n\n if (consumed.breach !== undefined) {\n // Provider-executed calls already ran provider-side: a\n // stop response with no APPLICATION calls can settle\n // the breach directly unless completion is required (RUN-025).\n if (\n agent.definition.completion?.required !== true &&\n trace.applicationToolCalls.length === 0 &&\n trace.finishReason === \"stop\"\n ) {\n const output = yield* decodeFinalOutput(agent, trace.text.join(\"\")).pipe(\n Effect.map(Option.some),\n Effect.catch(() => Effect.succeed(Option.none())),\n );\n\n if (Option.isSome(output)) {\n yield* advanceHistory(context, historyWithResponse(), options);\n\n const completionUsage = yield* usageReportOf(context);\n\n return emitThen(\n Stream.fromEffect(\n Effect.map(eventBase(context), (base) =>\n RunCompleted.make({\n ...base,\n output: output.value.encoded,\n turns: turn,\n finishReason: \"budget-exhausted\",\n exhausted: \"tokens\",\n ...completionUsage,\n }),\n ),\n ),\n );\n }\n }\n if (trace.applicationToolCalls.length > 0 && !completionBatch) {\n // RUN-025 joins the RUN-018 synthetic-settlement path:\n // the token-breaching batch never executes a handler,\n // and `tokenExhausted` (stamped by `consumeUsage`)\n // constrains every subsequent request.\n const rejection = yield* settleRejectedBatch(\n context,\n turnId,\n trace,\n AgentPolicyError.make({\n limit: \"tokens\",\n message: `Token budget exhausted: this Run's ${policy.tokenBudget ?? 0} token budget was reached, so this call was rejected without executing. Do not request more tools; produce your final answer now from the information you already have.`,\n }),\n );\n\n return emitThen(\n Stream.fromIterable(rejection).pipe(\n Stream.concat(\n toolBatchContinuation(\n agent,\n context,\n trace,\n prompt,\n turn,\n toolCalls,\n options,\n ),\n ),\n ),\n );\n }\n // A breaching stop response without decodable output\n // falls through: the ordinary settle decodes (and fails\n // typed) exactly as it would without the breach.\n }\n\n return emitThen(yield* next);\n }),\n ),\n ),\n );\n\n /**\n * Advance official history for a Turn that always continues, drain\n * steering at the safe seam, and start the next Turn. The `maxTurns`\n * guard already ran for these Tool Call sites.\n */\n const continueTurn = (history: Prompt.Prompt) =>\n Effect.gen(function* () {\n yield* advanceHistory(context, history, options);\n const steering = yield* drainInputs(context, options);\n const nextPrompt = yield* appendInputs(context, history, steering, options);\n\n return nextTurn(nextPrompt, turn + 1, toolCalls);\n });\n\n /**\n * The otherwise-stop seam: advance official history, drain steering,\n * fall back to buffered follow-ups, then either start the next Turn\n * under the `maxTurns` and repeated-failure Stop Policy bounds or\n * complete the Run with the Turn's decoded final output.\n */\n const settleOrFollowUp = (history: Prompt.Prompt) =>\n Effect.gen(function* () {\n yield* advanceHistory(context, history, options);\n const steering = yield* drainInputs(context, options);\n\n const queued =\n steering.length > 0\n ? steering\n : takeFollowUps(context, options.commandDrainPolicy ?? \"one\");\n\n if (queued.length > 0) {\n // Final-answer mode admits exactly one grace Turn past\n // `maxTurns` (RUN-019): `turn > maxTurns` can only be\n // `maxTurns + 1`, so a second grace is structurally\n // impossible.\n const turnsBlocked =\n policy.onExhaustion === \"fail\" ? turn >= bounds.maxTurns : turn > bounds.maxTurns;\n\n if (turnsBlocked) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"turns\",\n message: `Agent exceeded its ${bounds.maxTurns} Turn limit`,\n }),\n );\n }\n yield* applyRepeatedFailurePolicy(\n context,\n trace,\n agent.definition.policy.repeatedFailureLimit,\n );\n const nextPrompt = yield* appendInputs(context, history, queued, options);\n\n return nextTurn(nextPrompt, turn + 1, toolCalls);\n }\n const output = yield* decodeFinalOutput(agent, trace.text.join(\"\"));\n const declaration = agent.definition.runDisposition;\n\n const runDisposition =\n finalAnswerOnly || declaration === undefined\n ? undefined\n : yield* encodeRunDisposition(agent, output.decoded);\n\n const completionUsage = yield* usageReportOf(context);\n\n return Stream.fromEffect(\n Effect.map(eventBase(context), (base) =>\n RunCompleted.make({\n ...base,\n output: output.encoded,\n ...(runDisposition === undefined ? {} : { runDisposition }),\n turns: turn,\n // A Run settled under the final-answer constraint reports\n // the exhaustion honestly (RUN-011), never a plain model\n // stop, and carries the dimension that bound.\n finishReason: finalAnswerOnly ? \"budget-exhausted\" : \"model-stop\",\n ...(finalAnswerOnly && context.exhaustedDimension !== undefined\n ? { exhausted: context.exhaustedDimension }\n : {}),\n ...completionUsage,\n }),\n ),\n );\n });\n\n if (providerOnly && trace.finishReason === \"stop\") {\n if (agent.definition.completion?.required === true) {\n const turnsBlocked =\n policy.onExhaustion === \"fail\" ? turn >= bounds.maxTurns : turn > bounds.maxTurns;\n\n if (turnsBlocked) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"turns\",\n message: `Agent exceeded its ${bounds.maxTurns} Turn limit`,\n }),\n );\n }\n }\n\n return afterValidatedResponse(\n agent.definition.completion?.required === true\n ? continueTurn(historyWithResponse())\n : settleOrFollowUp(historyWithResponse()),\n );\n }\n\n if (trace.toolCalls.size > 0) {\n if (trace.finishReason !== \"tool-calls\") {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Model declared Tool Calls with incompatible finish reason ${trace.finishReason}`,\n }),\n );\n }\n\n const turnsBlocked =\n (turn > bounds.maxTurns &&\n !(turn === bounds.maxTurns + 1 && finalAnswerOnly && completionBatch)) ||\n (policy.onExhaustion === \"fail\" && turn === bounds.maxTurns && !completionBatch);\n\n if (turnsBlocked) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"turns\",\n message: `Agent exceeded its ${bounds.maxTurns} Turn limit`,\n }),\n );\n }\n\n // RUN-018: a rejected batch never executes a handler and is\n // never durably declared — it settles synthetically through the\n // ordinary batch continuation, so the model sees one failed\n // result per rejected call. Budget exhaustion constrains the next\n // Turn; a mixed completion declaration can be corrected within\n // the remaining budgets. `commitResponse` is deliberately skipped:\n // without it the Turn stays on the single-batch canonical\n // commit shape and recovery replays it like any no-tool Turn. The\n // rejected Turn's usage is still charged via\n // `afterValidatedResponse` because the Run continues.\n const batchRejection =\n overToolBudget &&\n trace.applicationToolCalls.length > 0 &&\n !(completionBatch && policy.onExhaustion === \"final-answer\")\n ? AgentPolicyError.make({\n limit: \"tool-calls\",\n message: `Tool Call budget exhausted: this Run's ${bounds.maxToolCalls} Tool Call limit was reached, so this call was rejected without executing. Do not request more tools; produce your final answer now from the information you already have.`,\n })\n : completionBatchError === undefined\n ? undefined\n : ModelProtocolError.make({\n message:\n `${completionBatchError.message}. ` +\n (hasProviderCalls\n ? \"The application batch was rejected before execution; none of its application tools ran. Completed provider results are retained. \"\n : \"The entire batch was rejected before execution; none of its tools ran. \") +\n \"Request any needed ordinary tools first, wait for their results, then call a completion tool alone.\",\n });\n\n if (batchRejection !== undefined) {\n return afterValidatedResponse(\n Effect.gen(function* () {\n const rejection = yield* settleRejectedBatch(\n context,\n turnId,\n trace,\n batchRejection,\n );\n\n return Stream.fromIterable(rejection).pipe(\n Stream.concat(\n toolBatchContinuation(\n agent,\n context,\n trace,\n prompt,\n turn,\n toolCalls,\n options,\n ),\n ),\n );\n }),\n );\n }\n if (trace.applicationToolCalls.length === 0) {\n return afterValidatedResponse(\n Effect.gen(function* () {\n const history = historyWithResponse();\n\n // Preserve a completed provider Tool batch even when its final outcome\n // reaches the failure limit and no following Turn starts.\n yield* advanceHistory(context, history, options);\n yield* applyRepeatedFailurePolicy(\n context,\n trace,\n agent.definition.policy.repeatedFailureLimit,\n );\n\n const steering = yield* drainInputs(context, options);\n const nextPrompt = yield* appendInputs(context, history, steering, options);\n\n return nextTurn(nextPrompt, turn + 1, toolCalls);\n }),\n );\n }\n\n return afterValidatedResponse(\n Effect.gen(function* () {\n const toolkit = yield* agent.definition.toolkit;\n\n const concurrency = yield* schedulingConcurrency(\n agent.definition.policy.toolConcurrency,\n options.scheduling,\n );\n\n if (options.durability !== undefined) {\n // Turn-response commit seam: staged canonical response events are emitted before\n // this persistence mutation, while approval preflight and preparation still run\n // afterward. This retains durability §15's provably-safe resume window without\n // allowing eager continuation work to overtake the append-only event stream.\n yield* options.durability.commitResponse({\n turn,\n turnId,\n responseMessages: promptFromTurnParts(trace),\n calls: trace.applicationCallDescriptors,\n ...(trace.toolParameterRejections.size === 0\n ? {}\n : {\n toolParameterRejections: [...trace.toolParameterRejections.values()],\n }),\n toolExposure: snapshot,\n });\n }\n\n const toolResults = guardBudgetStream(\n executeToolBatch(\n context,\n turnId,\n turn,\n toolkit,\n trace.applicationToolCalls,\n trace,\n concurrency,\n options,\n {\n maxToolCalls: bounds.maxToolCalls,\n declaredToolCalls: toolCalls,\n },\n agent.definition.policy.toolResultBounds,\n ),\n options.budget,\n );\n\n return toolResults.pipe(\n Stream.concat(\n toolBatchContinuation(agent, context, trace, prompt, turn, toolCalls, options),\n ),\n );\n }),\n );\n }\n\n if (trace.finishReason !== \"stop\") {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Model stopped without a final answer (${trace.finishReason})`,\n }),\n );\n }\n\n return afterValidatedResponse(settleOrFollowUp(historyWithResponse()));\n }),\n );\n\n const events = Stream.fromIterable(preEvents).pipe(\n Stream.concat(started),\n Stream.concat(response),\n Stream.concat(continuation.pipe(Stream.tapCause(() => retainFailedUsage()))),\n );\n\n return modelServices === undefined ? events : Stream.provideContext(events, modelServices);\n }),\n );\n\n/**\n * Settle a completed application Tool batch and continue the Run: verify one\n * final result per declared call, fold outcomes into the repeated-failure\n * Stop Policy, advance official history with the Tool message in declaration\n * order, drain steering at the safe seam, and start the next Turn. Shared by\n * the ordinary model-declared path (`makeTurn`) and the durable batch-resume\n * path (`makeResumeTurn`).\n */\nconst toolBatchContinuation = <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n HookError,\n HookRequirements,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 agent: RuntimeProgram<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n context: RunContext,\n trace: TurnTrace,\n prompt: Prompt.Prompt,\n turn: number,\n toolCalls: number,\n options: RunOptions<HookError, HookRequirements>,\n): Stream.Stream<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n if (trace.finalToolResultIds.size !== trace.toolCalls.size) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"A Tool Call turn completed without one final result per Tool Call\",\n }),\n );\n }\n const orderedResults: Array<(typeof trace.applicationToolResults)[number]> = [];\n\n for (const call of trace.applicationToolCalls) {\n const result = trace.applicationToolResults.find((candidate) => candidate?.id === call.id);\n\n if (result === undefined) {\n return failRunEventStream(\n ModelProtocolError.make({ message: \"Tool batch did not settle completely\" }),\n );\n }\n orderedResults.push(result);\n }\n\n for (const result of orderedResults) {\n if (!result.isFailure && result.toolSelection !== undefined)\n context.toolSelection = result.toolSelection;\n }\n\n const toolMessage = Prompt.makeMessage(\"tool\", {\n content: orderedResults.map((result) =>\n Prompt.makePart(\"tool-result\", {\n id: result.id,\n name: result.name,\n result: result.encodedResult,\n isFailure: result.isFailure,\n providerExecuted: false,\n }),\n ),\n });\n\n const history = Prompt.fromMessages([\n ...prompt.content,\n ...promptFromTurnParts(trace).content,\n toolMessage,\n ]);\n\n // Publish the complete batch before enforcing a terminal policy. RunFailed commits\n // this history through the same durable seam as a subsequent Turn or completion.\n yield* advanceHistory(context, history, options);\n yield* applyRepeatedFailurePolicy(\n context,\n trace,\n agent.definition.policy.repeatedFailureLimit,\n );\n\n const rolloverResult = orderedResults.length === 1 ? orderedResults[0] : undefined;\n\n if (\n rolloverResult !== undefined &&\n !rolloverResult.isFailure &&\n trace.applicationCallDescriptors.some((call) => call.toolCallId === rolloverResult.id) &&\n hasTool(agent.definition.toolkit.tools, rolloverResult.name) &&\n Context.get(\n agent.definition.toolkit.tools[rolloverResult.name].annotations,\n ContextRolloverTool,\n )\n ) {\n context.pendingContextToolCallId = rolloverResult.id;\n }\n\n const completion = agent.definition.completion;\n\n const successfulResult =\n trace.applicationToolCalls.length === 1 &&\n orderedResults.length === 1 &&\n orderedResults[0]?.isFailure === false\n ? orderedResults[0]\n : undefined;\n\n const actionCompletion = agent.definition.completionFromTools?.find(\n (declaration) => declaration.tool === successfulResult?.name,\n );\n\n let selectedOutput: Option.Option<{\n readonly encoded: Schema.Json;\n readonly decoded: Agent.Output<typeof agent>;\n }> = Option.none();\n\n if (\n successfulResult !== undefined &&\n trace.applicationCallDescriptors.some((call) => call.toolCallId === successfulResult.id) &&\n (successfulResult.name === completion?.tool || actionCompletion !== undefined)\n ) {\n const call = trace.applicationCallDescriptors[0];\n\n if (call === undefined) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"Completion Tool has no canonical call descriptor\",\n }),\n );\n }\n if (actionCompletion !== undefined) {\n selectedOutput = yield* projectCompletionFromToolOutput(\n agent,\n actionCompletion,\n call.parameters,\n successfulResult.encodedResult,\n );\n } else if (completion !== undefined) {\n selectedOutput = Option.some(\n yield* projectCompletionOutput(\n agent,\n completion,\n call.parameters,\n successfulResult.encodedResult,\n ),\n );\n }\n }\n\n if (Option.isSome(selectedOutput)) {\n const output = selectedOutput.value;\n const bounds = effectiveRunBounds(agent.definition.policy, options);\n\n const exhausted = context.tokenExhausted\n ? \"tokens\"\n : turn > bounds.maxTurns\n ? \"turns\"\n : toolCalls + context.programmaticToolCalls > bounds.maxToolCalls\n ? \"tool-calls\"\n : context.exhaustedDimension;\n\n if (exhausted !== undefined && context.exhaustedDimension === undefined) {\n context.exhaustedDimension = exhausted;\n }\n const declaration = agent.definition.runDisposition;\n\n const runDisposition =\n exhausted !== undefined || declaration === undefined\n ? undefined\n : yield* encodeRunDisposition(agent, output.decoded);\n\n const completionUsage = yield* usageReportOf(context);\n\n return Stream.fromEffect(\n Effect.map(eventBase(context), (base) =>\n RunCompleted.make({\n ...base,\n output: output.encoded,\n ...(runDisposition === undefined ? {} : { runDisposition }),\n turns: turn,\n finishReason: exhausted === undefined ? \"completed\" : \"budget-exhausted\",\n ...(exhausted === undefined ? {} : { exhausted }),\n ...completionUsage,\n }),\n ),\n );\n }\n const steering = yield* drainInputs(context, options);\n const nextPrompt = yield* appendInputs(context, history, steering, options);\n\n return nextTurn(nextPrompt, turn + 1, toolCalls);\n }),\n );\n\n/**\n * Resume one canonically declared Tool batch without re-invoking the model\n * (the durable batch-resume seam consumed via `RunOptions.resume`).\n *\n * Only unfinished calls are validated through their current parameter Schemas before\n * execution. Settled siblings retain bounded canonical JSON without looking up old Tools.\n * The original response and declaration order remain intact; approval, authorization and\n * durable preparation cover only calls that can still execute.\n * No model request is made and no usage is consumed for the resumed Turn.\n */\nconst makeResumeTurn = <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n HookError,\n HookRequirements,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 agent: RuntimeProgram<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n context: RunContext,\n prompt: Prompt.Prompt,\n resume: RunTurnResume,\n countedToolCalls: number,\n options: RunOptions<HookError, HookRequirements>,\n): Stream.Stream<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const tools = agent.definition.toolkit.tools;\n const turn = resume.turn;\n const turnId = resume.turnId;\n const settledInputs = yield* snapshotResumedSettledCalls(resume, resume.calls.length);\n const settledCalls = yield* Effect.forEach(settledInputs, decodeResumedSettledCall);\n const recordedSettledIds = new Set(settledCalls.map((call) => call.id));\n const visibility = yield* RunToolVisibility;\n\n if (\n resume.toolExposure === undefined &&\n resume.calls.some((call) => !call.providerExecuted && !recordedSettledIds.has(call.id)) &&\n (agent.definition.toolExposure !== undefined ||\n context.toolSelection !== undefined ||\n visibility !== undefined)\n )\n return yield* ModelProtocolError.make({\n message: \"Resumed progressive Turn is missing its original Tool exposure\",\n });\n\n context.toolCatalog = yield* eligibleCatalog(\n agent.definition,\n { threadId: context.threadId, runId: context.runId, turn, input: context.input },\n options.subagentGrant,\n options.delegationDepth ?? options.parentLink?.depth ?? 0,\n );\n context.toolExposure =\n resume.toolExposure === undefined ? undefined : yield* decodeSnapshot(resume.toolExposure);\n const originalExposure = context.toolExposure;\n\n if (originalExposure !== undefined) {\n if (resume.calls.some((call) => !originalExposure.exposedToolNames.includes(call.name)))\n return yield* ModelProtocolError.make({\n message: \"Resumed Tool call was not exposed in its original model request\",\n });\n context.toolSelection =\n originalExposure.selection === undefined\n ? undefined\n : {\n ...originalExposure.selection,\n toolNames: originalExposure.selection.toolNames.filter((name) =>\n hasTool(tools, name),\n ),\n };\n }\n\n if (!Number.isInteger(turn) || turn <= 0) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"Turn resume requires a positive integer turn number\",\n }),\n );\n }\n if (resume.calls.length === 0) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"Turn resume requires at least one declared Tool Call\",\n }),\n );\n }\n\n const trace: TurnTrace = {\n replayedResponse: resume.responseMessages,\n responsePartCount: 0,\n responsePartBytes: 0,\n parts: [],\n text: [],\n textParts: new Map(),\n reasoningParts: new Map(),\n toolParameterParts: new Map(),\n toolCalls: new Map(),\n finalToolResultIds: new Set(),\n providerResultPayloads: [],\n providerStagedPayloadBytes: 0,\n turnCompletion: undefined,\n applicationToolCalls: [],\n toolParameterRejections: new Map(),\n applicationCallDescriptors: [],\n applicationToolResults: [],\n finished: true,\n finishReason: \"tool-calls\",\n usage: undefined,\n };\n\n const declarationByCallId = new Map<\n string,\n { readonly index: number; readonly name: string; readonly providerExecuted: boolean }\n >();\n\n const rejections = yield* Schema.decodeEffect(Schema.Array(ToolParameterRejection))(\n resume.toolParameterRejections ?? [],\n ).pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({ message: \"Invalid parameter rejection evidence on resume\" }),\n ),\n );\n\n const sameJson = Schema.toEquivalence(Schema.Json);\n\n for (const rejection of rejections) {\n const call = resume.calls.find((call) => call.id === rejection.toolCallId);\n\n if (\n call === undefined ||\n call.providerExecuted ||\n call.name !== rejection.error.reason.toolName ||\n !sameJson(yield* decodeEventJson(call.params, \"Tool parameters\"), rejection.parameters) ||\n trace.toolParameterRejections.has(call.id)\n ) {\n return yield* ModelProtocolError.make({\n message: \"Parameter rejection does not match recorded Tool Call on resume\",\n });\n }\n\n trace.toolParameterRejections.set(call.id, rejection);\n if (!recordedSettledIds.has(call.id)) {\n settledCalls.push({\n id: call.id,\n isFailure: true,\n result: yield* decodeEventJson(\n boundEncodedToolResult(rejection.error, agent.definition.policy.toolResultBounds),\n \"Rejected Tool result\",\n ),\n });\n recordedSettledIds.add(call.id);\n }\n }\n\n for (const call of resume.calls) {\n if (!recordedSettledIds.has(call.id) && !hasTool(tools, call.name)) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Turn resume declared unknown unfinished Tool ${call.name}`,\n }),\n );\n }\n if (trace.toolCalls.has(call.id)) {\n return failRunEventStream(\n ModelProtocolError.make({ message: `Turn resume repeated Tool Call ID ${call.id}` }),\n );\n }\n const tool = tools[call.name] as ToolUnion<Tools>;\n const toolCallId = yield* decodeToolCallId(call.id);\n\n if (!recordedSettledIds.has(call.id)) {\n yield* decodeToolCallParameters<Tools>(tool, call.name, call.params, \"resume\");\n }\n const parameters = yield* decodeEventJson(call.params, \"Tool parameters\");\n const providerExecuted = call.providerExecuted === true;\n\n declarationByCallId.set(call.id, {\n index: trace.applicationToolCalls.length,\n name: call.name,\n providerExecuted,\n });\n trace.parts.push(\n Response.makePart(\"tool-call\", {\n id: call.id,\n name: call.name,\n params: parameters,\n providerExecuted,\n }),\n );\n trace.toolCalls.set(call.id, { name: call.name, providerExecuted });\n if (providerExecuted) continue;\n trace.applicationToolCalls.push(\n Response.makePart(\"tool-call\", {\n id: call.id,\n name: call.name,\n params: parameters,\n providerExecuted: false,\n }),\n );\n if (\n (!recordedSettledIds.has(call.id) || resume.settledCompletion === call.id) &&\n hasTool(tools, call.name)\n )\n trace.applicationCallDescriptors.push({\n toolCallId,\n toolName: call.name,\n parameters,\n executionClass: getToolExecutionClass(tool),\n executionKind: getToolExecutionKind(tool.annotations),\n });\n }\n const completionTool = agent.definition.completion?.tool;\n\n const completionCandidates = trace.applicationToolCalls.filter(\n (call) => !recordedSettledIds.has(call.id) || resume.settledCompletion === call.id,\n );\n\n const actionCompletionCall = completionCandidates.find((call) =>\n agent.definition.completionFromTools?.some((declaration) => declaration.tool === call.name),\n );\n\n if (\n (actionCompletionCall !== undefined ||\n (completionTool !== undefined &&\n completionCandidates.some((call) => call.name === completionTool))) &&\n trace.applicationToolCalls.length !== 1\n ) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"A completion Tool must be the only application Tool Call in its batch\",\n }),\n );\n }\n\n const completionBatch =\n completionTool !== undefined &&\n trace.applicationToolCalls.length === 1 &&\n completionCandidates[0]?.name === completionTool;\n\n if (\n (completionBatch &&\n completionTool !== undefined &&\n Context.get(tools[completionTool].annotations, ContextRolloverTool)) ||\n (actionCompletionCall !== undefined &&\n Context.get(tools[actionCompletionCall.name].annotations, ContextRolloverTool))\n ) {\n return failRunEventStream(\n ModelProtocolError.make({ message: \"A context rollover Tool cannot complete the Run\" }),\n );\n }\n\n if (context.finalizationUsed && (!completionBatch || trace.toolCalls.size !== 1)) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: \"A resumed grace finalization may only execute the completion Tool\",\n }),\n );\n }\n const settledIds = new Set<string>();\n\n for (const settledCall of settledCalls) {\n const rejection = trace.toolParameterRejections.get(settledCall.id);\n const rejectionJson = rejection === undefined ? undefined : JSON.stringify(rejection.error);\n\n // An old policy may have truncated this already-settled error. Verify its exact\n // retained slices against the canonical rejection, without imposing today's bound.\n const matchesRejection =\n rejection === undefined ||\n sameJson(settledCall.result, rejection.error) ||\n (Schema.is(Schema.toEncoded(TruncatedToolResult))(settledCall.result) &&\n rejectionJson !== undefined &&\n settledCall.result.originalBytes === utf8ByteLength(rejectionJson) &&\n rejectionJson.startsWith(settledCall.result.head) &&\n rejectionJson.endsWith(settledCall.result.tail));\n\n if (\n rejection !== undefined &&\n (!settledCall.isFailure ||\n settledCall.toolSelection !== undefined ||\n (settledCall.budgetRejected !== true && !matchesRejection))\n ) {\n return yield* ModelProtocolError.make({\n message: \"Settled result contradicts parameter rejection on resume\",\n });\n }\n\n const declared = declarationByCallId.get(settledCall.id);\n\n if (declared === undefined) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Turn resume settled an undeclared Tool Call ${settledCall.id}`,\n }),\n );\n }\n if (settledIds.has(settledCall.id)) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Turn resume settled Tool Call ${settledCall.id} more than once`,\n }),\n );\n }\n settledIds.add(settledCall.id);\n trace.finalToolResultIds.add(settledCall.id);\n if (declared.providerExecuted) {\n trace.parts.push(\n Response.makePart(\"tool-result\", {\n id: settledCall.id,\n name: declared.name,\n result: settledCall.result,\n encodedResult: settledCall.result,\n isFailure: settledCall.isFailure,\n providerExecuted: true,\n preliminary: false,\n }),\n );\n continue;\n }\n trace.applicationToolResults[declared.index] = {\n ...(settledCall.toolSelection === undefined\n ? {}\n : {\n toolSelection: {\n ...settledCall.toolSelection,\n toolNames: settledCall.toolSelection.toolNames.filter((name) =>\n hasTool(tools, name),\n ),\n },\n }),\n id: settledCall.id,\n name: declared.name,\n encodedResult: settledCall.result,\n isFailure: settledCall.isFailure,\n ...(settledCall.budgetRejected === undefined\n ? {}\n : { budgetRejected: settledCall.budgetRejected }),\n };\n }\n const policy = agent.definition.policy;\n const bounds = effectiveRunBounds(policy, options);\n const toolCalls = countedToolCalls;\n\n for (const [id, call] of declarationByCallId) {\n if (call.providerExecuted && !settledIds.has(id)) {\n return failRunEventStream(\n ModelProtocolError.make({\n message: `Turn resume lacks the canonical provider result for ${id}`,\n }),\n );\n }\n }\n const overToolBudget = toolCalls + context.programmaticToolCalls > bounds.maxToolCalls;\n\n if (overToolBudget && policy.onExhaustion === \"fail\") {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"tool-calls\",\n message: `Agent exceeded its ${bounds.maxToolCalls} Tool Call limit`,\n }),\n );\n }\n\n const turnsBlocked =\n (turn > bounds.maxTurns &&\n !(\n policy.onExhaustion === \"final-answer\" &&\n turn === bounds.maxTurns + 1 &&\n context.finalizationUsed &&\n completionBatch\n )) ||\n (policy.onExhaustion === \"fail\" && turn === bounds.maxTurns && !completionBatch);\n\n if (turnsBlocked) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"turns\",\n message: `Agent exceeded its ${bounds.maxTurns} Turn limit`,\n }),\n );\n }\n const toolkit = yield* agent.definition.toolkit;\n\n const concurrency = yield* schedulingConcurrency(\n agent.definition.policy.toolConcurrency,\n options.scheduling,\n );\n\n // The pending Turn's committed LEADING messages (Turn-1 evaluated\n // instructions + input, or steering committed inside the pending\n // canonical response record) re-enter official history here, BEFORE the\n // rebuilt assistant tool-call message: a resumed Attempt's canonical\n // prompt boundary excludes the pending Turn, so without this thread the\n // resumed Run's live model context would silently drop them. Absent\n // `leadingMessages` keeps the prior behavior byte-for-byte.\n const leading = resume.leadingMessages;\n\n const resumedPrompt =\n leading === undefined || leading.content.length === 0\n ? prompt\n : Prompt.fromMessages([...prompt.content, ...leading.content]);\n\n if (resumedPrompt !== prompt) {\n yield* advanceHistory(context, resumedPrompt, options);\n }\n\n // The resumed Turn made its model call in a prior Attempt: no\n // ModelStarted event, no model metric, and no usage is consumed. The\n // TurnCompleted seam is re-emitted so downstream commit seams observe\n // the normal ordering (a Turn completes before its Tool batch executes).\n const started = Stream.fromEffect(\n Effect.gen(function* () {\n yield* Effect.logDebug(\"agent resumed a declared Tool batch\").pipe(\n Effect.annotateLogs({\n agentId: context.agentId,\n runId: context.runId,\n turnId,\n }),\n );\n\n return [\n TurnStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n }),\n TurnCompleted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n finishReason: \"tool-calls\",\n }),\n ] satisfies ReadonlyArray<RunEvent>;\n }).pipe(Effect.withLogSpan(\"AgentRuntime.resume\")),\n ).pipe(Stream.flatMap(Stream.fromIterable));\n\n const continueAfterBatch = () =>\n toolBatchContinuation(agent, context, trace, resumedPrompt, turn, toolCalls, options);\n\n // RUN-018 on the resume path: a canonically declared over-budget batch\n // settles synthetically under final-answer mode — recorded settled\n // results stand verbatim, only open calls get the synthetic failure,\n // and no handler starts. Once the synthetic settlements commit, the\n // pending batch is complete and recovery offers no further resume.\n if (overToolBudget && !(completionBatch && policy.onExhaustion === \"final-answer\")) {\n const rejection = yield* settleRejectedBatch(\n context,\n turnId,\n trace,\n AgentPolicyError.make({\n limit: \"tool-calls\",\n message: `Tool Call budget exhausted: this Run's ${bounds.maxToolCalls} Tool Call limit was reached, so this call was rejected without executing. Do not request more tools; produce your final answer now from the information you already have.`,\n }),\n settledIds,\n );\n\n return started.pipe(\n Stream.concat(Stream.fromIterable(rejection)),\n Stream.concat(continueAfterBatch()),\n );\n }\n\n const toolResults = guardBudgetStream(\n executeToolBatch(\n context,\n turnId,\n turn,\n toolkit,\n trace.applicationToolCalls,\n trace,\n concurrency,\n options,\n {\n maxToolCalls: bounds.maxToolCalls,\n declaredToolCalls: toolCalls,\n },\n agent.definition.policy.toolResultBounds,\n settledIds,\n ),\n options.budget,\n );\n\n return started.pipe(Stream.concat(toolResults), Stream.concat(continueAfterBatch()));\n }),\n );\n\nconst failRunEventStream = <Error>(error: Error): Stream.Stream<RunEvent, Error> =>\n Stream.fail(error);\n\nconst durationLimitError = (policy: AgentPolicy): AgentPolicyError =>\n AgentPolicyError.make({\n limit: \"duration\",\n message: `Agent exceeded its ${Duration.format(policy.maxDuration)} duration limit`,\n });\n\nconst enforceDurationDeadline = <A, E, R>(\n execution: Stream.Stream<A, E, R>,\n durationDeadlineMillis: number,\n durationLimit: AgentPolicyError,\n): Stream.Stream<A, E | AgentPolicyError, R> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n const remaining = durationDeadlineMillis - now;\n\n if (remaining <= 0) {\n return Stream.fail(durationLimit);\n }\n\n return execution.pipe(\n Stream.interruptWhen(\n Effect.sleep(remaining).pipe(Effect.andThen(Effect.fail(durationLimit))),\n ),\n );\n }),\n );\n\nconst guardBudgetStream = <A, E, R, HookError, HookRequirements>(\n stream: Stream.Stream<A, E, R>,\n budget: RunOptions<HookError, HookRequirements>[\"budget\"],\n): Stream.Stream<A, E | HookError, R | HookRequirements> =>\n budget === undefined\n ? stream\n : Stream.transformPull(stream, (pull) => Effect.succeed(budget.guard(pull)));\n\n/** Decode input and interpret the Run, validating terminal output before committing history. */\nfunction streamWithCompletion<\n A extends ExecutableAgent,\n H = never,\n R = never,\n CompletionError = never,\n CompletionRequirements = never,\n>(\n agent: A,\n input: unknown,\n options: RunOptions<H, R> | undefined,\n onCompleted?: (\n completed: RunCompleted,\n ) => Effect.Effect<void, CompletionError, CompletionRequirements>,\n onUsage?: (read: Effect.Effect<RunUsageReport>) => void,\n): Stream.Stream<\n RunEvent,\n AgentRuntimeFailure<A, H> | CompletionError,\n | AgentRuntimeRequirements<A, R>\n | CompletionRequirements\n | ModelUsageAccounting\n | AgentUpdateAcceptance\n>;\nfunction streamWithCompletion<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n CompletionError = never,\n CompletionRequirements = never,\n HookError = never,\n HookRequirements = never,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 agentValue:\n | RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >\n | RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >[\"definition\"],\n input: unknown,\n runOptions: RunOptions<HookError, HookRequirements> = {},\n onCompleted?: (\n completed: RunCompleted,\n ) => Effect.Effect<void, CompletionError, CompletionRequirements>,\n onUsage?: (read: Effect.Effect<RunUsageReport>) => void,\n) {\n const agent: RuntimeProgram<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n > = { definition: \"definition\" in agentValue ? agentValue.definition : agentValue };\n\n const model = \"definition\" in agentValue ? agentValue.model : undefined;\n\n return Stream.unwrap(\n Effect.gen(function* (): Effect.fn.Return<\n Stream.Stream<\n RunEvent,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError> | CompletionError,\n | AgentRuntimeRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | CompletionRequirements\n | ModelRequires\n | ModelUsageAccounting\n | AgentUpdateAcceptance\n >,\n ThreadHistoryError,\n ThreadHistory\n > {\n const history = yield* ThreadHistory;\n\n const preparation = yield* Effect.serviceOption(RunContextPreparation).pipe(\n Effect.map(Option.getOrElse(() => RunContextPreparation.of({}))),\n );\n\n const authorization = yield* Effect.serviceOption(RunToolAuthorization).pipe(\n Effect.map(Option.getOrUndefined),\n );\n\n const visibility = yield* RunToolVisibility;\n\n const ids = yield* IdGenerator;\n const threadId = runOptions.threadId ?? (yield* ids.nextThreadId);\n const runId = runOptions.runId ?? (yield* ids.nextRunId);\n\n // Durable hosts retain each turn through their journal. Ordinary execution always has\n // an in-memory or on-success history owner; there is no discard-history Layer.\n const retained =\n history.retention === \"incremental\" && runOptions.durability !== undefined\n ? undefined\n : yield* history.open({ threadId, runId });\n\n if (\n history.retention === \"on-success\" &&\n (runOptions.history !== undefined ||\n runOptions.onHistory !== undefined ||\n runOptions.input !== undefined ||\n runOptions.durability !== undefined ||\n runOptions.subagent !== undefined ||\n runOptions.resume !== undefined ||\n runOptions.resumeUsage !== undefined)\n ) {\n return yield* ThreadHistoryError.make({\n threadId,\n reason: \"incompatible\",\n message:\n \"Provided history cannot share ownership with explicit history, input queues, or durable recovery hooks\",\n });\n }\n\n const initialHistory = runOptions.history ?? retained?.prompt;\n\n if (retained !== undefined && runOptions.history !== undefined) {\n yield* retained.stageHistory(runOptions.history);\n }\n\n const options: RunOptions<\n HookError | ThreadHistoryError | RunContextPreparationError,\n HookRequirements\n > = {\n ...runOptions,\n context: runOptions.context ?? preparation.hook,\n transientContext: runOptions.transientContext ?? preparation.transientContext,\n toolAuthorization: runOptions.toolAuthorization ?? authorization,\n threadId,\n runId,\n ...(retained === undefined\n ? {}\n : {\n history: initialHistory,\n onHistory: (next) =>\n retained\n .stageHistory(next)\n .pipe(Effect.andThen(() => runOptions.onHistory?.(next) ?? Effect.void)),\n }),\n };\n\n // Normalize the selected host policy at the Run boundary. Inner calls project typed\n // override failures into broker outcomes; native calls retain their original E channel.\n const programmaticAuthorization = Layer.effect(\n ProgrammaticToolAuthorization,\n Effect.gen(function* () {\n const services = yield* Effect.context<HookRequirements>();\n const selected = options.toolAuthorization;\n\n return ProgrammaticToolAuthorization.of({\n authorize: (request) =>\n selected === undefined\n ? Effect.succeed({ _tag: \"allowed\" })\n : provideHookServices(selected.authorize(request), services).pipe(\n Effect.catchCauseFilter(Cause.findError, (error, cause) =>\n Effect.fail(new BrokerCallFailure(error, cause)),\n ),\n ),\n });\n }),\n );\n\n const interpreted = Stream.unwrap(\n Effect.gen(function* () {\n const resumed =\n options.resume === undefined\n ? undefined\n : {\n batch: options.resume,\n usage: yield* decodeResumeUsage(options.resumeUsage),\n };\n\n const resumeUsage =\n resumed?.usage ??\n (options.resumeUsage === undefined\n ? undefined\n : yield* decodeResumeUsage(options.resumeUsage));\n\n if (\n resumed !== undefined &&\n (resumed.usage.committedTurns !== resumed.batch.turn ||\n resumed.usage.toolCalls < resumed.batch.calls.length ||\n resumed.usage.consecutiveToolFailures >\n resumed.usage.toolCalls - resumed.batch.calls.length)\n ) {\n return yield* ModelProtocolError.make({\n message:\n \"Run resume accounting conflicts with the pending Turn and declared Tool Calls\",\n });\n }\n const attemptStartedAtMillis = yield* Clock.currentTimeMillis;\n const maxDurationMillis = Duration.toMillis(agent.definition.policy.maxDuration);\n const attemptDeadlineMillis = attemptStartedAtMillis + maxDurationMillis;\n\n // A coordinator can impose an earlier deadline (for example a worker grant).\n // This option can only tighten the fresh execution allowance.\n const durationDeadlineMillis =\n options.durationDeadline === undefined\n ? attemptDeadlineMillis\n : Math.min(attemptDeadlineMillis, DateTime.toEpochMillis(options.durationDeadline));\n\n // Elapsed status tracks the logical Run's actual start. A shorter\n // deadline tightens execution without inventing time that never passed.\n const startedAtMillis =\n options.runStartedAt === undefined\n ? attemptStartedAtMillis\n : DateTime.toEpochMillis(options.runStartedAt);\n\n const compactor = yield* Effect.serviceOption(ContextCompactor).pipe(\n Effect.flatMap(\n Option.match({\n onSome: Effect.succeed,\n onNone: () => Effect.provide(ContextCompactor, ContextCompactor.layer),\n }),\n ),\n );\n\n const initialToolSelection =\n options.toolSelection ??\n (agent.definition.toolExposure === undefined\n ? undefined\n : { toolNames: agent.definition.toolExposure.initialToolNames ?? [] });\n\n const updateSchema = agent.definition.updates;\n const updateContext = yield* Effect.context<(UpdatesSchema & {})[\"DecodingServices\"]>();\n\n const validateUpdate =\n updateSchema === undefined\n ? () => Effect.fail(new UpdateError({ reason: \"unavailable\" }))\n : (value: Schema.Json) =>\n Schema.decodeEffect(updateSchema)(value).pipe(\n Effect.provide(updateContext),\n Effect.asVoid,\n Effect.mapError(() => new UpdateError({ reason: \"validation\" })),\n );\n\n const context: RunContext = {\n validateUpdate,\n updates: new Map(),\n updateBytes: 0,\n updatePermits: yield* Semaphore.make(1),\n definition: agent.definition,\n toolSelection:\n initialToolSelection === undefined\n ? undefined\n : yield* decodeSelection(initialToolSelection),\n toolCatalog: [],\n toolExposure: undefined,\n toolSchemaTransformer: undefined,\n agentId: agent.definition.id,\n threadId,\n runId,\n toolFailureObserver: yield* CurrentToolFailureObserver,\n input: undefined,\n pendingFollowUps: [],\n startedAtMillis,\n durationDeadlineMillis,\n history: options.history ?? Prompt.empty,\n // RUN-019: a resumed Attempt re-seeds cumulative usage from the\n // canonical response records so token budgets and the compaction\n // trigger keep accounting across ownership changes.\n modelCalls: resumeUsage?.modelCalls ?? 0,\n usageStatus:\n resumeUsage?.usageStatus ?? (resumeUsage === undefined ? \"complete\" : \"unknown\"),\n pricingStatus:\n resumeUsage?.pricingStatus ?? (resumeUsage === undefined ? \"complete\" : \"unknown\"),\n unobservedModelCalls: resumeUsage?.unobservedModelCalls ?? 0,\n childUsage: new Map(\n (resumeUsage?.children ?? []).map((child) => [\n child.runId,\n Effect.succeed(child.report),\n ]),\n ),\n liveChildren: new Set(),\n consecutiveToolFailures: resumeUsage?.consecutiveToolFailures ?? 0,\n inputTokens: resumeUsage?.inputTokens ?? 0,\n outputTokens: resumeUsage?.outputTokens ?? 0,\n lastInputTokens: resumeUsage?.lastInputTokens ?? 0,\n lastOutputTokens: resumeUsage?.lastOutputTokens ?? 0,\n costMicrousd: resumeUsage?.costMicrousd ?? 0,\n lastCostMicrousd: 0,\n warnedLimits: new Set(),\n finalizing: false,\n tokenExhausted: false,\n exhaustedDimension: undefined,\n compaction: initialCompactionState(),\n preparedCompactionSource: undefined,\n compactionTurn: { turn: 0, summaryCalls: 0, applied: new Set() },\n windowId: options.initialContextWindowId ?? contextWindowId(runId, 0),\n windowTokens: resumeUsage?.lastInputTokens ?? 0,\n windowContextTokenLimit: agent.definition.policy.contextTokenLimit,\n pendingContextToolCallId: options.pendingContextToolCallId,\n bufferLimits: effectiveRunBufferLimits(options.bufferLimits),\n sequence: 0,\n toolProgressBytes: 0,\n programmaticToolCalls: resumeUsage?.programmaticToolCalls ?? 0,\n finalizationUsed: resumeUsage?.finalizationUsed ?? false,\n policyReservations: yield* Semaphore.make(1),\n };\n\n onUsage?.(usageReportOf(context));\n\n // Restored totals can already breach the token budget (runtime spec §9):\n // the resumed Attempt must never issue an unconstrained external call.\n // \"fail\" rejects before any model call or resumed handler runs.\n if (resumeUsage !== undefined) {\n const bounds = effectiveRunBounds(agent.definition.policy, options);\n\n if (context.finalizationUsed) {\n context.exhaustedDimension =\n resumeUsage.committedTurns > bounds.maxTurns\n ? \"turns\"\n : resumeUsage.toolCalls + context.programmaticToolCalls > bounds.maxToolCalls\n ? \"tool-calls\"\n : \"tokens\";\n }\n if (\n agent.definition.policy.onExhaustion === \"fail\" &&\n resumeUsage.toolCalls + context.programmaticToolCalls > bounds.maxToolCalls\n ) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"tool-calls\",\n message: `Agent exceeded its ${bounds.maxToolCalls} Tool Call limit`,\n }),\n );\n }\n const failureLimit = agent.definition.policy.repeatedFailureLimit;\n\n if (failureLimit > 0 && context.consecutiveToolFailures >= failureLimit) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"repeated-failures\",\n message: `Agent reached its ${failureLimit} consecutive Tool Call failure limit`,\n }),\n );\n }\n // Cost is an unconditional hard rail with no grace call in either\n // exhaustion mode (runtime spec §3): a resume whose seeded spend\n // already breaches the budget rejects before input, resumed\n // handlers, or any external model execution.\n const seededCostBudget = agent.definition.policy.costBudgetMicrousd;\n\n if (seededCostBudget !== undefined && context.costMicrousd > seededCostBudget) {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"cost\",\n message: `Agent exceeded its ${seededCostBudget} microdollar cost budget`,\n }),\n );\n }\n const seededBudget = agent.definition.policy.tokenBudget;\n\n if (\n seededBudget !== undefined &&\n context.inputTokens + context.outputTokens > seededBudget\n ) {\n if (agent.definition.policy.onExhaustion === \"fail\") {\n return failRunEventStream(\n AgentPolicyError.make({\n limit: \"tokens\",\n message: `Agent exceeded its ${seededBudget} token budget`,\n }),\n );\n }\n context.tokenExhausted = true;\n context.exhaustedDimension ??= \"tokens\";\n }\n }\n if (options.input?.start !== undefined) {\n yield* options.input.start();\n }\n\n const started = Stream.fromEffect(\n Effect.gen(function* () {\n yield* Metric.update(runCounter, 1);\n yield* Effect.logDebug(\"agent run started\").pipe(\n Effect.annotateLogs({\n agentId: context.agentId,\n runId: context.runId,\n }),\n );\n\n return yield* eventBase(context).pipe(Effect.map((base) => RunStarted.make(base)));\n }).pipe(Effect.withLogSpan(\"AgentRuntime.run\")),\n );\n\n const execution = Stream.unwrap(\n Effect.gen(function* () {\n const initial = yield* Effect.gen(function* () {\n if (options.retainedInput !== undefined) {\n const encodedInput = yield* Schema.decodeEffect(Schema.Json)(\n options.retainedInput,\n ).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({\n message: `Invalid retained Agent input: ${cause.message}`,\n }),\n ),\n );\n\n const source = agent.definition.instructions;\n\n const instructions =\n typeof source === \"function\"\n ? yield* evaluateInstructions<\n InputSchema[\"Type\"],\n InstructionError,\n InstructionRequirements\n >(source, yield* decodeInput(agent, encodedInput))\n : yield* evaluateInstructions<\n undefined,\n InstructionError,\n InstructionRequirements\n >(source, undefined);\n\n return {\n instructions,\n encodedInput,\n inputPrompt: yield* renderInputPrompt(undefined, undefined, encodedInput),\n };\n }\n const decodedInput = yield* decodeInput(agent, input);\n\n const instructions = yield* evaluateInstructions<\n InputSchema[\"Type\"],\n InstructionError,\n InstructionRequirements\n >(agent.definition.instructions, decodedInput);\n\n const encodedInput = yield* encodeInput(agent, decodedInput);\n\n return {\n instructions,\n encodedInput,\n inputPrompt:\n options.frameworkMessage === undefined\n ? yield* renderInputPrompt(\n agent.definition.inputPrompt,\n decodedInput,\n encodedInput,\n )\n : undefined,\n };\n });\n\n const { instructions, encodedInput } = initial;\n\n context.input = encodedInput;\n if (retained !== undefined) yield* retained.stageInput(encodedInput);\n\n const inputPrompt =\n options.frameworkMessage === undefined\n ? (initial.inputPrompt ?? \"\")\n : yield* Schema.encodeEffect(Schema.fromJsonString(FrameworkMessage))(\n options.frameworkMessage,\n ).pipe(\n Effect.mapError(() =>\n AgentInputError.make({ message: \"Invalid worker message\" }),\n ),\n );\n\n const priorHistoryLength = context.history.content.length;\n const prompt = yield* makeInitialPrompt(instructions, inputPrompt, context.history);\n\n // Ordinary history keeps stable indices. Prepared history must map\n // an owned copy of this block before applying compaction coverage.\n if (options.context === undefined) {\n context.compaction.protectedStart = priorHistoryLength;\n context.compaction.protectedEnd = prompt.content.length;\n } else {\n const currentPrefix = prompt.content.slice(priorHistoryLength);\n\n const protectedMessages =\n options.protectedContext === undefined\n ? currentPrefix\n : [\n ...currentPrefix.filter((message) => message.role === \"system\"),\n ...options.protectedContext.content.filter(\n (message) => message.role !== \"system\",\n ),\n ];\n\n context.preparedCompactionSource = {\n protectedReferences: protectedMessages,\n protectedMessages: yield* snapshotCompactionMessages(protectedMessages),\n prefix: [],\n };\n }\n yield* advanceHistory(context, prompt, options);\n\n let pending:\n | {\n readonly prompt: Prompt.Prompt;\n readonly turn: number;\n readonly toolCalls: number;\n readonly resume?: RunTurnResume;\n }\n | undefined;\n\n if (resumed !== undefined) {\n // A declared-batch resume re-enters mid-Turn: steering seams\n // reopen only after the resumed batch settles, so the initial\n // drain is skipped and the continuation drains at the safe seam.\n pending = {\n prompt,\n turn: resumed.batch.turn,\n toolCalls: resumed.usage.toolCalls,\n resume: resumed.batch,\n };\n } else {\n const steering = yield* drainInputs(context, options);\n const initialPrompt = yield* appendInputs(context, prompt, steering, options);\n\n pending = {\n prompt: initialPrompt,\n turn: (resumeUsage?.committedTurns ?? 0) + 1,\n toolCalls: resumeUsage?.toolCalls ?? 0,\n };\n }\n\n // Each finite Turn returns at most one successor request. Sequential\n // flatMap releases its child pull and Scope before taking that\n // request, so prior traces and prepared prompts do not remain\n // reachable through recursively nested Stream.concat descriptions.\n return Stream.fromEffectRepeat(\n Effect.suspend(() => {\n const current = pending;\n\n pending = undefined;\n\n return current === undefined ? Cause.done() : Effect.succeed(current);\n }),\n ).pipe(\n Stream.flatMap((request) =>\n request.resume === undefined\n ? makeTurn(\n agent,\n context,\n request.prompt,\n request.turn,\n request.toolCalls,\n options,\n )\n : makeResumeTurn(\n agent,\n context,\n request.prompt,\n request.resume,\n request.toolCalls,\n options,\n ),\n ),\n Stream.filterMapEffect((output) =>\n Effect.sync(() => {\n if (output._tag === \"NextTurn\") {\n pending = output;\n\n return Result.fail(undefined);\n }\n\n return Result.succeed(output);\n }),\n ),\n );\n }),\n );\n\n const durationLimit = durationLimitError(agent.definition.policy);\n\n const deadline = enforceDurationDeadline(\n execution,\n durationDeadlineMillis,\n durationLimit,\n );\n\n // Engine-provided Tool services for this Run: a real `AgentSpawner`\n // bound to the Run's immutable identity and delegation depth, plus the\n // fail-closed `RunEventSink` and `DurableStep` defaults that each Tool\n // batch shadows with per-batch / per-call live services. Providing them\n // here is what removes these services from the runtime's public\n // requirements.\n const nativeUpdateTool = agent.definition.toolkit.tools.emit_update;\n\n const updateHandlers =\n agent.definition.updates === undefined || nativeUpdateTool === undefined\n ? Context.empty()\n : yield* Toolkit.make(nativeUpdateTool).toHandlers({\n emit_update: (parameters: unknown, call: Toolkit.HandlerContext<Tool.Any>) =>\n Effect.gen(function* () {\n if (call.toolCallId === undefined)\n return yield* new UpdateError({ reason: \"unavailable\" });\n\n const decoded = yield* Schema.decodeUnknownEffect(\n Schema.Struct({ value: Schema.Unknown }),\n )(parameters).pipe(\n Effect.mapError(() => new UpdateError({ reason: \"validation\" })),\n );\n\n const value = yield* Schema.encodeUnknownEffect(agent.definition.updates!)(\n decoded.value,\n ).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Json)),\n Effect.mapError(() => new UpdateError({ reason: \"validation\" })),\n );\n\n const updateId = yield* Schema.decodeEffect(IdempotencyKey)(\n `tool:${context.runId}:${call.toolCallId}`,\n ).pipe(Effect.mapError(() => new UpdateError({ reason: \"validation\" })));\n\n const emitter = yield* Emitter;\n\n yield* emitter.emit({ target: agent.definition, updateId, value });\n }),\n });\n\n const engineToolServices = Context.make(\n AgentSpawner,\n makeAgentSpawner(\n {\n agentId: context.agentId,\n threadId: context.threadId,\n runId: context.runId,\n },\n options.delegationDepth ?? options.parentLink?.depth ?? 0,\n history,\n preparation,\n agent.definition.policy,\n options.subagentGrant,\n options.subagentBudget,\n options.subagentBudgetScope,\n (childRunId, read) => {\n context.liveChildren.add(childRunId);\n context.childUsage.set(childRunId, read);\n },\n ),\n ).pipe(\n Context.add(ContextWindow, {\n status: Effect.sync(() => {\n const estimatedTokens = Math.min(\n Number.MAX_SAFE_INTEGER,\n context.windowTokens + context.lastOutputTokens,\n );\n\n const contextTokenLimit = context.windowContextTokenLimit ?? null;\n\n return ContextWindowStatus.make({\n threadId: context.threadId,\n runId: context.runId,\n windowId: context.windowId,\n estimatedTokens,\n contextTokenLimit,\n remainingTokens:\n contextTokenLimit === null\n ? null\n : Math.max(0, contextTokenLimit - estimatedTokens),\n });\n }),\n }),\n Context.merge(updateHandlers),\n Context.add(Emitter, {\n emit: () => Effect.fail(new UpdateError({ reason: \"unavailable\" })),\n }),\n Context.add(CurrentToolCatalog, { entries: [] }),\n Context.add(RunToolVisibility, visibility),\n Context.add(RunEventSink, closedRunEventSink),\n Context.add(DurableStep, closedDurableStep),\n Context.add(SubagentDurability, closedSubagentDurability),\n Context.add(SubagentHost, SubagentHost.unavailable),\n Context.add(MessagingHost, MessagingHost.unavailable),\n Context.add(\n CurrentSubagentAuthority,\n options.subagentGrant === undefined\n ? undefined\n : {\n grant: options.subagentGrant,\n depth: options.delegationDepth ?? options.parentLink?.depth ?? 0,\n },\n ),\n Context.add(ToolBroker, closedToolBroker),\n );\n\n return started.pipe(\n Stream.concat(deadline),\n Stream.catch((error) => {\n const terminal = Stream.fromEffect(\n Effect.gen(function* () {\n if (error instanceof AgentApprovalPending || error instanceof AgentChildPending) {\n return RunSuspended.make({\n ...(yield* terminalEventBase(context)),\n reason: error.message,\n ...(yield* usageReportOf(context)),\n });\n }\n\n return RunFailed.make({\n ...(yield* terminalEventBase(context)),\n ...(yield* usageReportOf(context)),\n errorTag: errorTag(error),\n message: errorMessage(error),\n });\n }),\n );\n\n return terminal.pipe(Stream.concat(Stream.fail(error)));\n }),\n Stream.withSpan(`invoke_agent ${context.agentId}`, {\n attributes: {\n ...agentTelemetryAttributes(context),\n \"gen_ai.operation.name\": \"invoke_agent\",\n agentId: context.agentId,\n threadId: context.threadId,\n runId: context.runId,\n },\n }),\n Stream.provide(engineToolServices),\n Stream.provideService(ContextCompactor, compactor),\n );\n }),\n );\n\n const finalized =\n options.input?.end === undefined\n ? interpreted\n : interpreted.pipe(Stream.ensuring(options.input.end()));\n\n const modeled: Stream.Stream<\n RunEvent,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | AgentRuntimeRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | ToolSpanTelemetry\n | ProgrammaticToolAuthorization\n | ModelRequires\n | ModelUsageAccounting\n | AgentUpdateAcceptance\n > = model === undefined ? finalized : finalized.pipe(Stream.provide(model, { local: true }));\n\n const events = modeled.pipe(\n // The engine composition boundary owns span-lifecycle isolation while preserving the host's\n // ambient Tracer/Logger configuration. Individual Tool executions consume this capability.\n Stream.provide(ToolSpanTelemetry.layer),\n Stream.provide(programmaticAuthorization),\n );\n\n if (retained === undefined && onCompleted === undefined) return events;\n let completed: RunCompleted | undefined;\n\n return events.pipe(\n Stream.filter((event) => {\n if (event._tag !== \"RunCompleted\") return true;\n completed = event;\n\n return false;\n }),\n // Finish run-owned work and close its acquired resources before result validation,\n // history commit, and observable completion. Services supplied by an enclosing\n // application Layer keep that application's Scope, even when the model consumes them.\n Stream.scoped,\n Stream.concat(\n Stream.unwrap(\n Effect.gen(function* () {\n const terminal = completed;\n\n if (terminal === undefined) {\n return yield* ModelProtocolError.make({\n message: \"Agent stream ended without RunCompleted\",\n });\n }\n\n return Stream.fromEffect(\n Effect.gen(function* () {\n if (onCompleted !== undefined) yield* onCompleted(terminal);\n if (retained !== undefined) yield* retained.commit(terminal);\n\n return terminal;\n }),\n ).pipe(\n Stream.catch((error) =>\n Stream.make(\n RunFailed.make({\n eventVersion: terminal.eventVersion,\n threadId: terminal.threadId,\n runId: terminal.runId,\n agentId: terminal.agentId,\n usage: terminal.usage,\n delegatedUsage: terminal.delegatedUsage,\n sequence: terminal.sequence,\n timestamp: terminal.timestamp,\n errorTag: errorTag(error),\n message: errorMessage(error),\n }),\n ).pipe(Stream.concat(Stream.fail(error))),\n ),\n );\n }),\n ),\n ),\n );\n }),\n );\n}\n\ntype CompletionValidator<A extends Agent.Any> = (\n completed: RunCompleted,\n) => Effect.Effect<\n void,\n ModelProtocolError | AgentOutputError | Agent.RunDispositionFailure<A>,\n Agent.OutputSchema<A>[\"DecodingServices\"] | Agent.RunDispositionSchema<A>[\"DecodingServices\"]\n>;\n\n/** Validate the terminal result before the stream commits history and publishes completion. */\nconst reduceRunEvents = <AgentValue extends Agent.Any, Error, Requirements>(\n agent: AgentValue,\n events: (\n onCompleted: (\n completed: RunCompleted,\n ) => Effect.Effect<\n void,\n ModelProtocolError | AgentOutputError | Agent.RunDispositionFailure<AgentValue>,\n | AgentValue[\"definition\"][\"output\"][\"DecodingServices\"]\n | Agent.RunDispositionSchema<AgentValue>[\"DecodingServices\"]\n >,\n ) => Stream.Stream<RunEvent, Error, Requirements>,\n): Effect.Effect<\n AgentResult<Agent.Output<AgentValue>>,\n Error | ModelProtocolError | AgentOutputError | Agent.RunDispositionFailure<AgentValue>,\n | Requirements\n | Agent.OutputSchema<AgentValue>[\"DecodingServices\"]\n | Agent.RunDispositionSchema<AgentValue>[\"DecodingServices\"]\n> =>\n Effect.gen(function* () {\n let result: AgentResult<Agent.Output<AgentValue>> | undefined;\n\n yield* Stream.runDrain(\n events((completed) =>\n Effect.gen(function* () {\n const candidateOutput: unknown = completed.output;\n\n const output = yield* Schema.decodeUnknownEffect(agent.definition.output)(\n candidateOutput,\n ).pipe(\n Effect.mapError((cause) =>\n AgentOutputError.make({\n message: cause.message,\n }),\n ),\n );\n\n const declaration = agent.definition.runDisposition;\n\n const runDisposition =\n completed.runDisposition === undefined\n ? undefined\n : completed.finishReason === \"budget-exhausted\"\n ? yield* ModelProtocolError.make({\n message:\n \"A budget-exhausted RunCompleted event cannot declare a run disposition\",\n })\n : declaration === undefined\n ? yield* ModelProtocolError.make({\n message:\n \"RunCompleted declared a run disposition without a definition-owned Schema\",\n })\n : yield* decodeRunDisposition(agent, completed.runDisposition);\n\n result = {\n output,\n threadId: completed.threadId,\n runId: completed.runId,\n turns: completed.turns,\n finishReason: completed.finishReason,\n ...(completed.exhausted !== undefined ? { exhausted: completed.exhausted } : {}),\n ...(runDisposition === undefined ? {} : { runDisposition: completed.runDisposition }),\n ...(completed.usage === undefined ? {} : { usage: completed.usage }),\n ...(completed.delegatedUsage === undefined\n ? {}\n : { delegatedUsage: completed.delegatedUsage }),\n };\n }),\n ),\n );\n if (result === undefined) {\n return yield* ModelProtocolError.make({ message: \"Agent stream ended without RunCompleted\" });\n }\n\n return result;\n });\n\n/**\n * Complete execution and close run-owned resources before returning the decoded result.\n * Caller-contributed requirements, including Scope, remain visible; services supplied by\n * application Layers retain their application's lifetime.\n */\nconst runProgram = Effect.fn(\"AgentRuntime.run\")(function* <A extends Agent.Any, E, R>(\n agent: A,\n events: (onCompleted: CompletionValidator<A>) => Stream.Stream<RunEvent, E, R>,\n) {\n return yield* reduceRunEvents(agent, events);\n});\n\n/**\n * Scoped detached execution whose observers cannot backpressure Run\n * completion.\n *\n * `observe` is a live multicast subscription: each subscription replays every\n * event the Run has already emitted, follows subsequent events as they occur,\n * and ends once the Run settles. The finite Run event ceiling sizes the replay\n * buffer so events are never dropped for a slow subscriber and publishing\n * never blocks the Run. `events` remains the complete bounded replay,\n * available after settlement. Both belong to the `start` Scope; observing\n * after that Scope closes interrupts the observer.\n */\nexport interface DetachedRun<Output, Error> {\n readonly await: Effect.Effect<AgentResult<Output>, Error>;\n readonly events: Effect.Effect<ReadonlyArray<RunEvent>>;\n readonly observe: Stream.Stream<RunEvent>;\n /** Snapshot of observed usage, also available after failure, defect, or interruption. Read after\n * await settles (or the owning Scope closes) for a final report. In-flight work may be unpriced. */\n readonly usageReport: Effect.Effect<RunUsageReport>;\n}\n\nconst startProgram = Effect.fn(\"AgentRuntime.start\")(function* <A extends Agent.Any, E, R, H, HR>(\n agent: A,\n events: (\n options: RunOptions<H, HR>,\n onCompleted: CompletionValidator<A>,\n onUsage: (read: Effect.Effect<RunUsageReport>) => void,\n ) => Stream.Stream<RunEvent, E, R>,\n options: RunOptions<H, HR>,\n) {\n yield* Scope.Scope;\n const bufferLimits = Object.freeze(effectiveRunBufferLimits(options.bufferLimits));\n\n const executionOptionDescriptors: PropertyDescriptorMap = {\n ...Object.getOwnPropertyDescriptors(options),\n bufferLimits: {\n configurable: false,\n enumerable: true,\n value: bufferLimits,\n writable: false,\n },\n };\n\n const executionOptions: RunOptions<H, HR> = Object.create(\n Object.getPrototypeOf(options),\n executionOptionDescriptors,\n );\n\n // Single-writer append-only trace owned by the Run fiber; readers only see\n // it after the fiber settles. `stream` admits at most `maxRunEvents`, so this\n // array has the same finite ceiling without per-event immutable copies.\n const captured: Array<RunEvent> = [];\n // One extra slot carries the terminal `Exit.void` Take after the bounded Run\n // event trace. Dropping is non-blocking, while the capacity proof means the\n // strategy never drops a valid event or the terminal marker.\n const observationCapacity = bufferLimits.maxRunEvents + 1;\n\n const pubsub = yield* PubSub.dropping<Take.Take<RunEvent>>({\n capacity: observationCapacity,\n replay: observationCapacity,\n });\n\n yield* Effect.addFinalizer(() => PubSub.shutdown(pubsub));\n\n let readUsage = Effect.succeed(\n RunUsageReport.make({ usage: emptyRunTotals(), delegatedUsage: emptyRunTotals() }),\n );\n\n const execution = reduceRunEvents(agent, (onCompleted) =>\n events(executionOptions, onCompleted, (read) => {\n readUsage = read;\n }).pipe(\n Stream.tap((event) =>\n Effect.suspend(() => {\n captured.push(event);\n\n return PubSub.publish(pubsub, [event]);\n }),\n ),\n ),\n ).pipe(\n Effect.onExit(() =>\n Effect.suspend(() => readUsage).pipe(\n Effect.flatMap((report) =>\n Effect.sync(() => {\n readUsage = Effect.succeed(report);\n }),\n ),\n ),\n ),\n Effect.ensuring(PubSub.publish(pubsub, Exit.void)),\n );\n\n const fiber = yield* execution.pipe(Effect.forkScoped);\n\n return {\n await: Fiber.join(fiber),\n events: Fiber.await(fiber).pipe(Effect.andThen(Effect.sync(() => captured.slice()))),\n observe: Stream.fromPubSubTake(pubsub),\n usageReport: Effect.suspend(() => readUsage),\n };\n});\n\n/** Executable definitions or explicit per-agent model Layers for registration and delegation. */\ntype ExecutableDefinition = Agent.AnyDefinition & {\n readonly instructions: InstructionSource<never, unknown, unknown>;\n};\ntype ExecutableAgent =\n | ExecutableDefinition\n | {\n readonly definition: ExecutableDefinition;\n readonly model: Layer.Layer<\n LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName,\n never,\n unknown\n >;\n };\n\n/** Decode external input before instructions or model execution. */\nconst streamUnknown = <A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: unknown,\n options?: RunOptions<H, R>,\n): Stream.Stream<RunEvent, AgentRuntimeFailure<A, H>, AgentRuntimeRequirements<A, R>> =>\n streamWithCompletion(agent, input, options).pipe(\n Stream.provide(\n Layer.mergeAll(ModelUsageAccounting.layerEphemeral, AgentUpdateAcceptance.layerEphemeral),\n ),\n );\n\n/**\n * Host interpreter entry point with Attempt-local usage accounting and update acceptance in R.\n * Durable coordinators provide these services alongside their recovery hooks;\n * ordinary callers use streamUnknown's explicit ephemeral composition.\n */\nconst streamWithUsageAccountingUnknown = <A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: unknown,\n options?: RunOptions<H, R>,\n): Stream.Stream<\n RunEvent,\n AgentRuntimeFailure<A, H>,\n AgentRuntimeRequirements<A, R> | ModelUsageAccounting | AgentUpdateAcceptance\n> => streamWithCompletion(agent, input, options);\n\n/** Accept schema-encoded input, retaining runtime validation. Use streamUnknown for external data. */\nconst stream = <A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: NoInfer<Agent.EncodedInput<A>>,\n options?: RunOptions<H, R>,\n): Stream.Stream<RunEvent, AgentRuntimeFailure<A, H>, AgentRuntimeRequirements<A, R>> =>\n streamUnknown(agent, input, options);\n\n/** Decode external input before instructions or model execution. */\nfunction runUnknown<A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: unknown,\n options?: RunOptions<H, R>,\n): Effect.Effect<\n AgentResult<Agent.Output<A>>,\n AgentRuntimeFailure<A, H>,\n AgentRuntimeRequirements<A, R>\n>;\nfunction runUnknown<H = never, R = never>(\n agent: ExecutableAgent,\n input: unknown,\n options: RunOptions<H, R> = {},\n) {\n const program = \"definition\" in agent ? agent : { definition: agent };\n\n return runProgram(program, (onCompleted) =>\n streamWithCompletion(agent, input, options, onCompleted).pipe(\n Stream.provide(\n Layer.mergeAll(ModelUsageAccounting.layerEphemeral, AgentUpdateAcceptance.layerEphemeral),\n ),\n ),\n );\n}\n\n/** Accept schema-encoded input, retaining runtime validation. Use runUnknown for external data. */\nconst run = <A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: NoInfer<Agent.EncodedInput<A>>,\n options?: RunOptions<H, R>,\n): Effect.Effect<\n AgentResult<Agent.Output<A>>,\n AgentRuntimeFailure<A, H>,\n AgentRuntimeRequirements<A, R>\n> => runUnknown(agent, input, options);\n\n/** Decode external input before instructions or model execution. */\nfunction startUnknown<A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: unknown,\n options?: RunOptions<H, R>,\n): Effect.Effect<\n DetachedRun<Agent.Output<A>, AgentRuntimeFailure<A, H>>,\n never,\n AgentRuntimeRequirements<A, R> | Scope.Scope\n>;\nfunction startUnknown<H = never, R = never>(\n agent: ExecutableAgent,\n input: unknown,\n options: RunOptions<H, R> = {},\n) {\n const program = \"definition\" in agent ? agent : { definition: agent };\n\n return startProgram(\n program,\n (executionOptions, onCompleted, onUsage) =>\n streamWithCompletion(agent, input, executionOptions, onCompleted, onUsage).pipe(\n Stream.provide(\n Layer.mergeAll(ModelUsageAccounting.layerEphemeral, AgentUpdateAcceptance.layerEphemeral),\n ),\n ),\n options,\n );\n}\n\n/** Accept schema-encoded input, retaining runtime validation. Use startUnknown for external data. */\nconst start = <A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: NoInfer<Agent.EncodedInput<A>>,\n options?: RunOptions<H, R>,\n): Effect.Effect<\n DetachedRun<Agent.Output<A>, AgentRuntimeFailure<A, H>>,\n never,\n AgentRuntimeRequirements<A, R> | Scope.Scope\n> => startUnknown(agent, input, options);\n\n/**\n * Immutable parent Run identity carried by the locally provided\n * `AgentSpawner`. It exposes no mutable engine state and no Layer Context.\n */\nexport interface AgentSpawnerParent {\n readonly agentId: AgentId;\n readonly threadId: ThreadId;\n readonly runId: RunId;\n}\n\n/**\n * Fail-closed Run-level `RunEventSink` default. Each Tool batch shadows it\n * with a live sink; any emission outside an active Tool batch fails with the\n * same typed error as emitting after a batch settled.\n */\nconst closedRunEventSink: RunEventSinkService = {\n emit: (payload) =>\n Effect.fail(\n RunEventSinkClosedError.make({\n message: `Subagent event ${payload._tag} was emitted outside an active Tool batch`,\n }),\n ),\n};\n\n/**\n * Fail-closed Run-level `DurableStep` default. Every executable Tool Call\n * shadows it with a live per-call service; a Step executed outside an active\n * Tool Call fails typed instead of silently running unrecorded.\n */\nconst closedDurableStep: DurableStepService = {\n do: (name) =>\n Effect.fail(\n DurableStepError.make({\n stepName: name,\n reason: \"no-active-tool-call\",\n message: \"Durable Step was executed outside an active Tool Call\",\n }),\n ),\n};\n\n/**\n * Fail-closed Run-level `ToolBroker` default. Every executable Tool Call\n * shadows it with a live per-call service bound to that call's identity and\n * held permit; opening a pass outside an active Tool Call fails typed.\n */\nconst closedToolBroker: ToolBrokerService = {\n openPass: () =>\n Effect.fail(\n ToolBrokerUnavailableError.make({\n message: \"The programmatic Tool broker was used outside an active Tool Call\",\n }),\n ),\n};\n\n/** Everything a live broker pass is bound to at its outer Tool Call. */\ninterface ToolBrokerBinding<HookError, HookRequirements> {\n readonly context: RunContext;\n readonly turnId: TurnId;\n readonly outerToolCallId: ToolCallId;\n readonly turn: number;\n readonly maxToolCalls: number;\n /** Model-declared Tool Calls committed through this batch (the outer call included). */\n readonly declaredToolCalls: number;\n readonly budget: RunOptions<HookError, HookRequirements>[\"budget\"];\n readonly reservePolicyUsage: RunDurabilityHook<HookError, HookRequirements>[\"reservePolicyUsage\"];\n readonly hookServices: Context.Context<HookRequirements>;\n}\n\nconst programmaticOutcomeError = (\n index: number | undefined,\n tag: string,\n message: string,\n): ProgrammaticCallOutcome => ({\n _tag: \"ProgrammaticCallError\",\n index,\n errorTag: tag,\n message,\n});\n\n/** A call's typed failure captured as a value so defects stay defects. */\nclass BrokerCallFailure {\n constructor(\n readonly error: unknown,\n readonly cause: Cause.Cause<unknown>,\n ) {}\n}\n\n/** Run-owned authorization with typed override failures preserved for broker projection. */\nclass ProgrammaticToolAuthorization extends Context.Service<\n ProgrammaticToolAuthorization,\n RunToolAuthorizationHook<BrokerCallFailure>\n>()(\"@effect-agent/engine/internal/ProgrammaticToolAuthorization\") {}\n\n/**\n * Measure one started programmatic handler with the same canonical span semantics as a\n * model-declared handler. A private marker gives value-level failures a failed exported status;\n * the marker is removed before the broker outcome returns, while an original Effect Cause is\n * restored unchanged outside the span.\n */\nconst stripProgrammaticToolSpanFailure = (\n cause: Cause.Cause<ToolSpanFailure>,\n marker: ToolSpanFailure,\n): { readonly found: boolean; readonly residual: Cause.Cause<never> } => {\n let found = false;\n const residual: Array<Cause.Reason<never>> = [];\n\n for (const reason of cause.reasons) {\n if (Cause.isFailReason(reason)) {\n if (reason.error === marker) {\n found = true;\n } else {\n // This Effect's only typed failure is its fresh marker. Preserve a future invariant break\n // as a defect instead of consuming an unauthenticated same-class value.\n residual.push(Cause.makeDieReason(reason.error));\n }\n } else {\n residual.push(reason);\n }\n }\n\n return { found, residual: Cause.fromReasons(residual) };\n};\n\nconst measureProgrammaticToolCall = <R>(\n telemetry: ToolSpanTelemetryService,\n descriptor: ToolTelemetryDescriptor,\n effect: Effect.Effect<ProgrammaticCallOutcome, never, R>,\n): Effect.Effect<ProgrammaticCallOutcome, never, R> =>\n Effect.suspend(() => {\n const marker = ToolSpanFailure.marker();\n let terminalResult: ProgrammaticCallOutcome | undefined;\n let propagatedFailure: Cause.Cause<never> | undefined;\n\n const measured: Effect.Effect<ProgrammaticCallOutcome, ToolSpanFailure, R> = Effect.exit(\n effect,\n ).pipe(\n Effect.flatMap((exit): Effect.Effect<ProgrammaticCallOutcome, ToolSpanFailure> => {\n if (Exit.isFailure(exit)) {\n if (exit.cause.reasons.length > 0 && exit.cause.reasons.every(Cause.isInterruptReason)) {\n return Effect.failCause(exit.cause);\n }\n propagatedFailure = exit.cause;\n\n return isolateToolDerivative(\n terminalToolTelemetry(descriptor, \"failure\", marker, \"propagated\"),\n ).pipe(Effect.andThen(Effect.fail(marker)));\n }\n\n terminalResult = exit.value;\n\n const outcome: ToolTelemetryOutcome =\n exit.value._tag === \"ProgrammaticCallSuccess\" ? \"success\" : \"failure\";\n\n return isolateToolDerivative(\n terminalToolTelemetry(\n descriptor,\n outcome,\n outcome === \"failure\" ? marker : undefined,\n outcome === \"failure\" ? \"returned-to-caller\" : undefined,\n ),\n ).pipe(\n Effect.andThen(outcome === \"failure\" ? Effect.fail(marker) : Effect.succeed(exit.value)),\n );\n }),\n Effect.withSpan(`execute_tool ${descriptor.toolName}`, {\n kind: \"internal\",\n attributes: toolTelemetryAttributes(descriptor),\n }),\n );\n\n return telemetry.isolateEffectSpanLifecycle(measured).pipe(\n Effect.catchCause((cause) => {\n const { found, residual } = stripProgrammaticToolSpanFailure(cause, marker);\n\n const restored =\n propagatedFailure === undefined ? residual : Cause.combine(propagatedFailure, residual);\n\n if (!found) return Effect.failCause(restored);\n if (restored.reasons.length > 0) return Effect.failCause(restored);\n\n return terminalResult === undefined\n ? Effect.die(\"Programmatic Tool telemetry completed without a terminal result\")\n : Effect.succeed(terminalResult);\n }),\n );\n });\n\nconst brokerSerializeJson = (\n value: unknown,\n): { readonly text: string; readonly bytes: number } | undefined => {\n try {\n const text = JSON.stringify(value);\n\n return text === undefined ? undefined : { text, bytes: utf8ByteLength(text) };\n } catch {\n return undefined;\n }\n};\n\nconst emptyProgrammaticUsage = Response.Usage.make({ inputTokens: {}, outputTokens: {} });\n\n/** Hostile values can throw from trap getters mid-decode; stay fail-closed. */\nconst brokerDecodeJson = (value: unknown): Option.Option<Schema.Json> => {\n try {\n return Schema.decodeUnknownOption(Schema.Json)(value);\n } catch {\n return Option.none();\n }\n};\n\n/** One live broker bound to one outer Tool Call, plus its lifecycle closer. */\ninterface LiveToolBroker {\n readonly service: ToolBrokerService;\n /**\n * Marks every pass opened under this outer Tool Call closed. The batch\n * executor runs it when the call's stream settles, so a retained pass\n * cannot execute Tools outside the batch's scheduling authority.\n */\n readonly close: () => void;\n}\n\n/**\n * Live per-outer-call `ToolBroker` (runtime spec §12.1; RUN-016, RUN-017).\n * The pass executes under the outer Tool Call's already-held scheduling\n * permit — invocations run in caller-owned structured fibers and acquire a finite\n * per-pass Semaphore, never the outer batch permit again. Execution indices are\n * allocated in invocation order before preflight, with gaps for rejected calls,\n * and every started call consumes the Run's Tool-call budgets before its\n * handler is invoked. Inner calls produce no Run events and no Canonical\n * Records. Trusted applications may explicitly observe non-propagating failures (RUN-036).\n */\nconst makeToolBrokerService = Effect.fnUntraced(function* <HookError, HookRequirements>(\n binding: ToolBrokerBinding<HookError, HookRequirements>,\n): Effect.fn.Return<LiveToolBroker, never, ToolSpanTelemetry | ProgrammaticToolAuthorization> {\n const toolSpanTelemetry = yield* ToolSpanTelemetry;\n const authorization = yield* ProgrammaticToolAuthorization;\n const lifecycle = { closed: false };\n const observer = binding.context.toolFailureObserver;\n\n // Rejections consume no execution budget and may arrive concurrently, even through retained\n // passes after close. Share one reporting permit across every pass from this broker. Callers\n // wait in their own structured fibers; there is no observation queue or consumer fiber.\n const preflightObserver =\n observer === undefined ? undefined : { observer, permits: Semaphore.makeUnsafe(1) };\n\n const service: ToolBrokerService = {\n openPass: (toolkit, passOptions) =>\n Effect.gen(function* () {\n const inheritedAuthority = yield* CurrentSubagentAuthority;\n\n if (lifecycle.closed) {\n return yield* ToolBrokerUnavailableError.make({\n message: \"The outer Tool Call for this broker has already settled\",\n });\n }\n // A malformed result bound would fail open (`NaN` defeats every\n // comparison), so it is rejected typed before the pass opens.\n if (\n passOptions === undefined ||\n !Number.isSafeInteger(passOptions.maxResultBytes) ||\n passOptions.maxResultBytes <= 0\n ) {\n return yield* ToolBrokerConfigurationError.make({\n message: `maxResultBytes must be a positive safe integer; received ${String(passOptions?.maxResultBytes)}`,\n });\n }\n // Capture the handler services present at the pass edge once; nothing\n // inside business execution can substitute them per invocation. The\n // same private-assertion contract as `provideHookServices` applies.\n const handlerServices = (yield* Effect.context<never>()) as Context.Context<unknown>;\n const concurrency = passOptions.concurrency ?? 4;\n\n if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64) {\n return yield* ToolBrokerConfigurationError.make({\n message: \"concurrency must be an integer between 1 and 64\",\n });\n }\n const permits = yield* Semaphore.make(concurrency);\n const records: Array<ProgrammaticCallRecord> = [];\n\n const preflightFailure = (\n input: ProgrammaticToolInput,\n kind: \"infrastructure\" | \"protocol\",\n tag: string,\n message: string,\n cause?: Cause.Cause<unknown>,\n ): Effect.Effect<ProgrammaticCallOutcome> => {\n const outcome = programmaticOutcomeError(undefined, tag, message);\n\n if (preflightObserver === undefined) return Effect.succeed(outcome);\n\n return deliverToolFailure(preflightObserver.observer, {\n _tag: \"ProgrammaticPreflightFailure\",\n agentId: binding.context.agentId,\n threadId: binding.context.threadId,\n runId: binding.context.runId,\n turnId: binding.turnId,\n parentToolCallId: binding.outerToolCallId,\n toolName: input.toolName,\n ...(hasTool(toolkit.tools, input.toolName)\n ? { executionClass: getToolExecutionClass(toolkit.tools[input.toolName]) }\n : {}),\n kind,\n tag,\n message: toolFailureMessage(message),\n ...(cause === undefined ? {} : { cause }),\n }).pipe(preflightObserver.permits.withPermits(1), Effect.as(outcome));\n };\n\n const body = (\n input: ProgrammaticToolInput,\n sequenceIndex: number,\n ): Effect.Effect<ProgrammaticCallOutcome> =>\n Effect.gen(function* () {\n if (!hasTool(toolkit.tools, input.toolName)) {\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n \"ProgrammaticToolUnknownError\",\n `Tool ${input.toolName} is not part of this pass's allowlisted Toolkit`,\n );\n }\n const tool = toolkit.tools[input.toolName] as Tool.Any;\n\n const advertised = Object.values(binding.context.definition.toolkit.tools).some(\n (outer) =>\n Context.get(outer.annotations, AdditionalToolCatalog).some(\n (entry) => entry.tool.name === input.toolName,\n ),\n );\n\n if (\n advertised &&\n !binding.context.toolCatalog.some(\n (entry) => entry.kind === \"code-mode\" && entry.tool.name === input.toolName,\n )\n )\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n \"ProgrammaticToolAuthorizationDenied\",\n \"Tool is excluded by the current host visibility policy\",\n );\n\n if (\n !isSubagentToolAllowed(\n inheritedAuthority?.grant,\n inheritedAuthority?.depth ?? 0,\n input.toolName,\n tool.annotations,\n )\n ) {\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n \"ProgrammaticToolAuthorizationDenied\",\n \"Tool exceeds the inherited subagent grant\",\n );\n }\n\n if (Context.get(tool.annotations, ContextRolloverTool)) {\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n \"ProgrammaticContextRolloverUnsupportedError\",\n \"Context rollover requires a direct, singleton model Tool Call\",\n );\n }\n const approval = tool.needsApproval;\n\n if (approval !== undefined && approval !== false) {\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n \"ProgrammaticApprovalUnsupportedError\",\n `Tool ${input.toolName} requires approval; approval-requiring Tools never start programmatically in the ephemeral slice`,\n );\n }\n\n // Validate the encoded arguments against the owning parameter\n // Schema before the handler can start; the pinned `Toolkit.handle`\n // decodes internally, so the validated encoded form passes through\n // (the same inversion as `prepareToolCall`).\n const decodeParameters = Schema.decodeUnknownEffect(tool.parametersSchema) as (\n value: unknown,\n ) => Effect.Effect<unknown, Schema.SchemaError>;\n\n const invalidParameters = yield* decodeParameters(input.encodedArguments).pipe(\n Effect.map(() => undefined),\n Effect.catchCauseFilter(Cause.findError, (error, cause) =>\n preflightFailure(\n input,\n \"protocol\",\n \"ModelProtocolError\",\n `Invalid parameters for Tool ${input.toolName}: ${error.message}`,\n cause,\n ),\n ),\n );\n\n if (invalidParameters !== undefined) {\n return invalidParameters;\n }\n\n const handleId = ToolCallId.make(`${binding.outerToolCallId}#${sequenceIndex}`);\n\n const denied = yield* authorization\n .authorize({\n threadId: binding.context.threadId,\n runId: binding.context.runId,\n turnId: binding.turnId,\n turn: binding.turn,\n input: binding.context.input,\n programmatic: { parentToolCallId: binding.outerToolCallId, sequenceIndex },\n call: {\n toolCallId: handleId,\n toolName: input.toolName,\n parameters: input.encodedArguments,\n executionClass: getToolExecutionClass(tool),\n executionKind: getToolExecutionKind(tool.annotations),\n },\n })\n .pipe(\n Effect.flatMap((decision) =>\n decision._tag === \"allowed\"\n ? Effect.succeed(undefined)\n : preflightFailure(\n input,\n \"infrastructure\",\n \"ProgrammaticToolAuthorizationDenied\",\n decision.reason,\n ),\n ),\n Effect.catch((failure) =>\n preflightFailure(\n input,\n \"infrastructure\",\n errorTag(failure.error),\n errorMessage(failure.error),\n failure.cause,\n ),\n ),\n );\n\n if (denied !== undefined) return denied;\n\n // Serialize admission and durable reservation across outer handlers.\n // Once reserved, a slot is never refunded: ownership may be lost\n // after the append but before the Handler starts.\n const rejected = yield* binding.context.policyReservations.withPermit(\n Effect.gen(function* () {\n const used = binding.declaredToolCalls + binding.context.programmaticToolCalls;\n\n if (used + 1 > binding.maxToolCalls) {\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n \"AgentPolicyError\",\n `Agent exceeded its ${binding.maxToolCalls} Tool Call limit`,\n );\n }\n if (binding.budget !== undefined) {\n const exhausted = yield* provideHookServices(\n binding.budget.consume({\n modelCalls: 0,\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n toolCalls: 1,\n costMicrousd: 0,\n usage: emptyProgrammaticUsage,\n }),\n binding.hookServices,\n ).pipe(\n Effect.map(() => undefined),\n Effect.catchCauseFilter(Cause.findError, (error, cause) =>\n Effect.succeed({ error, cause }),\n ),\n );\n\n if (exhausted !== undefined) {\n return yield* preflightFailure(\n input,\n \"infrastructure\",\n errorTag(exhausted.error),\n errorMessage(exhausted.error),\n exhausted.cause,\n );\n }\n }\n binding.context.programmaticToolCalls += 1;\n if (binding.reservePolicyUsage !== undefined) {\n return yield* provideHookServices(\n binding.reservePolicyUsage({\n programmaticToolCalls: binding.context.programmaticToolCalls,\n finalizationUsed: binding.context.finalizationUsed,\n }),\n binding.hookServices,\n ).pipe(\n Effect.as(undefined),\n Effect.catchCauseFilter(Cause.findError, (error, cause) =>\n preflightFailure(\n input,\n \"infrastructure\",\n errorTag(error),\n errorMessage(error),\n cause,\n ),\n ),\n );\n }\n\n return undefined;\n }),\n );\n\n if (rejected !== undefined) return rejected;\n\n const index = sequenceIndex;\n\n records[sequenceIndex] = {\n sequenceIndex,\n toolName: input.toolName,\n status: \"uncertain\",\n };\n const executionClass = getToolExecutionClass(tool);\n let failureObservation: ProgrammaticToolFailure | undefined;\n\n const startedFailure = (\n kind: \"infrastructure\" | \"protocol\",\n tag: string,\n message: string,\n ): Effect.Effect<ProgrammaticCallOutcome> => {\n const outcome = programmaticOutcomeError(index, tag, message);\n\n if (observer === undefined) return Effect.succeed(outcome);\n failureObservation = {\n _tag: \"ProgrammaticToolFailure\",\n agentId: binding.context.agentId,\n threadId: binding.context.threadId,\n runId: binding.context.runId,\n turnId: binding.turnId,\n toolCallId: handleId,\n parentToolCallId: binding.outerToolCallId,\n sequenceIndex: index,\n toolName: input.toolName,\n executionClass,\n kind,\n tag,\n message: toolFailureMessage(message),\n };\n\n return Effect.succeed(outcome);\n };\n\n const telemetryDescriptor: ToolTelemetryDescriptor = {\n context: binding.context,\n turnId: binding.turnId,\n toolCallId: handleId,\n toolName: input.toolName,\n executionClass,\n invocationKind: \"programmatic\",\n failureMode: tool.failureMode,\n parentToolCallId: binding.outerToolCallId,\n sequenceIndex: index,\n };\n\n const execution = measureProgrammaticToolCall(\n toolSpanTelemetry,\n telemetryDescriptor,\n Effect.gen(function* () {\n yield* Effect.logDebug(\"agent programmatic tool handler started\").pipe(\n Effect.annotateLogs({\n agentId: binding.context.agentId,\n runId: binding.context.runId,\n turnId: binding.turnId,\n toolCallId: handleId,\n parentToolCallId: binding.outerToolCallId,\n toolName: input.toolName,\n sequenceIndex: index,\n }),\n );\n yield* Metric.update(toolCounter, 1);\n\n let terminal:\n | {\n readonly encodedResult: unknown;\n readonly isFailure: boolean;\n readonly tag: string | undefined;\n }\n | undefined;\n\n let resultAfterTerminal = false;\n\n const handlerFailed = yield* Stream.unwrap(\n toolSpanTelemetry.isolateToolkitHandle(\n (\n toolkit.handle as (\n name: string,\n params: unknown,\n id: string,\n ) => Effect.Effect<\n Stream.Stream<Tool.HandlerResult<Tool.Any>, unknown, unknown>,\n unknown,\n unknown\n >\n )(input.toolName, input.encodedArguments, handleId),\n ),\n ).pipe(\n Stream.runForEach((result) =>\n Effect.sync(() => {\n // The direct path rejects a second result after the terminal\n // one; the broker preserves that protocol violation instead\n // of silently keeping the last value.\n if (terminal !== undefined) {\n resultAfterTerminal = true;\n\n return;\n }\n if (!result.preliminary) {\n terminal = {\n encodedResult: result.encodedResult,\n isFailure: result.isFailure,\n tag:\n observer === undefined || !result.isFailure\n ? undefined\n : errorTag(result.result),\n };\n }\n }),\n ),\n Effect.map(() => undefined),\n Effect.catchCauseFilter(Cause.findError, (error, cause) =>\n Effect.succeed(new BrokerCallFailure(error, cause)),\n ),\n );\n\n if (handlerFailed instanceof BrokerCallFailure) {\n const tag = errorTag(handlerFailed.error);\n\n if (observer !== undefined) {\n failureObservation = {\n _tag: \"ProgrammaticToolFailure\",\n agentId: binding.context.agentId,\n threadId: binding.context.threadId,\n runId: binding.context.runId,\n turnId: binding.turnId,\n toolCallId: handleId,\n parentToolCallId: binding.outerToolCallId,\n sequenceIndex: index,\n toolName: input.toolName,\n executionClass,\n kind: \"handler-error\",\n tag,\n cause: handlerFailed.cause,\n };\n }\n\n return programmaticOutcomeError(index, tag, errorMessage(handlerFailed.error));\n }\n if (resultAfterTerminal) {\n return yield* startedFailure(\n \"protocol\",\n \"ModelProtocolError\",\n `Tool Call ${handleId} produced more than one terminal result`,\n );\n }\n if (terminal === undefined) {\n return yield* startedFailure(\n \"protocol\",\n \"ModelProtocolError\",\n `Tool Call ${handleId} completed without a terminal result`,\n );\n }\n if (terminal.isFailure) {\n if (observer !== undefined) {\n failureObservation = {\n _tag: \"ProgrammaticToolFailure\",\n agentId: binding.context.agentId,\n threadId: binding.context.threadId,\n runId: binding.context.runId,\n turnId: binding.turnId,\n toolCallId: handleId,\n parentToolCallId: binding.outerToolCallId,\n sequenceIndex: index,\n toolName: input.toolName,\n executionClass,\n kind: \"declared-failure\",\n tag: terminal.tag ?? \"UnknownError\",\n };\n }\n\n return {\n _tag: \"ProgrammaticCallFailure\",\n index,\n encodedResult: terminal.encodedResult,\n } as const;\n }\n if (Option.isNone(brokerDecodeJson(terminal.encodedResult))) {\n return yield* startedFailure(\n \"protocol\",\n \"ModelProtocolError\",\n `Tool ${input.toolName} produced a success encoding outside JSON`,\n );\n }\n let encodedResult = terminal.encodedResult;\n\n if (passOptions.redactResult !== undefined) {\n // A redactor is a substitution point: its replacement re-crosses\n // the JSON boundary or the call fails closed.\n const redacted = brokerDecodeJson(yield* passOptions.redactResult(encodedResult));\n\n if (Option.isNone(redacted)) {\n return yield* startedFailure(\n \"protocol\",\n \"ModelProtocolError\",\n `The redacted result for Tool ${input.toolName} is outside the JSON surface`,\n );\n }\n encodedResult = redacted.value;\n }\n const snapshot = brokerSerializeJson(encodedResult);\n\n if (snapshot === undefined || snapshot.bytes > passOptions.maxResultBytes) {\n return yield* startedFailure(\n \"infrastructure\",\n \"ProgrammaticResultLimitError\",\n `Tool ${input.toolName} result of ${snapshot?.bytes ?? \"unencodable\"} bytes exceeds the ${passOptions.maxResultBytes}-byte broker bound`,\n );\n }\n\n // Retain the exact representation admitted above. Reusing the handler or redactor\n // value would let later mutation or stateful getters escape the byte bound.\n const owned = Schema.decodeOption(Schema.fromJsonString(Schema.Json))(\n snapshot.text,\n );\n\n if (Option.isNone(owned)) {\n return yield* startedFailure(\n \"protocol\",\n \"ModelProtocolError\",\n `Tool ${input.toolName} produced a success encoding outside JSON`,\n );\n }\n\n return {\n _tag: \"ProgrammaticCallSuccess\",\n index,\n encodedResult: owned.value,\n } as const;\n }),\n );\n\n // Fix the broker outcome and terminal telemetry before delivery. Interruption of an\n // observer cannot turn a settled inner failure into an interrupted Handler attempt.\n // This still runs inline under the outer call's permit, before pass.invoke returns.\n const recorded = execution.pipe(\n Effect.tap((outcome) =>\n Effect.sync(() => {\n records[sequenceIndex] = {\n sequenceIndex,\n toolName: input.toolName,\n status:\n outcome._tag === \"ProgrammaticCallSuccess\"\n ? \"succeeded\"\n : outcome._tag === \"ProgrammaticCallFailure\"\n ? \"failed\"\n : \"uncertain\",\n ...(outcome._tag === \"ProgrammaticCallError\"\n ? { errorTag: outcome.errorTag }\n : {}),\n };\n }),\n ),\n );\n\n return yield* observer === undefined\n ? recorded\n : recorded.pipe(\n Effect.tap(() =>\n failureObservation === undefined\n ? Effect.void\n : deliverToolFailure(observer, failureObservation),\n ),\n );\n }).pipe(Effect.provideContext(handlerServices)) as Effect.Effect<ProgrammaticCallOutcome>;\n\n const pass: ToolBrokerPass = {\n snapshot: Effect.sync(() => records.map((record) => ({ ...record }))),\n invoke: (input) =>\n Effect.suspend(() => {\n const sequenceIndex = records.length;\n\n records.push({ sequenceIndex, toolName: input.toolName, status: \"not-started\" });\n\n // Check after acquiring the permit too: queued work cannot start after its owner exits.\n return permits\n .withPermit(\n Effect.suspend(() =>\n lifecycle.closed\n ? preflightFailure(\n input,\n \"infrastructure\",\n \"ToolBrokerUnavailableError\",\n \"The outer Tool Call for this pass has already settled\",\n )\n : body(input, sequenceIndex),\n ),\n )\n .pipe(\n Effect.tap((outcome) =>\n Effect.sync(() => {\n if (outcome._tag === \"ProgrammaticCallError\" && outcome.index === undefined) {\n records[sequenceIndex] = {\n sequenceIndex,\n toolName: input.toolName,\n status: \"not-started\",\n errorTag: outcome.errorTag,\n };\n }\n }),\n ),\n );\n }),\n };\n\n return pass;\n }),\n };\n\n return {\n service,\n close: () => {\n lifecycle.closed = true;\n },\n };\n});\n\n/**\n * Ephemeral pass-through `DurableStep` provided when `RunOptions.durability`\n * is absent: each Step body executes exactly once in-process and nothing is\n * recorded. Durable Tools stay runnable on the ephemeral runtime with honest\n * (weaker) semantics — the durable claim attaches to the runtime, not the\n * Tool. Duplicate Step names remain the same typed identity conflict as under\n * the durable service so authoring bugs fail identically on both runtimes.\n */\nconst passthroughDurableStep = (): DurableStepService => {\n const usedNames = new Set<string>();\n\n return {\n do: <Output extends Schema.Top, BodyError, BodyServices>(\n name: string,\n _output: Output,\n execute: Effect.Effect<Output[\"Type\"], BodyError, BodyServices>,\n ) =>\n Effect.suspend(\n (): Effect.Effect<Output[\"Type\"], DurableStepError | BodyError, BodyServices> => {\n if (usedNames.has(name)) {\n return Effect.fail(\n DurableStepError.make({\n stepName: name,\n reason: \"duplicate-step-name\",\n message: \"Durable Step name was reused within one Tool Call\",\n }),\n );\n }\n usedNames.add(name);\n\n return execute;\n },\n ),\n };\n};\n\n/**\n * Durable `DurableStep` service bound to one Tool Call over the coordinator's\n * `RunStepHook`.\n *\n * Semantics per durability §11: a committed result decodes through the\n * declared output Schema and returns without executing the body\n * (exactly-once-recorded); otherwise the body runs (at-least-once-executed —\n * a crash mid-body re-executes on the next Attempt and duplicate external\n * effects stay observable), the success is encoded through the Schema, and\n * only then committed. Failures are never recorded: a failing body fails the\n * Step call into the handler's error channel and re-entry re-executes it.\n * Step names must be deterministic and unique within one Tool Call; reuse is\n * a typed identity conflict because the second call would silently replay the\n * first call's recorded result. Hook failures and codec conflicts surface as\n * `DurableStepError` without widening the handler's error channel.\n */\n/**\n * Provide a captured hook Context to a hook effect. TypeScript cannot reduce\n * the deferred conditional `Exclude<HookRequirements, HookRequirements>` on\n * an unresolved generic, so this private assertion pins the identity that\n * providing `Context<R>` to an `Effect<_, _, R>` leaves no requirements; it\n * never bypasses validation.\n */\nconst provideHookServices = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n services: Context.Context<R>,\n): Effect.Effect<A, E> =>\n effect.pipe(Effect.provideContext(services)) as unknown as Effect.Effect<A, E>;\n\nconst makeDurableStepService = <HookError, HookRequirements>(\n toolCallId: ToolCallId,\n hook: RunStepHook<HookError, HookRequirements>,\n hookServices: Context.Context<HookRequirements>,\n): DurableStepService => {\n const usedNames = new Set<string>();\n\n return {\n do: <Output extends Schema.Top, BodyError, BodyServices>(\n name: string,\n output: Output,\n execute: Effect.Effect<Output[\"Type\"], BodyError, BodyServices>,\n ) =>\n Effect.gen(function* () {\n if (usedNames.has(name)) {\n return yield* DurableStepError.make({\n toolCallId,\n stepName: name,\n reason: \"duplicate-step-name\",\n message: \"Durable Step name was reused within one Tool Call\",\n });\n }\n usedNames.add(name);\n const key: RunStepKey = { toolCallId, stepName: name };\n\n const recorded = yield* provideHookServices(hook.lookup(key), hookServices).pipe(\n Effect.mapError((cause) =>\n DurableStepError.make({\n toolCallId,\n stepName: name,\n reason: \"lookup-failed\",\n message: \"Durable Step lookup failed\",\n cause,\n }),\n ),\n );\n\n if (Option.isSome(recorded)) {\n return yield* Schema.decodeUnknownEffect(output)(recorded.value.encodedOutput).pipe(\n Effect.mapError(() =>\n DurableStepError.make({\n toolCallId,\n stepName: name,\n reason: \"recorded-result-invalid\",\n message: \"Recorded Durable Step result failed the declared output Schema\",\n }),\n ),\n );\n }\n const value = yield* execute;\n\n const encodedOutput = yield* Schema.encodeEffect(output)(value).pipe(\n Effect.mapError(() =>\n DurableStepError.make({\n toolCallId,\n stepName: name,\n reason: \"output-encoding-failed\",\n message: \"Durable Step output failed the declared output Schema\",\n }),\n ),\n );\n\n yield* provideHookServices(hook.commit(key, encodedOutput), hookServices).pipe(\n Effect.mapError((cause) =>\n DurableStepError.make({\n toolCallId,\n stepName: name,\n reason: \"commit-failed\",\n message: \"Durable Step commit failed\",\n cause,\n }),\n ),\n );\n\n return value;\n }),\n };\n};\n\n/**\n * Typed engine-owned suspension signal raised by a delegation Tool handler\n * through the per-batch `SubagentDurability` service when its durable child\n * is established but not settled (S2 plan §2). It is NOT a Tool failure: the\n * batch executor treats the raising call as \"stays open\" — no terminal\n * result, no `ToolCallFailed`, no batch failure policy, no sibling\n * interruption — and terminates the Run with `AgentChildPending` after every\n * non-waiting sibling handler settled.\n */\nexport class ToolCallWaiting extends Schema.TaggedError<ToolCallWaiting>()(\"ToolCallWaiting\", {\n toolCallId: ToolCallId,\n childThreadId: ThreadId,\n childSubmissionId: SubmissionId,\n childRunId: RunId,\n receiptId: ReceiptId,\n message: Schema.String,\n}) {}\n\n/**\n * The Run suspended `waitingForChild`: at least one durable delegation call\n * of the last Tool batch is waiting on its attached child.\n * Mirrors `AgentApprovalPending`: the engine emits\n * `RunSuspended` and then fails the Run stream with this error; the durable\n * coordinator catches it and ends the Attempt's ownership period without\n * settling. `children` is listed in declaration order, deterministically.\n */\nexport class AgentChildPending extends Schema.TaggedError<AgentChildPending>()(\n \"AgentChildPending\",\n {\n children: Schema.NonEmptyArray(\n Schema.Struct({\n toolCallId: ToolCallId,\n childThreadId: ThreadId,\n childSubmissionId: SubmissionId,\n childRunId: RunId,\n }),\n ),\n message: Schema.String,\n },\n) {}\n\n/**\n * Typed failure of the engine-provided `SubagentDurability` operations.\n * `hook-failed` wraps a coordinator hook failure without leaking the hook's\n * error type into handler signatures (the `DurableStepError` precedent);\n * `no-active-tool-batch` is the fail-closed Run-level default — establishment\n * outside an active Tool batch never silently degrades to ephemeral spawning.\n */\nexport class SubagentDurabilityError extends Schema.TaggedError<SubagentDurabilityError>()(\n \"SubagentDurabilityError\",\n {\n operation: Schema.Literals([\"establish\", \"join\", \"waiting\"]),\n reason: Schema.Literals([\"hook-failed\", \"no-active-tool-batch\"]),\n message: Schema.String.check(Schema.isMaxLength(4_096)),\n toolCallId: Schema.optionalKey(ToolCallId),\n /** Diagnostic cause for the live Effect only; Run events retain the fixed public message. */\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/**\n * Explicit ephemeral mode: no durable coordinator supplied\n * `RunOptions.subagent`, so no durable claim is being made and the delegation\n * handler keeps the S1 in-process spawn semantics honestly.\n */\nexport interface SubagentDurabilityEphemeral {\n readonly mode: \"ephemeral\";\n}\n\n/**\n * Durable mode: establishment and join run through the coordinator's\n * `RunSubagentHook` under the parent's ownership fence, and `waiting` raises\n * the engine-owned suspension signal for a still-running child.\n */\nexport interface SubagentDurabilityDurable {\n readonly mode: \"durable\";\n /** Idempotent durable child establishment under the parent ownership fence. */\n readonly establish: (\n request: RunSubagentEstablishRequest,\n ) => Effect.Effect<ChildEstablishStatus, SubagentDurabilityError>;\n /** Atomic settlement join: `SubagentJoined` + parent `ToolCallSettled` in one canonical batch (SUB-019). */\n readonly join: (request: RunSubagentJoinRequest) => Effect.Effect<void, SubagentDurabilityError>;\n /**\n * Raise the waiting suspension signal for one delegation call whose\n * established child has not settled. Never returns: the handler ends here,\n * siblings run to completion, the Run suspends, and the resumed batch\n * re-executes the handler idempotently.\n */\n readonly waiting: (\n toolCallId: ToolCallId,\n child: RunSubagentChildIdentity,\n ) => Effect.Effect<never, ToolCallWaiting | SubagentDurabilityError>;\n}\n\n/**\n * Mode-dispatched service value seen by delegation Tool handlers: an explicit\n * ephemeral default when the Run carries no durable coordinator, the durable\n * establish/join/waiting surface otherwise.\n */\nexport type SubagentDurabilityService = SubagentDurabilityEphemeral | SubagentDurabilityDurable;\n\n/**\n * Engine-owned durable-Subagent seam provided locally to every Tool batch,\n * constructed from `RunOptions.subagent` when present and the explicit\n * ephemeral-mode default when absent. Like the other engine-provided Tool\n * services it is excluded from the runtime's public requirements and MUST NOT\n * be satisfied from an application Layer; handlers resolve it per call (the\n * S1 innermost re-provide pattern) so a Layer built inside another Run's\n * batch never captures a stale mode.\n */\nexport class SubagentDurability extends Context.Service<\n SubagentDurability,\n SubagentDurabilityService\n>()(\"@effect-agent/engine/SubagentDurability\") {}\n\n/** The one explicit ephemeral-mode value: absence of a durable coordinator is stated, not inferred. */\nconst ephemeralSubagentDurability: SubagentDurabilityService = { mode: \"ephemeral\" };\n\nconst closedSubagentDurabilityFailure = (\n operation: \"establish\" | \"join\" | \"waiting\",\n toolCallId?: ToolCallId,\n): SubagentDurabilityError =>\n SubagentDurabilityError.make({\n operation,\n reason: \"no-active-tool-batch\",\n message: `Durable Subagent ${operation} was invoked outside an active Tool batch`,\n ...(toolCallId === undefined ? {} : { toolCallId }),\n });\n\n/**\n * Fail-closed Run-level `SubagentDurability` default. Each Tool batch shadows\n * it with its live per-batch service; resolving the seam outside an active\n * Tool batch fails typed instead of silently spawning an ephemeral child\n * under a durable coordinator.\n */\nconst closedSubagentDurability: SubagentDurabilityService = {\n mode: \"durable\",\n establish: (request) =>\n Effect.fail(closedSubagentDurabilityFailure(\"establish\", request.toolCallId)),\n join: (request) => Effect.fail(closedSubagentDurabilityFailure(\"join\", request.toolCallId)),\n waiting: (toolCallId) => Effect.fail(closedSubagentDurabilityFailure(\"waiting\", toolCallId)),\n};\n\n/**\n * Durable `SubagentDurability` service bound to one Tool batch over the\n * coordinator's `RunSubagentHook`. Hook failures surface as typed\n * `SubagentDurabilityError` values without widening handler error channels\n * (the coordinator keeps its own halt side channel, exactly like the Step\n * hook); `waiting` constructs the engine-owned `ToolCallWaiting` signal so a\n * handler can never counterfeit a foreign child identity shape.\n */\nconst makeSubagentDurabilityService = <HookError, HookRequirements>(\n hook: RunSubagentHook<HookError, HookRequirements>,\n hookServices: Context.Context<HookRequirements>,\n): SubagentDurabilityService => ({\n mode: \"durable\",\n establish: (request) =>\n provideHookServices(hook.establish(request), hookServices).pipe(\n Effect.mapError((cause) =>\n SubagentDurabilityError.make({\n operation: \"establish\",\n reason: \"hook-failed\",\n toolCallId: request.toolCallId,\n message: \"Durable child establishment failed\",\n cause,\n }),\n ),\n ),\n join: (request) =>\n provideHookServices(hook.join(request), hookServices).pipe(\n Effect.mapError((cause) =>\n SubagentDurabilityError.make({\n operation: \"join\",\n reason: \"hook-failed\",\n toolCallId: request.toolCallId,\n message: \"Durable child join failed\",\n cause,\n }),\n ),\n ),\n waiting: (toolCallId, child) =>\n Effect.fail(\n ToolCallWaiting.make({\n toolCallId,\n childThreadId: child.childThreadId,\n childSubmissionId: child.childSubmissionId,\n childRunId: child.childRunId,\n receiptId: child.receiptId,\n message: `Tool Call ${toolCallId} is waiting on durable attached child ${child.childSubmissionId}`,\n }),\n ),\n});\n\n/**\n * Extract the waiting suspension signal from a handler cause. It normally\n * travels as a typed failure through the native `Toolkit.handle` error\n * channel; the squash fallback also recognizes it inside a defect so a\n * wrapped signal still suspends instead of manufacturing a Tool failure.\n */\nconst waitingFromCause = (cause: Cause.Cause<unknown>): ToolCallWaiting | undefined => {\n const failure = Cause.findErrorOption(cause);\n\n if (Option.isSome(failure) && failure.value instanceof ToolCallWaiting) {\n return failure.value;\n }\n const squashed = Cause.squash(cause);\n\n return squashed instanceof ToolCallWaiting ? squashed : undefined;\n};\n\n/** Stable delegation identity supplied by the invoking delegation Tool handler. */\nexport interface SpawnDelegation {\n readonly delegationId: DelegationId;\n readonly parentToolCallId: ToolCallId;\n}\n\n/**\n * Child Run options accepted by `AgentSpawner.spawn`. Child Thread/Run\n * identity and the Parent Link are spawner-owned and cannot be overridden.\n */\nexport interface SpawnRunOptions<HookError = never, HookRequirements = never> extends Omit<\n RunOptions<HookError, HookRequirements>,\n \"threadId\" | \"runId\" | \"parentLink\"\n> {}\n\n/**\n * Handle to one spawned Attached Child: its preallocated child identity, its\n * immutable Parent Link, and the same observation surface as `DetachedRun`.\n * The child fiber belongs to the Scope the caller provided to `spawn`.\n */\nexport interface SpawnedChildRun<Output, Error> extends DetachedRun<Output, Error> {\n readonly threadId: ThreadId;\n readonly runId: RunId;\n readonly parentLink: SubagentParentLink;\n}\n\n/**\n * Run one child Agent Binding through the same interpreter as a top-level\n * Run.\n *\n * The spawner allocates a fresh child `ThreadId` and `RunId` through\n * `IdGenerator` (guaranteeing a fresh child Thread per invocation, with\n * no Thread reuse), constructs the immutable Parent Link at\n * `depth + 1`, and starts the child eagerly with `AgentRuntime.start` inside\n * the caller-provided Scope, so parent interruption always reaches the child\n * and its finalizers. Preflight policy (including S1's normative\n * subtree reservation and inherited-grant checks) belongs to the delegation capability and runs\n * before `spawn` is called. Children inherit the parent Run's provided history and context\n * services; delegation handlers do not select separate host policies.\n */\nconst spawnWithParent = (\n parent: AgentSpawnerParent,\n depth: number,\n history: ThreadHistory[\"Service\"],\n preparation: RunContextPreparation[\"Service\"],\n onChild: (runId: RunId, read: Effect.Effect<RunUsageReport>) => void,\n) =>\n Effect.fn(\"AgentSpawner.spawn\")(function* <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n HookError = never,\n HookRequirements = never,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 binding: RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n input: unknown,\n delegation: SpawnDelegation,\n options?: SpawnRunOptions<HookError, HookRequirements>,\n ): Effect.fn.Return<\n SpawnedChildRun<\n Agent.Output<typeof binding>,\n AgentRuntimeFailure<typeof binding, HookError, InstructionError>\n >,\n never,\n | Scope.Scope\n | Exclude<\n AgentRuntimeRequirements<typeof binding, HookRequirements, InstructionRequirements>,\n ThreadHistory | RunContextPreparation\n >\n > {\n const ids = yield* IdGenerator;\n const threadId = yield* ids.nextThreadId;\n const runId = yield* ids.nextRunId;\n // `depth + 1` is always an integer >= 1, so a decode failure is a defect.\n const childDepth = yield* Schema.decodeEffect(DelegationDepth)(depth + 1).pipe(Effect.orDie);\n\n const parentLink = SubagentParentLink.make({\n delegationId: delegation.delegationId,\n parentAgentId: parent.agentId,\n parentThreadId: parent.threadId,\n parentRunId: parent.runId,\n parentToolCallId: delegation.parentToolCallId,\n depth: childDepth,\n });\n\n const child = yield* startUnknown(binding, input, {\n ...options,\n threadId,\n runId,\n parentLink,\n }).pipe(\n Effect.provide(\n Context.make(ThreadHistory, history).pipe(Context.add(RunContextPreparation, preparation)),\n ),\n );\n\n onChild(runId, child.usageReport);\n\n return {\n ...child,\n threadId,\n runId,\n parentLink,\n };\n });\n\n/**\n * Narrow parent execution value visible to Tool handlers. `depth` is the\n * current Run's root-relative delegation depth: `0` for a root Run and\n * `parentLink.depth` for a child, which the delegation preflight uses to\n * enforce inherited nesting ceilings and conserved subtree allocations.\n */\nexport interface AgentSpawnerService {\n /** Resolved defaults for this parent Run; never includes its tools or handlers. */\n readonly policy: AgentPolicy;\n readonly depth: number;\n readonly grant?: SubagentGrant;\n readonly budget?: SubagentBudgetReservation;\n readonly budgetScope?: WorkerBudgetScope;\n readonly parent: AgentSpawnerParent;\n readonly spawn: <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n HookError = never,\n HookRequirements = never,\n InstructionError = InstructionErrorOf<Instructions, InputSchema[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<Instructions, InputSchema[\"Type\"]>,\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 binding: RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n input: unknown,\n delegation: SpawnDelegation,\n options?: SpawnRunOptions<HookError, HookRequirements>,\n ) => Effect.Effect<\n SpawnedChildRun<\n OutputSchema[\"Type\"],\n AgentRuntimeFailure<\n RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n HookError,\n InstructionError\n >\n >,\n never,\n | Scope.Scope\n | Exclude<\n AgentRuntimeRequirements<\n RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n HookRequirements,\n InstructionRequirements\n >,\n ThreadHistory | RunContextPreparation\n >\n >;\n}\n\n/**\n * Engine-owned service contract through which a declared delegation Tool\n * runs an Attached Child on the same interpreter.\n *\n * The engine provides this service locally to every Run, bound to the Run's\n * immutable identity and delegation depth; it is never satisfied from an\n * application Layer, is excluded from the runtime's public requirements, and\n * exposes neither the engine's mutable Run state nor any root Layer Context.\n */\nexport class AgentSpawner extends Context.Service<AgentSpawner, AgentSpawnerService>()(\n \"@effect-agent/engine/AgentSpawner\",\n) {}\n\nconst makeAgentSpawner = (\n parent: AgentSpawnerParent,\n depth: number,\n history: ThreadHistory[\"Service\"],\n preparation: RunContextPreparation[\"Service\"],\n policy: AgentPolicy,\n grant?: SubagentGrant,\n budget?: SubagentBudgetReservation,\n budgetScope?: WorkerBudgetScope,\n onChild: (runId: RunId, read: Effect.Effect<RunUsageReport>) => void = () => {},\n): AgentSpawnerService => ({\n ...(grant === undefined ? {} : { grant }),\n ...(budget === undefined ? {} : { budget }),\n ...(budgetScope === undefined ? {} : { budgetScope }),\n policy,\n depth,\n parent,\n spawn: spawnWithParent(parent, depth, history, preparation, onChild),\n});\n\n/** Bound applied to the rendered defect message of `withTerminalDefectEvent` (SEC-013). */\nconst DEFECT_MESSAGE_LIMIT = 2_048;\n\n/**\n * Opt-in boundary combinator (P7 §7(h), decision point 8): the engine keeps defects as\n * defects — `RunFailed` covers EXPECTED failures only, and a defect still fails the event\n * stream with its full Cause (AGENTS.md: errors are never silently widened, and a defect is\n * never converted into a typed failure by default). A host boundary that forwards Run Events\n * to a UI or transport can wrap the stream with this helper to append ONE bounded terminal\n * `RunFailed { errorTag: \"Defect\" }` event before the original cause is rethrown, so a viewer\n * always observes a terminal event even when the Run dies.\n *\n * Event contract:\n *\n * - typed failures and interruptions pass through untouched — the engine already emitted\n * their terminal event, so nothing is duplicated;\n * - a cause carrying a defect first emits `RunFailed` with `errorTag: \"Defect\"` and a\n * bounded string rendering of the defect (never the raw value; hosts owning stricter\n * redaction apply it downstream), then RETHROWS the original cause unchanged;\n * - identity fields come from the last event already streamed (`sequence` advances by one);\n * a defect BEFORE the first event has no Run identity to attribute, so it is rethrown\n * without an event — the helper never fabricates identities.\n */\nexport const withTerminalDefectEvent = <E, R>(\n events: Stream.Stream<RunEvent, E, R>,\n): Stream.Stream<RunEvent, E, R> =>\n Stream.suspend(() => {\n let last: RunEvent | undefined;\n\n return events.pipe(\n Stream.tap((event) =>\n Effect.sync(() => {\n last = event;\n }),\n ),\n Stream.catchCause((cause): Stream.Stream<RunEvent, E, R> => {\n const base = last;\n\n if (base === undefined || !Cause.hasDies(cause) || Cause.hasInterruptsOnly(cause)) {\n return Stream.failCause(cause);\n }\n\n const terminal = Stream.fromEffect(\n Effect.gen(function* () {\n const timestamp = DateTime.makeUnsafe(yield* Clock.currentTimeMillis);\n\n return RunFailed.make({\n eventVersion: 1,\n runId: base.runId,\n threadId: base.threadId,\n agentId: base.agentId,\n sequence: base.sequence + 1,\n timestamp,\n errorTag: \"Defect\",\n message: errorMessage(Cause.squash(cause)).slice(0, DEFECT_MESSAGE_LIMIT),\n });\n }),\n );\n\n return terminal.pipe(Stream.concat(Stream.failCause(cause)));\n }),\n );\n });\n\n/**\n * Ephemeral Agent interpreter whose `run` operation reduces the same semantic\n * event stream exposed by `stream`.\n *\n * Definitions consume native model services from the caller's Context. Explicit bindings\n * provide their model Layer locally; all remaining requirements stay visible\n * in the returned Effect or Stream. The interpreter owns no shared service or\n * Layer state. The two output helpers are the canonical revalidation seams for\n * durable thread adapters; they apply the same Schemas and projector as live\n * execution without invoking a Model or Tool Handler. The disposition helper\n * likewise reapplies the Definition selector and Schema.\n */\nexport {\n decodeFinalOutput,\n encodeRunDisposition,\n projectCompletionOutput,\n projectCompletionFromToolOutput,\n run,\n runUnknown,\n start,\n startUnknown,\n stream,\n streamUnknown,\n streamWithUsageAccountingUnknown,\n};\n","/** Public AgentRuntime API. Implementation helpers remain private. */\nexport {\n decodeFinalOutput,\n encodeRunDisposition,\n projectCompletionOutput,\n projectCompletionFromToolOutput,\n run,\n runUnknown,\n start,\n startUnknown,\n stream,\n streamUnknown,\n streamWithUsageAccountingUnknown,\n AgentResultSchema,\n AgentChildPending,\n AgentSpawner,\n SubagentDurability,\n SubagentDurabilityError,\n ToolCallWaiting,\n renderInputPrompt,\n withTerminalDefectEvent,\n type AgentResult,\n type AgentRuntimeFailure,\n type AgentRuntimeRequirements,\n type AgentCompletionProjectionRequirements,\n type AgentSpawnerParent,\n type AgentSpawnerService,\n type DetachedRun,\n type EngineProvidedToolServices,\n type RuntimeBinding,\n type SpawnDelegation,\n type SpawnedChildRun,\n type SpawnRunOptions,\n type SubagentDurabilityDurable,\n type SubagentDurabilityEphemeral,\n type SubagentDurabilityService,\n} from \"./internal/agent-runtime.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B;AAChC,MAAM,uBAAuB,OAAO,eAAe,SAAS,WAAW,CAAC,CAAC;AACzE,MAAM,oBAAoB,OAAO,eAAe,SAAS,KAAK,KAAA,CAAS,CAAC;AAExE,MAAM,0CAA0B,IAAI,IAAY;CAC9C,SAAS;CACT,UAAU;CACV,WAAW;CACX,kBAAkB;CAClB,WAAW;CACX,YAAY;CACZ,WAAW;CACX,YAAY;CACZ,aAAa;CACb,aAAa;CACb,cAAc;CACd,eAAe;AACjB,CAAC;AAED,MAAM,8BAA8B,OAAO,yBACzC,YAAY,WACZ,YACF,CAAC,EAAE;AAEH,MAAM,sBAAsB,OAAO,eAAe,WAAW,SAAS;AACtE,MAAM,yBAAyB,OAAO,yBAAyB,qBAAqB,QAAQ,CAAC,EAAE;AAC/F,MAAM,yBAAyB,OAAO,yBAAyB,qBAAqB,QAAQ,CAAC,EAAE;AAC/F,MAAM,uBAAuB,OAAO,yBAAyB,SAAS,WAAW,QAAQ,CAAC,EAAE;AAC5F,MAAM,iBAAiB,QAAQ,IAAI,YAAY,KAAK;AAEpD,MAAM,yBACJ,OAAO,mBAAmB,aACtB,OAAO,yBAAyB,gBAAgB,WAAW,IAC3D,KAAA;AAEN,MAAM,gBACJ,2BAA2B,KAAA,KAC3B,WAAW,0BACX,uBAAuB,UAAU,QACjC,OAAO,uBAAuB,UAAU,WACpC,OAAO,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