@yielded/agent 0.1.0-beta.174 → 0.1.0-beta.175
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Admin-BHmp2V9p.d.mts → Admin-Qa3I1oA5.d.mts} +38 -7
- package/dist/{AgentRuntime-BD3ZHAMq.d.mts → AgentRuntime-CHDyRbSf.d.mts} +3 -3
- package/dist/{AgentRuntime-B6qZlD3f.mjs → AgentRuntime-DaDKMasp.mjs} +123 -114
- package/dist/AgentRuntime-DaDKMasp.mjs.map +1 -0
- package/dist/{Digest-EpeqWEdv.mjs → Digest-C3EODOee.mjs} +2 -2
- package/dist/{Digest-EpeqWEdv.mjs.map → Digest-C3EODOee.mjs.map} +1 -1
- package/dist/{DurableAgentRuntime-CBBjRNJN.mjs → DurableAgentRuntime-CPlw5_7e.mjs} +161 -85
- package/dist/DurableAgentRuntime-CPlw5_7e.mjs.map +1 -0
- package/dist/{EventSource-C9aaJaXT.d.mts → EventSource-BTu68yDW.d.mts} +2 -2
- package/dist/InMemory.d.mts +2 -2
- package/dist/{MessageDelivery-BGDm-c46.d.mts → MessageDelivery-DjAZJ4Fd.d.mts} +4 -4
- package/dist/{MessagingHost-CRUK4JBi.mjs → MessagingHost-CZCyrnvJ.mjs} +27 -26
- package/dist/MessagingHost-CZCyrnvJ.mjs.map +1 -0
- package/dist/{PreparedInputAdmission-BvDqlgiP.d.mts → PreparedInputAdmission-wgY4JMZY.d.mts} +3 -3
- package/dist/{Records-BiuJDWNe.mjs → Records-DzL4Kbtw.mjs} +2 -2
- package/dist/{Records-BiuJDWNe.mjs.map → Records-DzL4Kbtw.mjs.map} +1 -1
- package/dist/{RunContinuation-CTJ1jGrO.d.mts → RunContinuation-3jB5pULC.d.mts} +10 -4
- package/dist/{RunContinuation-4ZATcVLB.mjs → RunContinuation-BiyKJK32.mjs} +74 -40
- package/dist/RunContinuation-BiyKJK32.mjs.map +1 -0
- package/dist/{RunJournal-CNZqA3Ge.mjs → RunJournal-CPMKcfd0.mjs} +84 -79
- package/dist/RunJournal-CPMKcfd0.mjs.map +1 -0
- package/dist/{RunStorage-BHjuuERI.mjs → RunStorage-CzutHJBE.mjs} +3 -2
- package/dist/RunStorage-CzutHJBE.mjs.map +1 -0
- package/dist/{Scheduling-NG8slKdI.mjs → Scheduling-07_dsGED.mjs} +3 -3
- package/dist/{Scheduling-NG8slKdI.mjs.map → Scheduling-07_dsGED.mjs.map} +1 -1
- package/dist/{Subagent-CTIpnzlB.mjs → Subagent-CexndZSp.mjs} +2 -2
- package/dist/{Subagent-CTIpnzlB.mjs.map → Subagent-CexndZSp.mjs.map} +1 -1
- package/dist/{Subagent-DKhZA72u.d.mts → Subagent-xhN_aD1r.d.mts} +3 -3
- package/dist/{Subscription-BNg9VCRl.d.mts → Subscription-DmIHlOJK.d.mts} +2 -2
- package/dist/{SubscriptionInput-BUoXv-_K.d.mts → SubscriptionInput-DgcQhvbe.d.mts} +2 -2
- package/dist/{Thread-dk-QiNml.d.mts → Thread-DzdJAY4J.d.mts} +4 -3
- package/dist/{ThreadHistory-ByxS8HU1.d.mts → ThreadHistory-KPPBJLJb.d.mts} +12 -2
- package/dist/{ThreadImport-CodYoJoa.mjs → ThreadImport-CjlG57vH.mjs} +8 -8
- package/dist/{ThreadImport-CodYoJoa.mjs.map → ThreadImport-CjlG57vH.mjs.map} +1 -1
- package/dist/{ThreadImport-CMgzttvr.d.mts → ThreadImport-DP-vOk2F.d.mts} +4 -4
- package/dist/{ThreadStore-59uDGXul.mjs → ThreadStore-EuUilthA.mjs} +5 -7
- package/dist/ThreadStore-EuUilthA.mjs.map +1 -0
- package/dist/{ThreadTransfer-3jigUl3g.mjs → ThreadTransfer-DB_zsrtJ.mjs} +4 -4
- package/dist/{ThreadTransfer-3jigUl3g.mjs.map → ThreadTransfer-DB_zsrtJ.mjs.map} +1 -1
- package/dist/{WorkerAdmission-DDYJdOsU.mjs → WorkerAdmission-eBeXt_mu.mjs} +5 -5
- package/dist/{WorkerAdmission-DDYJdOsU.mjs.map → WorkerAdmission-eBeXt_mu.mjs.map} +1 -1
- package/dist/{agent-registration-DRbyhAu-.mjs → agent-registration-a6QYaG3h.mjs} +4 -4
- package/dist/{agent-registration-DRbyhAu-.mjs.map → agent-registration-a6QYaG3h.mjs.map} +1 -1
- package/dist/capabilities/Messaging.mjs +1 -1
- package/dist/capabilities/ModelContext.d.mts +1 -1
- package/dist/capabilities/RunHooks.d.mts +1 -1
- package/dist/capabilities/Subagent.d.mts +1 -1
- package/dist/capabilities/Subagent.mjs +1 -1
- package/dist/core/Thread.d.mts +2 -2
- package/dist/core/Thread.mjs +5 -3
- package/dist/core/Thread.mjs.map +1 -1
- package/dist/durable/ActivityStore.mjs +1 -1
- package/dist/durable/Admin.d.mts +1 -1
- package/dist/durable/Admin.mjs +1 -1
- package/dist/durable/AgentRegistration.d.mts +1 -1
- package/dist/durable/AgentRegistration.mjs +1 -1
- package/dist/durable/Certification.d.mts +1 -1
- package/dist/durable/CommittedActivity.d.mts +1 -1
- package/dist/durable/CommittedActivity.mjs +3 -3
- package/dist/durable/Digest.mjs +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.mjs +2 -2
- package/dist/durable/EventSource.d.mts +1 -1
- package/dist/durable/EventSource.mjs +1 -1
- package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
- package/dist/durable/LifecyclePublication.d.mts +1 -1
- package/dist/durable/LifecyclePublication.mjs +2 -2
- package/dist/durable/MessageDelivery.d.mts +1 -1
- package/dist/durable/MessageDelivery.mjs +2 -2
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
- package/dist/durable/MessageDeliveryStoreConformance.mjs +2 -2
- package/dist/durable/PersistentHistory.d.mts +2 -2
- package/dist/durable/PersistentHistory.mjs +4 -4
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/RecordFormat.mjs +1 -1
- package/dist/durable/Records.mjs +1 -1
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/Recovery.mjs +1 -1
- package/dist/durable/RunContinuation.d.mts +2 -2
- package/dist/durable/RunContinuation.mjs +3 -3
- package/dist/durable/RunJournal.d.mts +2 -2
- package/dist/durable/RunJournal.mjs +2 -2
- package/dist/durable/RunStorage.d.mts +1 -1
- package/dist/durable/RunStorage.mjs +1 -1
- package/dist/durable/Schedule.mjs +1 -1
- package/dist/durable/ScheduleStoreConformance.mjs +1 -1
- package/dist/durable/ScheduleTransition.mjs +1 -1
- package/dist/durable/Scheduling.d.mts +1 -1
- package/dist/durable/Scheduling.mjs +1 -1
- package/dist/durable/SettlementPublisher.d.mts +1 -1
- package/dist/durable/SettlementPublisher.mjs +3 -3
- package/dist/durable/SqlMemoryStore.mjs +5 -3
- package/dist/durable/SqlMemoryStore.mjs.map +1 -1
- package/dist/durable/SubmissionLedger.d.mts +1 -1
- package/dist/durable/SubmissionLedger.mjs +7 -3
- package/dist/durable/SubmissionLedger.mjs.map +1 -1
- package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
- package/dist/durable/SubmissionLedgerConformance.mjs +6 -6
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/Subscription.mjs +2 -2
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionInput.mjs +2 -2
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
- package/dist/durable/SubscriptionTools.d.mts +2 -2
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/SubscriptionTransition.mjs +1 -1
- package/dist/durable/Subscriptions.d.mts +5 -5
- package/dist/durable/Subscriptions.mjs +2 -2
- package/dist/durable/ThreadArchiveRange.d.mts +1 -1
- package/dist/durable/ThreadArchiveRange.mjs +1 -1
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadContextHistory.mjs +2 -2
- package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
- package/dist/durable/ThreadImport.d.mts +1 -1
- package/dist/durable/ThreadImport.mjs +1 -1
- package/dist/durable/ThreadInvariants.d.mts +3 -3
- package/dist/durable/ThreadInvariants.mjs +4 -4
- package/dist/durable/ThreadProjection.mjs +1 -1
- package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
- package/dist/durable/ThreadReader.d.mts +1 -1
- package/dist/durable/ThreadReader.mjs +1 -1
- package/dist/durable/ThreadStore.d.mts +1 -1
- package/dist/durable/ThreadStore.mjs +2 -2
- package/dist/durable/ThreadStoreConformance.d.mts +1 -1
- package/dist/durable/ThreadStoreConformance.mjs +4 -4
- package/dist/durable/ThreadTransfer.d.mts +1 -1
- package/dist/durable/ThreadTransfer.mjs +1 -1
- package/dist/durable/ThreadWork.d.mts +2 -2
- package/dist/durable/ThreadWork.mjs +12 -6
- package/dist/durable/ThreadWork.mjs.map +1 -1
- package/dist/durable/ToolReconciler.mjs +1 -1
- package/dist/durable/WakeScheduler.mjs +23 -39
- package/dist/durable/WakeScheduler.mjs.map +1 -1
- package/dist/durable/WorkerAdmission.d.mts +1 -1
- package/dist/durable/WorkerAdmission.mjs +1 -1
- package/dist/durable/WorkerHost.d.mts +1 -1
- package/dist/engine/AgentRuntime.d.mts +1 -1
- package/dist/engine/AgentRuntime.mjs +1 -1
- package/dist/engine/MessagingHost.mjs +1 -1
- package/dist/engine/Output.mjs +1 -1
- package/dist/engine/ThreadHistory.d.mts +1 -1
- package/dist/engine/ThreadHistory.mjs +3 -2
- package/dist/engine/ThreadHistory.mjs.map +1 -1
- package/dist/index.d.mts +12 -12
- package/dist/index.mjs +13 -13
- package/dist/{output-contract-CMIhu4Cw.mjs → output-contract-DCnLYCdp.mjs} +12 -15
- package/dist/{output-contract-CMIhu4Cw.mjs.map → output-contract-DCnLYCdp.mjs.map} +1 -1
- package/dist/{run-context-reader-CC7ZD95F.d.mts → run-context-reader-DVhJZ1Qe.d.mts} +2 -2
- package/package.json +1 -1
- package/src/core/Thread.ts +143 -146
- package/src/durable/DurableAgentRuntime.ts +381 -206
- package/src/durable/RunContinuation.ts +113 -62
- package/src/durable/RunJournal.ts +99 -108
- package/src/durable/RunStorage.ts +7 -0
- package/src/durable/SqlMemoryStore.ts +8 -6
- package/src/durable/SubmissionLedger.ts +7 -0
- package/src/durable/ThreadStore.ts +9 -7
- package/src/durable/ThreadWork.ts +10 -0
- package/src/durable/WakeScheduler.ts +34 -66
- package/src/durable/internal/usage-totals.ts +28 -31
- package/src/engine/MessagingHost.ts +4 -2
- package/src/engine/ThreadHistory.ts +47 -48
- package/src/engine/internal/agent-runtime.ts +234 -202
- package/src/engine/internal/output-contract.ts +15 -15
- package/src/engine/internal/primitive-delta.ts +2 -3
- package/src/engine/internal/tool-telemetry.ts +3 -5
- package/dist/AgentRuntime-B6qZlD3f.mjs.map +0 -1
- package/dist/DurableAgentRuntime-CBBjRNJN.mjs.map +0 -1
- package/dist/MessagingHost-CRUK4JBi.mjs.map +0 -1
- package/dist/RunContinuation-4ZATcVLB.mjs.map +0 -1
- package/dist/RunJournal-CNZqA3Ge.mjs.map +0 -1
- package/dist/RunStorage-BHjuuERI.mjs.map +0 -1
- package/dist/ThreadStore-59uDGXul.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AgentRuntime-DaDKMasp.mjs","names":["ProvisionalText.Publisher","ProvisionalText.noopPublisher","CurrentProvisionalTextAttempt","Agent.isModelResolver"],"sources":["../src/engine/internal/bounded-value.ts","../src/engine/internal/primitive-delta.ts","../src/engine/internal/provisional-text.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 * as DateTime from \"effect/DateTime\";\nimport * as Redacted from \"effect/Redacted\";\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 response value without invoking user 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 memory-retention guard does not replace Schema validation or ownership capture. Callers\n * also use it before copying provider values. Reflection can trigger Proxy traps because\n * JavaScript offers no portable, trap-free Proxy test.\n * Native ArrayBuffer and URL storage is measured only for their exact built-in prototypes.\n * Plain and caller-approved prototypes promise own-property state; native objects deliberately\n * disguised with those prototypes are outside this guard's contract. Parsed model JSON cannot\n * construct such values; application and provider code must preserve native prototypes.\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 (prototype === ArrayBuffer.prototype) {\n const bufferByteLength = intrinsicArrayBufferByteLength(value);\n\n if (bufferByteLength === undefined || !add(bufferByteLength)) return false;\n supportedSpecialObject = true;\n }\n if (urlPrototype !== undefined && prototype === urlPrototype) {\n const urlByteLength = intrinsicUrlByteLength(value);\n\n if (urlByteLength === undefined || !add(urlByteLength)) return false;\n supportedSpecialObject = true;\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 * as Response from \"effect/ai/Response\";\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\"];\nconst boundaryKeys = [brand, \"type\", \"id\", \"metadata\"];\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 boundaryOverhead = (\n type: \"text-start\" | \"text-end\" | \"reasoning-start\" | \"reasoning-end\",\n) => ({\n source: boundedValueFootprint(Response.makePart(type, { id: \"\" }), Number.MAX_SAFE_INTEGER),\n encoded: boundedValueFootprint({ type, id: \"\", metadata: {} }, Number.MAX_SAFE_INTEGER),\n});\n\nconst overheads = {\n \"text-delta\": overhead(\"text-delta\"),\n \"reasoning-delta\": overhead(\"reasoning-delta\"),\n \"text-start\": boundaryOverhead(\"text-start\"),\n \"text-end\": boundaryOverhead(\"text-end\"),\n \"reasoning-start\": boundaryOverhead(\"reasoning-start\"),\n \"reasoning-end\": boundaryOverhead(\"reasoning-end\"),\n};\n\n/**\n * Capture complete primitive text and reasoning values for 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 capturePrimitiveTextPart = (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 const typeDescriptor = Object.getOwnPropertyDescriptor(part, \"type\");\n\n if (typeDescriptor === undefined || !(\"value\" in typeDescriptor)) return undefined;\n\n const isDelta =\n typeDescriptor.value === \"text-delta\" || typeDescriptor.value === \"reasoning-delta\";\n\n const selectedKeys = isDelta ? keys : boundaryKeys;\n\n if (Reflect.ownKeys(part).length !== selectedKeys.length) return undefined;\n const snapshot: Record<string, unknown> = {};\n\n for (const key of selectedKeys) {\n const descriptor = Object.getOwnPropertyDescriptor(part, key);\n\n if (descriptor === undefined || !(\"value\" in descriptor)) return undefined;\n snapshot[key] = descriptor.value;\n }\n if (snapshot[brand] !== brand) return undefined;\n const { type, id, delta, metadata } = snapshot;\n\n if (\n type !== \"text-delta\" &&\n type !== \"reasoning-delta\" &&\n type !== \"text-start\" &&\n type !== \"text-end\" &&\n type !== \"reasoning-start\" &&\n type !== \"reasoning-end\"\n ) {\n return undefined;\n }\n if (isDelta !== (type === \"text-delta\" || type === \"reasoning-delta\")) return undefined;\n if (typeof id !== \"string\" || (isDelta && 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) + (typeof delta === \"string\" ? utf8ByteLength(delta) : 0);\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\n return { part: snapshot, 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 * as Response from \"effect/ai/Response\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\n\nimport type { AttemptId, RunId, SubmissionId, ThreadId, TurnId } from \"../../core/Identifiers.ts\";\nimport * as ProvisionalText from \"../../core/ProvisionalText.ts\";\n\nexport interface ModelHandle {\n readonly offerUnsafe: (part: Extract<ProvisionalText.Event, { _tag: \"Text\" }>[\"part\"]) => boolean;\n readonly discard: () => void;\n readonly close: () => void;\n}\n\nexport interface Attempt {\n readonly threadId: ThreadId;\n readonly openModel: (runId: RunId, turnId: TurnId) => ModelHandle | undefined;\n readonly close: () => void;\n}\n\n/** Bound only from a trusted Claim, inside captured registration and per-Attempt services. */\nexport const CurrentAttempt = Context.Reference<Attempt | undefined>(\n \"@effect-agent/engine/ProvisionalText/CurrentAttempt\",\n { defaultValue: () => undefined },\n);\n\nconst makeAttempt = Effect.fnUntraced(function* (\n threadId: ThreadId,\n submissionId: SubmissionId,\n attemptId: AttemptId,\n): Effect.fn.Return<Attempt> {\n const publisher = yield* ProvisionalText.Publisher;\n const identity = { threadId, submissionId, attemptId };\n let closed = false;\n let nextGeneration = 0;\n\n const offerUnsafe = (event: ProvisionalText.Event): boolean => {\n try {\n return publisher.offerUnsafe(event);\n } catch {\n return false;\n }\n };\n\n return {\n threadId,\n openModel: (runId, turnId) => {\n if (closed) return undefined;\n\n const generation = ++nextGeneration;\n let open = true;\n\n const handle: ModelHandle = {\n offerUnsafe: (part) => {\n if (!open || closed) return false;\n\n // processModelPart retains the original. Copy only native text fields so a\n // publisher cannot mutate that trace or observe provider metadata.\n const detached =\n part.type === \"text-delta\"\n ? Response.makePart(\"text-delta\", { id: part.id, delta: part.delta })\n : Response.makePart(part.type, { id: part.id });\n\n return offerUnsafe({\n _tag: \"Text\",\n ...identity,\n runId,\n turnId,\n generation,\n part: detached,\n });\n },\n discard: () => {\n if (!open || closed) return;\n handle.close();\n offerUnsafe({ _tag: \"Discard\", ...identity, runId, turnId, generation });\n },\n close: () => {\n if (!open) return;\n open = false;\n },\n };\n\n return handle;\n },\n close: () => {\n if (closed) return;\n closed = true;\n offerUnsafe({ _tag: \"AttemptEnded\", ...identity });\n },\n };\n});\n\n/** Disabled observation acquires no Scope, counters, handles, or event payloads. */\nexport const withAttempt = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n threadId: ThreadId,\n submissionId: SubmissionId,\n attemptId: AttemptId,\n): Effect.Effect<A, E, R> =>\n Effect.flatMap(ProvisionalText.Publisher, (publisher) =>\n publisher === ProvisionalText.noopPublisher\n ? Effect.provideService(effect, CurrentAttempt, undefined)\n : Effect.scoped(\n Effect.acquireRelease(makeAttempt(threadId, submissionId, attemptId), (attempt) =>\n Effect.sync(attempt.close),\n ).pipe(\n Effect.flatMap((attempt) => Effect.provideService(effect, CurrentAttempt, attempt)),\n ),\n ),\n );\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as ErrorReporter from \"effect/ErrorReporter\";\nimport * as Exit from \"effect/Exit\";\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","import type { LanguageModel } from \"effect/ai\";\nimport * as Tool from \"effect/ai/Tool\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\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.fnUntraced(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.fnUntraced(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.fnUntraced(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 declarations: Array<unknown> = [];\n\n for (const name of names) {\n const tool = definition.toolkit.tools[name];\n\n if (tool === undefined) return yield* invalid(\"A selected Tool schema cannot be rendered\");\n declarations.push(\n yield* Effect.try({\n try: () =>\n 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 catch: () => invalid(\"A selected Tool schema cannot be rendered\"),\n }),\n );\n }\n\n const bytes = yield* Effect.try({\n try: () => utf8ByteLength(JSON.stringify(declarations)),\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 type { Fiber } from \"effect\";\nimport type { Tool } from \"effect/ai\";\nimport * as AiError from \"effect/ai/AiError\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as ErrorReporter from \"effect/ErrorReporter\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tracer from \"effect/Tracer\";\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 | undefined,\n): { readonly found: boolean; readonly residual: Cause.Cause<E | ToolSpanFailure> } => {\n if (marker === undefined) return { found: false, residual: cause };\n\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 | undefined,\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 Schema.TaggedError<ToolSpanLifecycleFailure>()(\n \"ToolSpanLifecycleFailure\",\n {},\n) {\n override readonly name = \"ToolSpanLifecycleFailure\";\n override readonly message = \"Tool span lifecycle failed\";\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 ?? ToolSpanLifecycleFailure.make({}))\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 // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.\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 // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.\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 // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.\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 // oxlint-disable-next-line effect/no-untyped-throw -- The synchronous foreign tracer hook must rethrow the original primitive failure for the Effect evaluator.\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(ToolSpanLifecycleFailure.make({})));\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 make: Effect.Effect<ToolSpanTelemetryService> = Effect.map(\n Tracer.Tracer,\n (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","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 * as AiError from \"effect/ai/AiError\";\nimport * as LanguageModel from \"effect/ai/LanguageModel\";\nimport * as Model from \"effect/ai/Model\";\nimport * as Prompt from \"effect/ai/Prompt\";\nimport * as Response from \"effect/ai/Response\";\nimport * as ResponseIdTracker from \"effect/ai/ResponseIdTracker\";\nimport * as Tool from \"effect/ai/Tool\";\nimport * as Toolkit from \"effect/ai/Toolkit\";\nimport * as Arr from \"effect/Array\";\nimport * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Layer from \"effect/Layer\";\nimport * as Metric from \"effect/Metric\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Queue from \"effect/Queue\";\nimport * as Result from \"effect/Result\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport * 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 AgentInputDecodeError,\n AgentPersistenceCapacityError,\n AgentInputError,\n AgentOutputError,\n AgentRunDispositionError,\n AgentToolAuthorizationDenied,\n type AgentToolAuthorizationCheckError,\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 { copyJson } from \"../../core/internal/json.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 ModelRestarted,\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 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 {\n AssignmentDisposition,\n FrameworkMessage,\n type WorkerBudgetScope,\n} 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 { isTextOutput, outputSchemaContract, prepareModelPrompt } from \"./output-contract.ts\";\nimport { capturePrimitiveTextPart } from \"./primitive-delta.ts\";\nimport {\n boundedCanonicalJsonSnapshot,\n boundedJsonSnapshot,\n type BoundedJsonSnapshot,\n} from \"./provider-result-staging.ts\";\nimport {\n CurrentAttempt as CurrentProvisionalTextAttempt,\n type ModelHandle as ProvisionalTextModelHandle,\n} from \"./provisional-text.ts\";\nimport { deliverToolFailure, 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 ProgrammaticToolFailure,\n type RunToolFailureObserver,\n type ChildEstablishStatus,\n type CommandDrainPolicy,\n type RunApprovalRequest,\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 type RunTurnCommit,\n type RunTurnCompletion,\n type RunTurnResponse,\n type RunTurnToolResult,\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 estimateMessageTokens,\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 ...(context.webSearchCalls === undefined ? {} : { webSearchCalls: context.webSearchCalls }),\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.fnUntraced(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.fnUntraced(function* (context: RunContext, turn: number) {\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 | AgentToolAuthorizationCheckError\n | ModelProtocolError\n | AgentPersistenceCapacityError\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\ntype EventPublisher = (events: ReadonlyArray<RunEvent>) => Effect.Effect<void>;\n\ninterface RunContext {\n readonly publish: EventPublisher | undefined;\n readonly progressFailure: Deferred.Deferred<never, ModelProtocolError | AgentPolicyError>;\n /** A thread resolver owns model identity; context hooks must not replace it. */\n readonly resolvedModel: boolean;\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 readonly durationFailure: AgentPolicyError;\n history: Prompt.Prompt;\n /** New canonical input messages, owned here until their response is accepted. */\n readonly pendingCommitInputs: Array<Prompt.Message>;\n modelCalls: number;\n modelRestarts: number;\n usageStatus: typeof UsageCompleteness.Type;\n pricingStatus: typeof UsageCompleteness.Type;\n unobservedModelCalls: number;\n webSearchCalls: number | undefined;\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 modelSource: Prompt.Prompt | undefined;\n sourceLength: number;\n }\n | undefined;\n windowId: string;\n windowTokens: number | (() => 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 admitted native Tool progress bytes, including headless execution. */\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\n/** Observation is optional; semantic execution never waits for an absent consumer. */\nconst publishEvent = <E, R>(\n context: RunContext,\n make: () => Effect.Effect<RunEvent, E, R>,\n): Effect.Effect<void, E, R> =>\n context.publish === undefined\n ? Effect.void\n : Effect.flatMap(Effect.suspend(make), (event) => publishEvents(context, [event]));\n\nconst publishEvents = (\n context: RunContext,\n events: ReadonlyArray<RunEvent>,\n): Effect.Effect<void> =>\n context.publish === undefined || events.length === 0 ? Effect.void : context.publish(events);\n\n/** A completed admission failure cannot be swallowed by a Handler or outrun by its result. */\nconst checkpointExecution = <E, R>(\n context: RunContext,\n durability?: RunDurabilityHook<E, R>,\n): Effect.Effect<void, E | ModelProtocolError | AgentPolicyError, R> =>\n Effect.suspend((): Effect.Effect<void, E | ModelProtocolError | AgentPolicyError, R> =>\n Deferred.isDoneUnsafe(context.progressFailure)\n ? Deferred.await(context.progressFailure)\n : (durability?.checkpoint ?? Effect.void),\n );\n\nconst noEvents: ReadonlyArray<RunEvent> = [];\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 /** Observed payloads held until the complete model response validates. */\n readonly providerResultPayloads: Array<ProviderResultEventPayload> | undefined;\n /** Semantic admission bounds apply equally to observed and headless execution. */\n providerStagedEventCount: number;\n providerStagedPayloadBytes: number;\n /** Provider progress is charged only after the complete model response validates. */\n providerProgressBytes: number;\n /** Scalar completion admission retained until provider closure. */\n turnCompletion: Response.FinishReason | undefined;\n readonly applicationToolCalls: Array<Response.ToolCallPart<string, Schema.Json>>;\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<\n RunToolCallDescriptor & { readonly parameters: Schema.Json }\n >;\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 /** Validated response facts exist only after the provider stream has closed. */\n commitResponse?: RunTurnResponse;\n commitInputCount?: number;\n responseCommitted?: boolean;\n resultsCommitted?: boolean;\n commitFailed?: boolean;\n historyAccepted?: boolean;\n}\n\n/** Publish from the Turn owner; failed storage acceptance is never retried by failure cleanup. */\nconst acceptTurnCommit = <E, R>(\n context: RunContext,\n trace: TurnTrace,\n durability: RunDurabilityHook<E, R> | undefined,\n commit: RunTurnCommit,\n): Effect.Effect<void, E | ModelProtocolError | AgentPolicyError, R> =>\n Effect.suspend(() => {\n if (trace.commitFailed) return Effect.void;\n\n const accepted = checkpointExecution(context, durability).pipe(\n Effect.andThen(() => durability?.commitTurn(commit) ?? Effect.succeed(\"committed\" as const)),\n );\n\n return Effect.onExitPrimitive(\n Effect.flatMap(accepted, (receipt) => {\n if (receipt === \"deferred\")\n return commit._tag === \"Response\" && commit.defer === true\n ? Effect.void\n : Effect.fail(\n ModelProtocolError.make({\n message: \"Durability deferred an ineligible Turn commit\",\n }),\n );\n\n if (commit._tag !== \"Partial\") {\n if (commit.response !== undefined) {\n context.pendingCommitInputs.splice(0, trace.commitInputCount ?? 0);\n trace.responseCommitted = true;\n }\n if (commit._tag === \"Settled\") trace.resultsCommitted = true;\n }\n\n return Effect.void;\n }),\n (exit) => {\n if (Exit.isFailure(exit)) trace.commitFailed = true;\n },\n );\n });\n\n/** Only stream-closed application outcomes enter the trace; provider results stay in response. */\nconst turnToolResults = (\n trace: TurnTrace,\n): Effect.Effect<ReadonlyArray<RunTurnToolResult>, ModelProtocolError> =>\n Effect.forEach(\n trace.applicationToolResults.filter((result) => result !== undefined),\n (result) =>\n Effect.map(decodeToolCallId(result.id), (toolCallId): RunTurnToolResult => ({\n toolCallId,\n toolName: result.name,\n result: result.encodedResult,\n isFailure: result.isFailure,\n ...(result.toolSelection === undefined ? {} : { toolSelection: result.toolSelection }),\n ...(result.budgetRejected === undefined ? {} : { budgetRejected: result.budgetRejected }),\n })),\n );\n\nconst settleTurn = <E, R>(\n context: RunContext,\n trace: TurnTrace,\n turn: number,\n turnId: TurnId,\n options: RunOptions<E, R>,\n completion?: RunTurnCompletion,\n): Effect.Effect<void, E | ModelProtocolError | AgentPolicyError, R> =>\n options.durability === undefined\n ? Effect.void\n : Effect.suspend(() => {\n if (trace.commitFailed || (trace.resultsCommitted && completion === undefined))\n return Effect.void;\n\n const response = trace.responseCommitted ? undefined : trace.commitResponse;\n\n return Effect.flatMap(\n trace.resultsCommitted ? Effect.succeed([]) : turnToolResults(trace),\n (results) =>\n response === undefined && results.length === 0 && completion === undefined\n ? Effect.void\n : acceptTurnCommit(context, trace, options.durability, {\n _tag: \"Settled\",\n turn,\n turnId,\n ...(response === undefined ? {} : { response }),\n results,\n ...(completion === undefined ? {} : { completion }),\n }),\n );\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 maxBufferedEvents: 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 maxBufferedEvents: 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 maxBufferedEvents: tighteningBufferLimit(\n configured?.maxBufferedEvents,\n DEFAULT_RUN_BUFFER_LIMITS.maxBufferedEvents,\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): PropertyDescriptor | undefined => {\n const descriptor = Object.getOwnPropertyDescriptor(part, key);\n\n return descriptor !== undefined && \"value\" in descriptor ? descriptor : undefined;\n };\n\n const type = read(\"type\")?.value;\n\n if (type !== \"tool-call\" && type !== \"tool-result\") return undefined;\n const name = read(\"name\")?.value;\n\n if (typeof name !== \"string\" || !hasTool(toolkit.tools, name)) return undefined;\n const tool = toolkit.tools[name];\n const payload: unknown = read(type === \"tool-call\" ? \"params\" : \"result\")?.value;\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 const descriptor = read(key);\n\n if (descriptor === undefined) return undefined;\n preflight[key] = descriptor.value;\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 makeModelResponseParsers = (toolkit: Toolkit.Any) => {\n const codec = Schema.toCodecJson(Response.StreamPart(encodedToolParameterToolkit(toolkit)));\n\n // The native encoder validates application payloads before detachment. Interpreter state uses\n // their canonical JSON, so ownership must not run application decoding transformations again.\n const ownedToolkit = Toolkit.make(\n ...Object.values(toolkit.tools).map((tool) =>\n tool.setParameters(Schema.Json).setSuccess(Schema.Json).setFailure(Schema.Json),\n ),\n );\n\n return {\n encode: Schema.encodeUnknownEffect(codec),\n decode: Schema.decodeUnknownEffect(Schema.toCodecJson(Response.StreamPart(ownedToolkit))),\n };\n};\n\n// Native Toolkits are immutable. Weak keys let discarded definitions and handler Toolkits go\n// away while each live Toolkit shares compiled parsers across response parts and Turns.\nconst modelResponseParsers = new WeakMap<\n Toolkit.Any,\n ReturnType<typeof makeModelResponseParsers>\n>();\n\nconst modelResponseParsersFor = (toolkit: Toolkit.Any) => {\n const cached = modelResponseParsers.get(toolkit);\n\n if (cached !== undefined) return cached;\n const parsers = makeModelResponseParsers(toolkit);\n\n modelResponseParsers.set(toolkit, parsers);\n\n return parsers;\n};\n\nconst captureModelResponsePartGeneral = Effect.fnUntraced(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 parsers = modelResponseParsersFor(toolkit);\n\n const encoded = yield* parsers\n .encode(part)\n .pipe(\n Effect.mapError(() =>\n ModelProtocolError.make({ message: \"Model response part failed canonical encoding\" }),\n ),\n );\n\n const retainedBytes = yield* inspectModelResponsePartCapacity(usage, encoded, limits);\n\n if (typeof structuredCloneFunction !== \"function\") {\n return yield* ModelProtocolError.make({\n message: \"Model response part could not be converted into engine-owned data\",\n });\n }\n\n const ownedEncoded = yield* Effect.try({\n try: () => {\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 return { encodedPart: ownedEncoded, retainedBytes };\n});\n\ninterface OwnedModelResponsePart {\n readonly ownedPart: Response.AnyPart;\n readonly retainedBytes: number;\n}\n\nconst decodePrimitiveModelResponsePart = Schema.decodeUnknownEffect(\n Schema.toType(\n Schema.Union([\n Response.TextStartPart,\n Response.TextDeltaPart,\n Response.TextEndPart,\n Response.ReasoningStartPart,\n Response.ReasoningDeltaPart,\n Response.ReasoningEndPart,\n ]),\n ),\n);\n\n/** Reject trailing content before its capture can run an application codec or suspend. */\nconst ownModelResponsePart = <Tools extends Record<string, Tool.Any>>(\n part: unknown,\n toolkit: Toolkit.Toolkit<Tools>,\n usage: ModelResponseBufferUsage,\n limits: EffectiveRunBufferLimits,\n finished: boolean,\n): Effect.Effect<OwnedModelResponsePart, ModelProtocolError> =>\n Effect.suspend((): Effect.Effect<OwnedModelResponsePart, ModelProtocolError> => {\n if (finished) {\n return Effect.fail(\n ModelProtocolError.make({\n message: \"Model response emitted content after its finish part\",\n }),\n );\n }\n\n const primitive =\n usage.responsePartCount < limits.maxModelResponseParts\n ? capturePrimitiveTextPart(part, limits.maxModelResponseBytes - usage.responsePartBytes)\n : undefined;\n\n // Complete primitive snapshots need validation, but no defaults or transformation.\n // Schema.toType retains every constraint from the native Response part schemas.\n if (primitive !== undefined) {\n return Effect.mapBothEager(decodePrimitiveModelResponsePart(primitive.part), {\n onFailure: () =>\n ModelProtocolError.make({ message: \"Model response part failed canonical decoding\" }),\n onSuccess: (ownedPart) => ({ ownedPart, retainedBytes: primitive.retainedBytes }),\n });\n }\n\n // Pending application codecs keep normal Effect execution in this same consumer fiber.\n return Effect.flatMapEager(\n captureModelResponsePartGeneral(part, toolkit, usage, limits),\n (captured) =>\n Effect.mapBothEager(modelResponseParsersFor(toolkit).decode(captured.encodedPart), {\n onFailure: () =>\n ModelProtocolError.make({ message: \"Model response part failed canonical decoding\" }),\n onSuccess: (ownedPart) => ({ ownedPart, retainedBytes: captured.retainedBytes }),\n }),\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, Schema.Json>;\n readonly name: keyof Tools & string;\n readonly toolCallId: ToolCallId;\n readonly validation: Result.Result<\n Option.Option<Tool.Parameters<ToolUnion<Tools>>>,\n ToolParameterRejection\n >;\n readonly tool: ToolUnion<Tools>;\n readonly declarationIndex: number;\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/** Native identity proves encoding does not transform the already validated parameters. */\nconst reusesValidatedToolParameters = (tool: Tool.Any): boolean =>\n (tool.needsApproval === undefined || tool.needsApproval === false) &&\n SchemaAST.toEncoded(tool.parametersSchema.ast) === tool.parametersSchema.ast;\n\n/**\n * Fresh responses and resumed batches validate every call before reaching this boundary.\n * Identity encodings with no approval need no second decoded value. Other codecs retain the\n * complete batch preflight, including validation of their canonical round trip, before dispatch.\n */\nconst prepareToolCall = <Tools extends Record<string, Tool.Any>>(\n toolkit: Toolkit.WithHandler<Tools>,\n call: Response.ToolCallPart<string, Schema.Json>,\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.flatMap(decodeToolCallId(call.id), (toolCallId) => {\n const prepared = (\n validation: PreparedToolCall<Tools>[\"validation\"],\n ): PreparedToolCall<Tools> => ({\n call,\n name,\n toolCallId,\n validation,\n tool,\n declarationIndex,\n });\n\n if (rejection !== undefined) return Effect.succeed(prepared(Result.fail(rejection)));\n if (reusesValidatedToolParameters(tool))\n return Effect.succeed(prepared(Result.succeed(Option.none())));\n\n return Effect.map(\n decodeToolCallParameters<Tools>(tool, call.name, copyJson(call.params)),\n (parameters) => prepared(Result.succeed(Option.some(parameters))),\n );\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 readSnapshotProperty = Effect.fnUntraced(function* (\n input: object,\n key: string,\n invalid: () => ModelProtocolError,\n optional = false,\n): Effect.fn.Return<unknown, ModelProtocolError> {\n const descriptor = yield* Effect.try({\n try: () => Object.getOwnPropertyDescriptor(input, key),\n catch: invalid,\n });\n\n if (descriptor === undefined && optional) return undefined;\n if (descriptor === undefined || !(\"value\" in descriptor)) return yield* invalid();\n\n return descriptor.value;\n});\n\nconst decodeResumedSettledCall = Effect.fnUntraced(function* (input: unknown) {\n const invalid = () =>\n ModelProtocolError.make({\n message: \"Turn resume contains an invalid settled Tool Call\",\n });\n\n if (input === null || typeof input !== \"object\") return yield* invalid();\n const id = yield* readSnapshotProperty(input, \"id\", invalid);\n const resultValue = yield* readSnapshotProperty(input, \"result\", invalid);\n const isFailure = yield* readSnapshotProperty(input, \"isFailure\", invalid);\n\n const { selection, rejected } = yield* Effect.try({\n try: () => ({\n selection: Object.getOwnPropertyDescriptor(input, \"toolSelection\"),\n rejected: Object.getOwnPropertyDescriptor(input, \"budgetRejected\"),\n }),\n catch: invalid,\n });\n\n if (\n (selection !== undefined && !(\"value\" in selection)) ||\n (rejected !== undefined && !(\"value\" in rejected))\n )\n return yield* invalid();\n\n const raw = {\n id,\n result: resultValue,\n isFailure,\n ...(rejected === undefined ? {} : { budgetRejected: rejected.value }),\n ...(selection === undefined ? {} : { toolSelection: selection.value }),\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\nconst snapshotResumedSettledCalls = Effect.fnUntraced(function* (resume: unknown, maximum: number) {\n const invalid = () =>\n ModelProtocolError.make({\n message: \"Turn resume contains an invalid settled Tool Call collection\",\n });\n\n if (resume === null || typeof resume !== \"object\") return yield* invalid();\n const settled = yield* readSnapshotProperty(resume, \"settled\", invalid);\n const isArray = yield* Effect.try({ try: () => Array.isArray(settled), catch: invalid });\n\n if (!isArray || settled === null || typeof settled !== \"object\") return yield* invalid();\n const length = yield* readSnapshotProperty(settled, \"length\", invalid);\n\n if (\n typeof length !== \"number\" ||\n !Number.isSafeInteger(length) ||\n length < 0 ||\n length > maximum\n ) {\n return yield* invalid();\n }\n const snapshot: Array<unknown> = [];\n\n for (let index = 0; index < length; index += 1) {\n snapshot.push(yield* readSnapshotProperty(settled, String(index), invalid));\n }\n\n return snapshot;\n});\n\nconst decodeResumeUsage = Effect.fnUntraced(function* (input: unknown) {\n const invalid = () =>\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 if (input === null || typeof input !== \"object\") return yield* invalid();\n const snapshot: Record<string, unknown> = {};\n\n for (const key of [\n \"usageStatus\",\n \"pricingStatus\",\n \"unobservedModelCalls\",\n \"children\",\n \"modelRestarts\",\n \"webSearchCalls\",\n ] satisfies ReadonlyArray<keyof RunResumeUsage>) {\n const value = yield* readSnapshotProperty(input, key, invalid, true);\n\n if (value !== undefined) snapshot[key] = value;\n }\n for (const key of [\n \"modelCalls\",\n \"inputTokens\",\n \"outputTokens\",\n \"lastInputTokens\",\n \"lastOutputTokens\",\n \"costMicrousd\",\n \"committedTurns\",\n \"toolCalls\",\n \"programmaticToolCalls\",\n \"consecutiveToolFailures\",\n \"finalizationUsed\",\n ] satisfies ReadonlyArray<keyof RunResumeUsage>) {\n snapshot[key] = yield* readSnapshotProperty(input, key, invalid);\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\nconst makeToolFailedEvent = Effect.fnUntraced(function* (\n context: RunContext,\n turnId: TurnId,\n call: Response.ToolCallPart<string, Schema.Json>,\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.fnUntraced(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> | undefined = context.publish === undefined ? undefined : [];\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 ?? noEvents;\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.fnUntraced(function* (\n context: RunContext,\n turnId: TurnId,\n payload: ToolEventPayload,\n): Effect.fn.Return<\n | AgentUpdateEmitted\n | SubagentRequested\n | SubagentStarted\n | SubagentProgress\n | SubagentCompleted\n | SubagentFailed\n | SubagentInterrupted\n | SubagentJoined,\n ModelProtocolError\n> {\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 prepareApprovalRequest = <Tools extends Record<string, Tool.Any>>(\n context: RunContext,\n turnId: TurnId,\n prepared: PreparedToolCall<Tools>,\n): Effect.Effect<\n RunApprovalRequest | undefined,\n ModelProtocolError | AgentPolicyError,\n Tool.HandlerServices<ToolUnion<Tools>>\n> =>\n prepareWithinDeadline(\n context,\n Effect.gen(function* () {\n if (Result.isFailure(prepared.validation)) return undefined;\n if (Option.isNone(prepared.validation.success)) return undefined;\n const decodedParams = prepared.validation.success.value;\n const approval = prepared.tool.needsApproval;\n\n const required =\n typeof approval === \"function\"\n ? yield* Effect.suspend(() => {\n // Match native Effect AI: history is readonly and may contain opaque Tool values.\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) return undefined;\n\n const toolCallId = yield* decodeToolCallId(prepared.call.id);\n\n const parameters =\n typeof approval === \"function\"\n ? yield* decodeToolCallParameters<Tools>(\n prepared.tool,\n prepared.call.name,\n copyJson(prepared.call.params),\n )\n : decodedParams;\n\n return {\n request: Response.makePart(\"tool-approval-request\", {\n approvalId: `${context.runId}:${prepared.call.id}`,\n toolCallId: prepared.call.id,\n }),\n threadId: context.threadId,\n runId: context.runId,\n turnId,\n toolCallId,\n toolName: prepared.call.name,\n parameters,\n };\n }),\n );\n\n/**\n * Resolve every native Effect AI approval before the handler scheduler starts.\n * Retaining all required requests before decisions keeps denied or unresolved\n * batches a strict no-start boundary across replacement Attempts.\n */\nconst preflightApproval = Effect.fnUntraced(function* <\n Tools extends Record<string, Tool.Any>,\n HookError,\n HookRequirements,\n>(\n context: RunContext,\n turnId: TurnId,\n prepared: PreparedToolCall<Tools>,\n request: RunApprovalRequest,\n options: RunOptions<HookError, HookRequirements>,\n): Effect.fn.Return<\n void,\n HookError | ModelProtocolError | AgentPolicyError | AgentApprovalDenied | AgentApprovalPending,\n HookRequirements | Tool.HandlerServices<ToolUnion<Tools>>\n> {\n const hook = options.approval;\n\n const decision =\n hook === undefined\n ? { _tag: \"unresolved\" as const, reason: \"No approval decision hook is available\" }\n : yield* prepareWithinDeadline(context, hook.request(request));\n\n // Canonical acceptance is fenced by its storage owner and must finish before the decision is used.\n if (hook?.commit !== undefined) yield* hook.commit(request, decision);\n const toolCallId = request.toolCallId;\n\n yield* publishEvent(context, () =>\n Effect.map(eventBase(context), (base) =>\n ApprovalRequested.make({\n ...base,\n turnId,\n toolCallId,\n toolName: prepared.call.name,\n }),\n ),\n );\n\n switch (decision._tag) {\n case \"approved\":\n return;\n case \"denied\": {\n const denied = AgentApprovalDenied.make({\n toolCallId: prepared.call.id,\n toolName: prepared.call.name,\n message: decision.reason ?? \"Tool approval was denied\",\n });\n\n yield* publishEvent(context, () =>\n Effect.map(eventBase(context), (base) =>\n ToolCallFailed.make({\n ...base,\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 );\n\n return yield* denied;\n }\n case \"unresolved\":\n return yield* AgentApprovalPending.make({\n approvalId: request.request.approvalId,\n toolCallId: prepared.call.id,\n toolName: prepared.call.name,\n message: decision.reason ?? \"Tool approval remains unresolved\",\n });\n }\n});\n\n/** Recheck every executable declaration before the durable fence and any handler start. */\nconst preflightToolAuthorization = Effect.fnUntraced(function* <HookError, HookRequirements>(\n context: RunContext,\n turnId: TurnId,\n turn: number,\n call: RunToolCallDescriptor & { readonly parameters: Schema.Json },\n options: RunOptions<HookError, HookRequirements>,\n annotations: Context.Context<never>,\n): Effect.fn.Return<\n void,\n HookError | ModelProtocolError | AgentToolAuthorizationDenied | AgentPolicyError,\n HookRequirements\n> {\n const authorization: RunToolAuthorizationHook<HookError, HookRequirements> | undefined =\n 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 || authorization === RunToolAuthorization.allowAllPolicy) return;\n\n const decision = yield* prepareWithinDeadline(\n context,\n authorization.authorize({\n threadId: context.threadId,\n runId: context.runId,\n turnId,\n turn,\n input: context.input,\n call: { ...call, parameters: copyJson(call.parameters) },\n }),\n );\n\n if (decision._tag === \"allowed\") return;\n\n const denied = AgentToolAuthorizationDenied.make({\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n message: decision.reason,\n ...(decision.cause === undefined ? {} : { cause: decision.cause }),\n });\n\n yield* publishEvent(context, () =>\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 );\n\n return yield* denied;\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* (\n context: RunContext,\n turnId?: TurnId,\n onSpan?: (span: Tracer.Span) => void,\n) {\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 onSpan?.(span);\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.logDebug(\"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 = Effect.fnUntraced(function* <\n Tools extends Record<string, Tool.Any>,\n>(\n context: RunContext,\n turnId: TurnId,\n toolkit: Toolkit.WithHandler<Tools>,\n prepared: PreparedToolCall<Tools>,\n trace: TurnTrace,\n resultBounds: ToolResultBounds,\n onWaiting: (waiting: ToolCallWaiting) => void,\n): Effect.fn.Return<\n void,\n ModelProtocolError | AgentPolicyError | AiError.AiError | Tool.HandlerError<ToolUnion<Tools>>,\n ToolSpanTelemetry | Tool.HandlerServices<ToolUnion<Tools>>\n> {\n type ToolExecutionError =\n | ModelProtocolError\n | AgentPolicyError\n | AiError.AiError\n | Tool.HandlerError<ToolUnion<Tools>>;\n const call = prepared.call;\n const toolCallId = prepared.toolCallId;\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 let toolSpanFailure: ToolSpanFailure | undefined;\n // Successful attempts need no private failure value or Schema class construction.\n const failureMarker = () => (toolSpanFailure ??= ToolSpanFailure.marker());\n let terminal = false;\n let terminalResultCommitted = false;\n\n let terminalResult:\n | { readonly encodedResult: unknown; readonly isFailure: boolean; readonly result: unknown }\n | undefined;\n\n let propagatedFailure: Cause.Cause<ToolExecutionError> | undefined;\n\n const terminalTelemetry = (outcome: ToolTelemetryOutcome, handling?: ToolFailureHandling) =>\n isolateToolDerivative(\n terminalToolTelemetry(\n telemetryDescriptor,\n outcome,\n outcome === \"failure\" ? failureMarker() : undefined,\n handling,\n ),\n );\n\n const started = Result.isFailure(prepared.validation)\n ? Effect.void\n : Effect.gen(function* () {\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 yield* publishEvent(context, () =>\n Effect.map(eventBase(context), (base) =>\n ToolCallStarted.make({ ...base, turnId, toolCallId, toolName: call.name }),\n ),\n );\n }).pipe(Effect.withLogSpan(\"AgentRuntime.tool\"));\n\n // This existing assertion widens only the native dynamic name/parameter correlation.\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, copyJson(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 = prepareWithinDeadline(\n context,\n Stream.runForEach(handlerResults, (result) =>\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 const encodedResult = toolResultForJson(prepared.tool, result);\n\n if (result.preliminary) {\n // Admission and cumulative bytes are semantic even without an observer.\n const owned = yield* ownApplicationToolProgress(context, encodedResult);\n\n yield* publishEvent(context, () =>\n Effect.map(eventBase(context), (base) =>\n ToolProgress.make({\n ...base,\n turnId,\n toolCallId,\n toolName: call.name,\n result: owned,\n providerExecuted: false,\n }),\n ),\n );\n\n return;\n }\n terminal = true;\n terminalResult = { encodedResult, isFailure: result.isFailure, result: result.result };\n }),\n ),\n );\n\n const commitTerminalResult = Effect.gen(function* () {\n // The native stream's own Scope is closed before runForEach succeeds. No late terminal,\n // native handler failure or native stream finalizer failure can follow this admission.\n yield* checkpointExecution<never, never>(context);\n if (!terminal || terminalResult === undefined)\n return yield* ModelProtocolError.make({\n message: `Tool Call ${call.id} completed without a terminal result`,\n });\n const result = terminalResult;\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 yield* exposureSnapshot(\n context.definition,\n toolSelection,\n context.toolCatalog,\n context.toolSchemaTransformer,\n );\n }\n const encodedResult = yield* boundEncodedToolResult(result.encodedResult, resultBounds);\n\n // The ordinary JSON boundary remains required; only the public Class projection is optional.\n const successResult = result.isFailure\n ? undefined\n : yield* decodeEventJson(encodedResult, \"Tool result\");\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 yield* terminalTelemetry(\n result.isFailure ? \"failure\" : \"success\",\n result.isFailure ? \"returned-to-model\" : undefined,\n );\n // Derivatives finish before optional publication, under the same call permit.\n if (observer !== undefined && result.isFailure && rejection === undefined)\n yield* prepareWithinDeadline(\n context,\n deliverToolFailure(observer, {\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: errorTag(result.result),\n }),\n );\n yield* publishEvent(context, () =>\n Effect.gen(function* () {\n const base = yield* eventBase(context);\n\n if (result.isFailure)\n return ToolCallFailed.make({\n ...base,\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 // A successful JSON encoding may be null, but never undefined after admission above.\n if (successResult === undefined)\n return yield* ModelProtocolError.make({ message: \"Missing validated Tool result\" });\n\n return ToolCallSucceeded.make({\n ...base,\n turnId,\n toolCallId,\n toolName: call.name,\n result: successResult,\n ...(toolSelection === undefined ? {} : { toolSelection }),\n providerExecuted: false,\n });\n }),\n );\n if (result.isFailure) return yield* failureMarker();\n });\n\n const failTerminalResult = Effect.fnUntraced(function* (cause: Cause.Cause<ToolExecutionError>) {\n terminal = true;\n terminalResult = undefined;\n propagatedFailure = cause;\n // The raw failure has no canonical success/result, matching the prior propagated path.\n yield* decodeToolCallId(call.id);\n trace.finalToolResultIds.add(call.id);\n terminalResultCommitted = true;\n yield* terminalTelemetry(\"failure\", \"propagated\");\n yield* publishEvent(context, () =>\n makeToolFailedEvent(context, turnId, call, Cause.squash(cause), \"propagated\"),\n );\n\n return yield* failureMarker();\n });\n\n const measured = started.pipe(\n Effect.andThen(results),\n Effect.andThen(commitTerminalResult),\n Effect.catchCause((cause) => {\n const { found, residual: toolCause } = stripToolSpanFailures(cause, toolSpanFailure);\n\n if (found) return Effect.failCause(cause);\n if (terminalResultCommitted) return Effect.failCause(toolCause);\n if (toolCause.reasons.length > 0 && toolCause.reasons.every(Cause.isInterruptReason))\n return Effect.failCause(toolCause);\n const waiting = waitingFromCause(toolCause);\n\n if (waiting !== undefined) {\n if (terminal || trace.finalToolResultIds.has(call.id))\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 onWaiting(waiting);\n\n return Effect.void;\n }\n\n return failTerminalResult(toolCause);\n }),\n Effect.withSpan(`execute_tool ${call.name}`, {\n kind: \"internal\",\n attributes: toolTelemetryAttributes(telemetryDescriptor),\n }),\n );\n\n const telemetry = yield* ToolSpanTelemetry;\n\n return yield* telemetry.isolateEffectSpanLifecycle(measured).pipe(\n Effect.catchCause((cause) => {\n const { found, restored } = restoreToolSpanFailureCause(\n cause,\n toolSpanFailure,\n propagatedFailure,\n );\n\n if (!found) return Effect.failCause(restored);\n\n return restored.reasons.length === 0 ? Effect.void : Effect.failCause(restored);\n }),\n );\n});\n\nconst executeToolBatch = Effect.fnUntraced(function* <\n Tools extends Record<string, Tool.Any>,\n HookError,\n HookRequirements,\n>(\n context: RunContext,\n turnId: TurnId,\n turn: number,\n toolkit: Toolkit.WithHandler<Tools>,\n calls: ReadonlyArray<Response.ToolCallPart<string, Schema.Json>>,\n trace: TurnTrace,\n concurrency: number,\n options: RunOptions<HookError, HookRequirements>,\n brokerAccounting: { readonly maxToolCalls: number; readonly declaredToolCalls: number },\n resultBounds: ToolResultBounds,\n settledCallIds?: ReadonlySet<string>,\n): Effect.fn.Return<\n void,\n | HookError\n | ModelProtocolError\n | AgentPolicyError\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 | Scope.Scope\n | Tool.HandlerServices<ToolUnion<Tools>>\n> {\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 (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 const prepareCalls = Effect.forEach(\n calls.flatMap((call, declarationIndex) =>\n settledCallIds?.has(call.id) ? [] : [{ call, declarationIndex }],\n ),\n ({ call, declarationIndex }) =>\n prepareToolCall(toolkit, call, declarationIndex, trace.toolParameterRejections.get(call.id)),\n );\n\n const needsParameterDecoding = calls.some(\n (call) =>\n !settledCallIds?.has(call.id) &&\n !trace.toolParameterRejections.has(call.id) &&\n hasTool(toolkit.tools, call.name) &&\n !reusesValidatedToolParameters(toolkit.tools[call.name]),\n );\n\n const prepared = yield* needsParameterDecoding\n ? prepareWithinDeadline(context, prepareCalls)\n : Effect.flatMap(\n Clock.currentTimeMillis,\n (\n now,\n ): Effect.Effect<\n Array<PreparedToolCall<Tools>>,\n ModelProtocolError | AgentPolicyError,\n Tool.HandlerServices<ToolUnion<Tools>>\n > =>\n context.durationDeadlineMillis - now <= 0\n ? Effect.fail(context.durationFailure)\n : prepareCalls,\n );\n\n if (\n prepared.some((call) => Context.get(call.tool.annotations, ContextRolloverTool)) &&\n calls.length !== 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 descriptors = trace.applicationCallDescriptors.filter(\n (call) => !trace.toolParameterRejections.has(call.toolCallId),\n );\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 durability = options.durability;\n const hookServices = yield* Effect.context<HookRequirements>();\n\n yield* checkpointExecution(context, durability);\n\n const approvalCalls = prepared.filter(\n (call) =>\n Result.isSuccess(call.validation) &&\n call.tool.needsApproval !== undefined &&\n call.tool.needsApproval !== false,\n );\n\n if (approvalCalls.length > 0) {\n const approvals = yield* Effect.forEach(approvalCalls, (call) =>\n Effect.map(prepareApprovalRequest(context, turnId, call), (request) => ({ call, request })),\n );\n\n const required = approvals.flatMap(({ request }) => (request === undefined ? [] : [request]));\n\n if (options.approval?.prepareBatch !== undefined && required.length > 0)\n yield* options.approval.prepareBatch(required);\n yield* checkpointExecution(context, durability);\n for (const { call, request } of approvals) {\n if (request === undefined) continue;\n yield* preflightApproval(context, turnId, call, request, options);\n yield* checkpointExecution(context, durability);\n }\n }\n if (\n (options.toolAuthorization !== undefined &&\n options.toolAuthorization !== RunToolAuthorization.allowAllPolicy) ||\n options.subagentGrant !== undefined\n ) {\n for (const call of executableDescriptors) {\n yield* preflightToolAuthorization(\n context,\n turnId,\n turn,\n call,\n options,\n toolkit.tools[call.toolName]?.annotations ?? Context.empty(),\n );\n yield* checkpointExecution(context, durability);\n }\n }\n if (\n durability !== undefined &&\n executableDescriptors.some(\n (call) => call.executionClass !== \"readonly\" || call.executionKind !== \"ordinary\",\n )\n )\n yield* durability.checkToolDispatch;\n\n const stepServiceFor = (call: PreparedToolCall<Tools>): DurableStepService =>\n durability === undefined\n ? passthroughDurableStep()\n : makeDurableStepService(call.toolCallId, durability.step, hookServices);\n\n const batchSubagentDurability: SubagentDurabilityService =\n options.subagent === undefined\n ? ephemeralSubagentDurability\n : makeSubagentDurabilityService(options.subagent, hookServices);\n\n const waitingByDeclaration = new Map<number, ToolCallWaiting>();\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 parallel.push(call);\n }\n if (parallel.length > 0) groups.push(parallel);\n\n let updatesOpen = true;\n\n const closedSink = () =>\n RunEventSinkClosedError.make({\n message: \"Tool event was emitted after its batch settled or raw admission failed\",\n });\n\n const emitPayload = (payload: ToolEventPayload): Effect.Effect<void, RunEventSinkClosedError> =>\n Effect.gen(function* () {\n if (!updatesOpen || Deferred.isDoneUnsafe(context.progressFailure))\n return yield* closedSink();\n // This existing Schema owner validates raw payloads, including Completed's cross-field\n // filter, even headless. Only raw inbound payloads retain this semantic Class construction.\n const admitted = yield* Effect.exit(stampSubagentEvent(context, turnId, payload));\n\n if (Exit.isFailure(admitted)) {\n updatesOpen = false;\n // Complete the independent Run failure before returning a handler-visible error. Toolkit\n // normalization or a handler catch can never consume the authoritative admission Cause.\n yield* Deferred.failCause(context.progressFailure, admitted.cause);\n\n return yield* closedSink();\n }\n const event = admitted.value;\n\n if (event._tag !== \"AgentUpdateEmitted\" && !context.liveChildren.has(event.childRunId)) {\n if (\"usage\" in event && event.usage !== undefined) {\n context.childUsage.set(\n event.childRunId,\n Effect.succeed(\n RunUsageReport.make({\n usage: event.usage,\n delegatedUsage: event.delegatedUsage ?? unknownRunTotals(),\n }),\n ),\n );\n } else if (event._tag === \"SubagentStarted\" && !context.childUsage.has(event.childRunId)) {\n context.childUsage.set(\n event.childRunId,\n Effect.succeed(\n RunUsageReport.make({\n usage: unknownRunTotals(),\n delegatedUsage: unknownRunTotals(),\n }),\n ),\n );\n }\n }\n if (context.publish !== undefined) yield* context.publish([event]);\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(RunEventSinkClosedError.make({ message: \"Unsupported Tool event payload\" }))\n : emitPayload(payload),\n };\n\n const updateAcceptance = yield* AgentUpdateAcceptance;\n\n const updateEmitter: Emitter[\"Service\"] = {\n emit: (request) =>\n context.updatePermits.withPermit(\n Effect.gen(function* () {\n if (!updatesOpen) return yield* UpdateError.make({ 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* UpdateError.make({ reason: \"identity\" });\n\n const updateId = yield* Schema.decodeEffect(IdempotencyKey)(request.updateId).pipe(\n Effect.mapError(() => UpdateError.make({ reason: \"validation\" })),\n );\n\n const value = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(\n JSON.stringify(request.value),\n ).pipe(Effect.mapError(() => UpdateError.make({ 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* UpdateError.make({ 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* UpdateError.make({ reason: \"capacity\" });\n\n const snapshot = boundedCanonicalJsonSnapshot(value, bytes);\n\n if (snapshot === undefined) return yield* UpdateError.make({ 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(() => UpdateError.make({ 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* UpdateError.make({ 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 yield* emitPayload({ _tag: \"AgentUpdateEmitted\", update }).pipe(\n Effect.mapError(() => UpdateError.make({ reason: \"unavailable\" })),\n );\n\n return update;\n }),\n ),\n };\n\n // The permit covers the child's complete lifetime, including descendant cleanup. The call\n // owns its resource Scope and its fiber belongs to the enclosing Turn Scope. The native bracket\n // joins or interrupts it before releasing the permit, without another supervisor Scope.\n const permits = yield* Semaphore.make(concurrency);\n\n const handlers = Effect.gen(function* () {\n for (const group of groups) {\n yield* Effect.forEach(\n group,\n (call) =>\n permits.withPermit(\n Effect.acquireUseRelease(\n Effect.forkScoped(\n Effect.scoped(\n Effect.gen(function* () {\n yield* checkpointExecution(context, durability);\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: durability?.reservePolicyUsage,\n hookServices,\n });\n\n const step = stepServiceFor(call);\n const subagent = subagentHost(source);\n const messaging = messagingHost(source);\n const catalog = { entries: context.toolCatalog };\n\n return yield* 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 // Match the original providers' outer-to-inner order with one restoration.\n Effect.updateContext(\n (\n services: Context.Context<\n ToolSpanTelemetry | Tool.HandlerServices<ToolUnion<Tools>>\n >,\n ) =>\n services.pipe(\n Context.add(CurrentToolCatalog, catalog),\n Context.add(ToolBroker, broker.service),\n Context.add(MessagingHost, messaging),\n Context.add(SubagentHost, subagent),\n Context.add(DurableStep, step),\n ),\n ),\n Effect.ensuring(Effect.sync(() => broker.close())),\n );\n }),\n ),\n ),\n Fiber.join,\n Fiber.interrupt,\n ),\n ),\n { concurrency: group.length === 1 ? 1 : \"unbounded\", discard: true },\n );\n // Each following call checks before dispatch; the batch owner checks again\n // after the final group, its cleanup, and the optional budget guard.\n }\n }).pipe(\n Effect.updateContext(\n (\n services: Context.Context<\n | HookRequirements\n | ToolSpanTelemetry\n | ProgrammaticToolAuthorization\n | Scope.Scope\n | Tool.HandlerServices<ToolUnion<Tools>>\n >,\n ) =>\n services.pipe(\n Context.add(SubagentDurability, batchSubagentDurability),\n Context.add(Emitter, updateEmitter),\n Context.add(RunEventSink, batchSink),\n ),\n ),\n Effect.ensuring(\n Effect.sync(() => {\n updatesOpen = false;\n }),\n ),\n );\n\n // A genuine sibling failure exits here with its original Cause after sibling cleanup. Raw\n // admissions are awaited inline, so there is no secondary drainer to join or error to delay.\n yield* guardBudgetEffect(handlers, options.budget);\n yield* checkpointExecution(context, durability);\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) return;\n\n const child = (signal: ToolCallWaiting) => ({\n toolCallId: signal.toolCallId,\n childThreadId: signal.childThreadId,\n childSubmissionId: signal.childSubmissionId,\n childRunId: signal.childRunId,\n });\n\n if (durability !== undefined) {\n const results = yield* turnToolResults(trace);\n\n if (results.length > 0)\n yield* acceptTurnCommit(context, trace, durability, {\n _tag: \"Partial\",\n turn,\n turnId,\n results,\n });\n }\n\n return yield* AgentChildPending.make({\n children: [child(first), ...rest.map(child)],\n message: `${waiting.length} durable delegation ${waiting.length === 1 ? \"call is\" : \"calls are\"} waiting on attached children; the Run suspended without settling`,\n });\n});\n\nconst schedulingConcurrency = Effect.fnUntraced(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 const prepared = context.preparedCompactionSource;\n const modelSource = prepared?.modelSource;\n\n const messages =\n modelSource === undefined || prepared === undefined\n ? history.content\n : [...modelSource.content, ...history.content.slice(prepared.sourceLength)];\n\n yield* options.onHistory(\n history,\n Prompt.fromMessages(buildCompactedView(messages, context.compaction)),\n );\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 if (options.durability !== undefined) context.pendingCommitInputs.push(...additions.content);\n yield* advanceHistory(context, history, options);\n\n return history;\n });\n\n/**\n * Toolkit uses the declared codec's raw encoding. A Void encoding needs Effect's\n * JSON representation before entering history or the broker; explicit encodings\n * and failure results remain authoritative.\n */\nconst toolResultForJson = (tool: Tool.Any, result: Tool.HandlerResult<Tool.Any>): unknown => {\n if (\n !result.isFailure &&\n result.encodedResult === undefined &&\n SchemaAST.isVoid(SchemaAST.toEncoded(tool.successSchema.ast))\n ) {\n return Schema.encodeSync(Schema.toCodecJson(Schema.Void))(undefined);\n }\n\n return result.encodedResult;\n};\n\nconst decodeBoundedToolResult = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));\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 on the measured representation.\n */\nconst boundEncodedToolResult = (\n encodedResult: unknown,\n bounds: ToolResultBounds,\n): Effect.Effect<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 Effect.succeed(unserializableToolResult(cause));\n }\n if (text === undefined) {\n return Effect.succeed(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 // Stay in the caller's Effect; a synchronous decoder would start another runtime fiber.\n return decodeBoundedToolResult(bounded).pipe(Effect.orElseSucceed(unserializableToolResult));\n};\n\nconst durableResultBounds = <E, R>(\n bounds: ToolResultBounds,\n options: RunOptions<E, R>,\n turn: number,\n): ToolResultBounds =>\n ToolResultBounds.make({\n maxBytes: Math.min(\n bounds.maxBytes,\n options.durability?.toolResultMaxBytes ?? bounds.maxBytes,\n options.resume?.turn === turn\n ? (options.resume.toolResultMaxBytes ?? bounds.maxBytes)\n : bounds.maxBytes,\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. Capable adapters receive trailing system guidance,\n * leaving the preceding user/tool result available as a cache-write boundary.\n */\nconst outgoingModelPrompt = (\n policy: AgentPolicy,\n context: RunContext,\n prepared: Prompt.Prompt,\n turn: number,\n declaredToolCalls: number,\n systemMessagesInHistory: boolean,\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 systemMessagesInHistory\n ? Prompt.systemMessage({ content: status })\n : Prompt.userMessage({ content: [Prompt.textPart({ text: status })] }),\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 isWebSearchAction = Schema.is(\n Schema.Struct({\n action: Schema.Struct({ type: Schema.Literal(\"search\") }),\n }),\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 decodeUsageTotal = Schema.decodeEffect(Schema.Natural);\nconst decodeProviderUsage = Schema.decodeEffect(ProviderUsage);\n\nconst decodeProviderUsageTotal = (value: number): Effect.Effect<number, ModelProtocolError> =>\n decodeUsageTotal(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<\n RunCostEstimateRequest,\n \"response\" | \"finishMetadata\" | \"purpose\" | \"webSearchCalls\"\n > = {},\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 webSearchCalls = yield* decodeProviderUsageTotal(response.webSearchCalls ?? 0);\n\n const providerUsage = yield* decodeProviderUsage(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 = 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 = disjointReportedUncached + cacheRead + cacheWrite;\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 = 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 // Validate the complete additive components before pricing or staging usage.\n const inputUsage = yield* InputTokenUsage.makeEffect({\n total: inputTokens,\n uncached,\n cacheRead: normalizedCacheRead,\n cacheWrite: normalizedCacheWrite,\n }).pipe(Effect.mapError(() => invalidProviderUsage()));\n\n const outputUsage = yield* OutputTokenUsage.makeEffect({\n total: outputTokens,\n text,\n reasoning: normalizedReasoning,\n }).pipe(Effect.mapError(() => invalidProviderUsage()));\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, {\n provider,\n model,\n usage,\n ...response,\n webSearchCalls,\n });\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 webSearchCalls,\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: inputUsage,\n outputTokens: outputUsage,\n costMicrousd,\n });\n\n const modelCalls = yield* decodeProviderUsageTotal(context.modelCalls + 1);\n\n const cumulativeWebSearchCalls =\n context.webSearchCalls === undefined\n ? undefined\n : yield* decodeProviderUsageTotal(context.webSearchCalls + webSearchCalls);\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.webSearchCalls = cumulativeWebSearchCalls;\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> | undefined = context.publish === undefined ? undefined : [];\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: warnings ?? noEvents, 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.publish !== undefined && 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 if (trace.providerStagedEventCount >= 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 context: RunContext,\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 if (payload._tag === \"ToolProgress\") {\n // Measure the same bounded, normalized JSON used by observed progress. Only its\n // scalar charge is retained headless; malformed response closure charges nothing.\n const text = yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Json))(\n Option.getOrThrow(normalizedResult),\n ).pipe(Effect.mapError(() => toolProgressLimitError(context)));\n\n trace.providerProgressBytes += utf8ByteLength(text);\n }\n if (trace.providerResultPayloads !== undefined) {\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 }\n trace.providerStagedEventCount++;\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 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.fnUntraced(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.fnUntraced(function* (\n context: RunContext,\n view: ReadonlyArray<Prompt.Message>,\n systemMessagesInHistory: boolean,\n staticInstructions: Prompt.RawInput | undefined,\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(\n prepareModelPrompt(\n Prompt.fromMessages(view),\n undefined,\n systemMessagesInHistory,\n staticInstructions,\n ).content,\n );\n});\n\nconst snapshotCompactionMessages = (messages: ReadonlyArray<Prompt.Message>) =>\n 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\nconst HttpStatus = AiError.HttpResponseDetails.fields.status.check(\n Schema.isBetween({ minimum: 100, maximum: 599 }),\n);\n\nconst decodeHttpErrorPayload = Schema.decodeUnknownOption(\n Schema.Union([Schema.Struct({ code: HttpStatus }), Schema.Struct({ status: HttpStatus })]),\n);\n\n/** Native error parts carry unknown payloads; classify only validated HTTP statuses. */\nconst isTransientErrorPayload = (error: Response.ErrorPart[\"error\"]): boolean =>\n Option.exists(\n decodeHttpErrorPayload(error),\n (payload) =>\n AiError.reasonFromHttpStatus({ status: \"code\" in payload ? payload.code : payload.status })\n .isRetryable,\n );\n\n/** Content streamed before a failure makes the call unsafe to repeat. */\nconst hasStreamedContent = (trace: TurnTrace): boolean =>\n trace.toolCalls.size > 0 ||\n trace.parts.some((part) => part.type !== \"response-metadata\" && part.type !== \"error\");\n\nconst MODEL_RETRY_BASE = Duration.seconds(1);\nconst MODEL_RETRY_MAX_DELAY = Duration.seconds(30);\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 changed: boolean;\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> | undefined = context.publish === undefined ? undefined : [];\n let changed = false;\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: events ?? noEvents, changed };\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 consumeSummaryPart = Effect.fnUntraced(function* (owned: OwnedModelResponsePart) {\n responseUsage.responsePartCount++;\n responseUsage.responsePartBytes += owned.retainedBytes;\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 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 const summaryExit = yield* enforceDurationDeadline(\n guardBudgetStream(LanguageModel.streamText({ prompt: summarizerPrompt }), options.budget),\n context.durationDeadlineMillis,\n context.durationFailure,\n ).pipe(\n Stream.provideServiceEffect(Tracer.Tracer, modelTelemetryTracer(context)),\n Stream.runForEach((part) =>\n ownModelResponsePart(\n part,\n Toolkit.empty,\n responseUsage,\n context.bufferLimits,\n summaryFinished,\n ).pipe(Effect.flatMap(consumeSummaryPart)),\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\n ? generate\n : Effect.scoped(\n Effect.gen(function* () {\n const services = yield* prepareWithinDeadline(\n context,\n Layer.build(Layer.fresh(model)),\n );\n\n return yield* Effect.provide(generate, services);\n }),\n );\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) =>\n enforceDurationDeadline(stream, context.durationDeadlineMillis, context.durationFailure),\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 changed = true;\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: events ?? noEvents, changed };\n });\n\nconst decodeInput = <AgentValue extends Agent.Any>(\n agent: AgentValue,\n input: unknown,\n): Effect.Effect<\n Agent.Input<AgentValue>,\n AgentInputDecodeError,\n AgentValue[\"definition\"][\"input\"][\"DecodingServices\"]\n> =>\n Schema.decodeUnknownEffect<AgentValue[\"definition\"][\"input\"]>(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputDecodeError.make({\n message: cause.message,\n }),\n ),\n );\n\nconst evaluateInstructions = <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\nconst encodeInput = <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<AgentValue[\"definition\"][\"input\"]>(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\nconst renderInputPromptEffect = <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.gen(function* () {\n const encoded = yield* Effect.try({\n try: () => JSON.stringify(encodedInput),\n catch: (cause) =>\n AgentInputError.make({\n message: `Unable to materialize Agent input: ${errorMessage(cause)}`,\n }),\n });\n\n if (encoded === undefined)\n return yield* AgentInputError.make({\n message: \"Unable to materialize Agent input: Agent input cannot be represented as JSON\",\n });\n\n return encoded;\n })\n : Effect.suspend(() => {\n const result = inputPrompt(decodedInput);\n\n return Effect.isEffect(result) ? result : Effect.succeed(result);\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, Error, Requirements>(\n inputPrompt: InputPromptSource<Input, Error, Requirements> | undefined,\n decodedInput: Input,\n encodedInput: unknown,\n): Effect.Effect<Prompt.RawInput, Error | AgentInputError, Requirements> {\n return renderInputPromptEffect(inputPrompt, decodedInput, encodedInput);\n}\n\nconst makeInitialPrompt = (\n instructions: Prompt.RawInput,\n inputPrompt: Prompt.RawInput,\n history: Prompt.Prompt,\n): Effect.Effect<Prompt.Prompt, AgentInputError> =>\n Effect.suspend(() =>\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 decodeToolCallIdValue = Schema.decodeEffect(ToolCallId);\nconst decodeProviderToolCallIdValue = Schema.decodeEffect(ProviderToolCallId);\nconst decodeProviderResponsePartIdValue = Schema.decodeEffect(ProviderResponsePartId);\nconst decodeJson = Schema.decodeUnknownEffect(Schema.Json);\n\nconst decodeToolCallId = (id: string) =>\n Effect.suspend(() =>\n decodeToolCallIdValue(id).pipe(\n Effect.mapError((cause) =>\n ModelProtocolError.make({\n message: `Invalid Tool Call ID: ${cause.message}`,\n }),\n ),\n ),\n );\n\nconst decodeProviderToolCallId = (id: string) =>\n decodeProviderToolCallIdValue(id).pipe(\n Effect.mapErrorEager(() =>\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\nconst decodeProviderResponsePartId = (id: string) =>\n decodeProviderResponsePartIdValue(id).pipe(\n Effect.mapErrorEager(() =>\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\nconst validateProviderPartIdentifiers = Effect.fnUntracedEager(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 = (\n value: unknown,\n label: string,\n): Effect.Effect<Schema.Json, ModelProtocolError> =>\n Effect.suspend(() =>\n decodeJson(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// Yield the returned Effect immediately and exactly once from the executing stream\n// consumer: construction runs the synchronous prefix, mutating trace counters and maps.\n// Application codecs and events still suspend. The enclosing model request owns the span.\nconst processModelPart = Effect.fnUntracedEager(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 events: Array<RunEvent> | undefined,\n): Effect.fn.Return<\n void,\n ModelProtocolError,\n | Tool.HandlerServices<ToolUnion<Tools>>\n | Tool.ParametersSchema<ToolUnion<Tools>>[\"EncodingServices\"]\n> {\n // Ownership checked this part against the cumulative count and byte limits.\n trace.responsePartCount++;\n trace.responsePartBytes += retainedBytes;\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 // 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 if (events === undefined) return;\n\n events.push(\n TextDelta.make({\n ...(yield* eventBase(context)),\n turnId,\n text: part.delta,\n }),\n );\n\n return;\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 if (events === undefined) return;\n\n events.push(\n ReasoningDelta.make({\n ...(yield* eventBase(context)),\n turnId,\n text: part.delta,\n }),\n );\n\n return;\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 if (Tool.isProviderDefined(tool) && !tool.requiresHandler && !part.providerExecuted) {\n return yield* ModelProtocolError.make({\n message: `Tool ${part.name} must execute at the provider`,\n });\n }\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: AiError.ToolParameterValidationError.make({\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 const executionParameters = copyJson(parameters);\n\n trace.applicationToolCalls.push({ ...canonicalCall, params: executionParameters });\n trace.applicationCallDescriptors.push({\n toolCallId,\n toolName: part.name,\n parameters: executionParameters,\n executionClass: getToolExecutionClass(tool),\n executionKind: getToolExecutionKind(tool.annotations),\n });\n }\n\n if (events === undefined) return;\n\n const declared = ToolCallDeclared.make({\n ...(yield* eventBase(context)),\n turnId,\n toolCallId,\n toolName: part.name,\n parameters: copyJson(parameters),\n providerExecuted: part.providerExecuted,\n });\n\n events.push(declared);\n\n return;\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(context, 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(context, 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(context, 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 snapshot = yield* snapshotStagedProviderEvent(trace, {\n _tag: \"TurnCompleted\",\n finishReason: part.reason,\n });\n\n trace.turnCompletion = part.reason;\n trace.providerStagedEventCount++;\n trace.providerStagedPayloadBytes += snapshot.bytes;\n\n return;\n }\n\n if (events === undefined) return;\n\n events.push(\n TurnCompleted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n finishReason: part.reason,\n }),\n );\n\n return;\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.fnUntraced(function* <AgentValue extends Agent.Any>(\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<AgentValue[\"definition\"][\"output\"]>(\n agent.definition.output,\n )(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.fnUntraced(function* <AgentValue extends Agent.Any>(\n agent: AgentValue,\n candidate: unknown,\n) {\n const encoded = yield* Schema.encodeUnknownEffect<AgentValue[\"definition\"][\"output\"]>(\n agent.definition.output,\n )(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<AgentValue[\"definition\"][\"output\"]>(\n agent.definition.output,\n )(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.fnUntraced(function* <AgentValue extends Agent.Any>(\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 tools: AgentValue[\"definition\"][\"toolkit\"][\"tools\"] = agent.definition.toolkit.tools;\n const tool = 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<\n AgentValue[\"definition\"][\"toolkit\"][\"tools\"][string][\"parametersSchema\"]\n >(tool.parametersSchema)(parameters).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<\n AgentValue[\"definition\"][\"toolkit\"][\"tools\"][string][\"successSchema\"]\n >(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.fnUntraced(function* <AgentValue extends Agent.Any>(\n agent: AgentValue,\n declaration: CompletionToolDeclaration,\n parameters: unknown,\n result: unknown,\n) {\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.fnUntraced(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\nconst encodeRunDispositionCandidate = Effect.fnUntraced(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 && declaration.workerLifecycle === 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 if (declaration.workerLifecycle === \"assignment\") {\n return yield* Schema.decodeUnknownEffect(AssignmentDisposition)(encoded).pipe(\n Effect.mapError((cause) =>\n AgentRunDispositionError.make({\n cause,\n message: \"Assignment disposition must encode completed or waiting\",\n }),\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 = <Output, DispositionSchema extends Schema.Top>(\n declaration: RunDispositionDeclaration<Output, DispositionSchema>,\n encoded: Schema.Json,\n): Effect.Effect<\n DispositionSchema[\"Type\"],\n AgentRunDispositionError,\n DispositionSchema[\"DecodingServices\"]\n> =>\n Schema.decodeEffect(declaration.schema)(encoded).pipe(\n Effect.mapError((cause) =>\n AgentRunDispositionError.make({\n cause,\n message: cause.message,\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 restarting?: boolean;\n readonly prompt: Prompt.Prompt;\n readonly turn: number;\n readonly toolCalls: number;\n}\n\ntype TurnOutput = RunCompleted | NextTurn;\n\nconst nextTurn = (\n prompt: Prompt.Prompt,\n turn: number,\n toolCalls: number,\n): Effect.Effect<TurnOutput> => Effect.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 restarting = false,\n): Effect.Effect<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements> | Scope.Scope\n> =>\n Effect.flatten(\n Effect.gen(function* () {\n yield* checkpointExecution(context, options.durability);\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 failExecution(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 failExecution(\n AgentPolicyError.make({\n limit: \"turns\",\n message: `Agent exceeded its ${bounds.maxTurns} Turn limit`,\n }),\n );\n }\n if (context.finalizationUsed && !restarting) {\n return failExecution(\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\n ? { prompt }\n : yield* prepareWithinDeadline(context, options.context.prepare(contextRequest));\n\n if (context.resolvedModel && modelContext.modelCall !== undefined) {\n return yield* AiError.AiError.make({\n module: \"AgentRuntime\",\n method: \"resolveModel\",\n reason: AiError.InvalidRequestError.make({\n description: \"Context preparation cannot replace a thread-resolved model\",\n }),\n });\n }\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 // Estimates belong to this prepared prompt. Rebuild the cache after every context\n // preparation so caller-owned message identities never carry counts into another turn.\n const messageTokenEstimates = new WeakMap<Prompt.Message, number>();\n\n const estimatePreparedMessage = (message: Prompt.Message) => {\n const cached = messageTokenEstimates.get(message);\n\n if (cached !== undefined) return cached;\n const tokens = estimateMessageTokens(message);\n\n messageTokenEstimates.set(message, tokens);\n\n return tokens;\n };\n\n const compactor = yield* ContextCompactor;\n\n const messageTokenEstimator =\n modelContext.modelCall?.estimateMessageTokens ??\n (compactor.estimate === estimatePromptTokens ? estimatePreparedMessage : undefined);\n\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 ).pipe((effect) =>\n visibility === undefined ? effect : prepareWithinDeadline(context, effect),\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 // Hosted tools may execute before emitting a response part. Only readonly\n // hosted tools are safe to repeat after a failure or joined-input restart.\n const canRepeatModelCall = !Object.values(modelToolkit.tools).some(\n (tool) => Tool.isProviderDefined(tool) && !Context.get(tool.annotations, Tool.Readonly),\n );\n\n const estimateCallTokens = (messages: ReadonlyArray<Prompt.Message>) =>\n prepareWithinDeadline(context, estimateContextTokens(messages, messageTokenEstimator));\n\n const modelServices =\n modelContext.modelCall === undefined\n ? undefined\n : yield* prepareWithinDeadline(\n context,\n Layer.build(Layer.fresh(modelContext.modelCall.model)),\n );\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 provider = yield* withCallModel(Model.ProviderName);\n\n // Older adapters do not expose this native capability. Keep their safe\n // projection; only the established OpenAI and xAI transports default to it.\n // Evaluate against this call's services so scoped model overrides are honored.\n const callModel: LanguageModel.LanguageModel & {\n readonly supportsSystemMessagesInHistory?: Effect.Effect<boolean> | undefined;\n } = yield* withCallModel(LanguageModel.LanguageModel);\n\n const systemMessagesInHistory =\n callModel.supportsSystemMessagesInHistory === undefined\n ? provider === \"openai\" || provider === \"xai\"\n : yield* withCallModel(callModel.supportsSystemMessagesInHistory);\n\n const staticInstructions =\n typeof agent.definition.instructions === \"function\"\n ? undefined\n : agent.definition.instructions;\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 if (context.preparedCompactionSource !== undefined) {\n context.preparedCompactionSource.modelSource = modelContext.prompt;\n context.preparedCompactionSource.sourceLength = prompt.content.length;\n }\n\n let restartRequested = false;\n let responseStarted = false;\n let activeModelSpan: Tracer.Span | undefined;\n let activeProvisionalText: ProvisionalTextModelHandle | undefined;\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: context.publish === undefined ? undefined : [],\n providerStagedEventCount: 0,\n providerStagedPayloadBytes: 0,\n providerProgressBytes: 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 = 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 if (context.publish === undefined) return;\n\n yield* context.publish([\n TurnStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n }),\n ]);\n yield* context.publish([\n ModelStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n }),\n ]);\n\n return;\n }).pipe(Effect.withLogSpan(\"AgentRuntime.model\"));\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(\n policy,\n context,\n Prompt.empty,\n turn,\n priorToolCalls,\n systemMessagesInHistory,\n ).pipe(withCallModel);\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. Full\n // estimates exclude system copies removed by the provider projection;\n // canonical indices still locate appended content and compaction coverage.\n const estimateSourceContext = (view: ReadonlyArray<Prompt.Message>) =>\n options.context === undefined && options.transientContext === undefined\n ? nextContextEstimate(context, view, systemMessagesInHistory, staticInstructions)\n : estimateCallTokens(\n prepareModelPrompt(\n Prompt.fromMessages(view),\n undefined,\n systemMessagesInHistory,\n staticInstructions,\n ).content,\n );\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> = noEvents;\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.changed) 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 if (context.publish !== undefined) preEvents = [...preEvents, ...outcome.events];\n if (outcome.changed) 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* prepareWithinDeadline(\n context,\n options.transientContext\n .load(contextRequest)\n .pipe(Effect.flatMap(transientInputToPrompt)),\n );\n\n const derivedPrompt =\n options.transientContext === undefined\n ? canonicalDecoration\n : yield* outgoingModelPrompt(\n policy,\n context,\n transientContext,\n turn,\n priorToolCalls,\n systemMessagesInHistory,\n ).pipe(withCallModel);\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 if (context.publish !== undefined) preEvents = [...preEvents, ...outcome.events];\n if (outcome.changed) 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 webSearchCalls: new Set(\n trace.parts.flatMap((part) => {\n if (\n (part.type !== \"tool-call\" && part.type !== \"tool-result\") ||\n !part.providerExecuted\n )\n return [];\n const tool = agent.definition.toolkit.tools[part.name];\n\n if (\n tool === undefined ||\n !Tool.isProviderDefined(tool) ||\n ![\"web_search\", \"web_search_preview\"].includes(tool.providerName)\n )\n return [];\n\n // OpenAI bills search actions, not opening/finding within returned pages.\n // Preview tools carry the action on results rather than call parameters.\n return !tool.id.startsWith(\"openai.\") ||\n isWebSearchAction(part.type === \"tool-call\" ? part.params : part.result)\n ? [part.id]\n : [];\n }),\n ).size,\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 let failedUsageCause:\n | Cause.Cause<AgentRuntimeFailure<typeof agent, HookError, InstructionError>>\n | undefined;\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.fnUntraced(function* () {\n if (trace.usageConsumed) return;\n trace.usageConsumed = true;\n if (trace.usage === undefined) {\n return yield* noteIncompleteUsage(context, turn);\n }\n const exit = yield* consumeTurnUsage(0).pipe(Effect.exit);\n\n if (Exit.isFailure(exit)) failedUsageCause = exit.cause;\n });\n\n const attempt = (\n basis: Prompt.Prompt,\n ): Effect.Effect<\n void,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | Scope.Scope\n > =>\n Effect.flatten(\n outgoingModelPrompt(\n policy,\n context,\n prepareModelPrompt(\n Prompt.concat(basis, transientContext),\n outputContract._tag === \"rendered\" ? outputContract.part : undefined,\n systemMessagesInHistory,\n staticInstructions,\n ),\n turn,\n priorToolCalls,\n systemMessagesInHistory,\n ).pipe(\n withCallModel,\n Effect.flatMap((providerPrompt) =>\n Effect.gen(function* () {\n yield* checkpointExecution(context, options.durability);\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 let provisionalText: ProvisionalTextModelHandle | undefined;\n\n // Unbounded calls need no admission estimate. Context Tools still obtain the\n // same live estimate on demand, without charging every outgoing request for it.\n const trackContext =\n contextTokenLimit === undefined && policy.tokenBudget === undefined\n ? Effect.sync(() => {\n context.windowTokens = () => compactor.estimate(providerPrompt.content);\n })\n : estimateCallTokens(providerPrompt.content).pipe(\n Effect.map((tokens) => tokens + toolSchemaTokens),\n Effect.tap((estimatedTokens) =>\n contextTokenLimit !== undefined &&\n (options.context !== undefined ||\n 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 );\n\n return yield* trackContext.pipe(\n Effect.as(\n // Transport-only tools retain existential schema services; the enclosing attempt keeps the Agent's declared requirements.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n guardBudgetStream(\n LanguageModel.streamText({\n // Every attempt, including an overflow retry, places the\n // contract in the leading system block before appending\n // transient run status.\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 // Provider-held responses retain prior model-only context.\n // Isolate tracking when a later request can discard it.\n (stream) =>\n policy.runStatus === \"appended\" ||\n options.context !== undefined ||\n options.transientContext !== undefined\n ? stream.pipe(\n Stream.provideServiceEffect(\n ResponseIdTracker.ResponseIdTracker,\n ResponseIdTracker.make,\n ),\n )\n : stream,\n Stream.provideServiceEffect(\n Tracer.Tracer,\n modelTelemetryTracer(context, turnId, (span) => {\n activeModelSpan = span;\n }),\n ),\n Stream.onStart(\n Effect.gen(function* () {\n const attempt = yield* CurrentProvisionalTextAttempt;\n\n trace.usageConsumed = false;\n provisionalText =\n !restartRequested && attempt?.threadId === context.threadId\n ? attempt.openModel(context.runId, turnId)\n : undefined;\n activeProvisionalText = provisionalText;\n }),\n ),\n Stream.runForEachArray((parts) =>\n Effect.gen(function* () {\n for (const part of parts) {\n const owned = yield* ownModelResponsePart(\n part,\n agent.definition.toolkit,\n trace,\n context.bufferLimits,\n trace.finished,\n );\n\n const events = context.publish === undefined ? undefined : [];\n\n yield* processModelPart(\n context,\n turnId,\n turn,\n agent.definition.toolkit.tools,\n trace,\n owned.ownedPart,\n owned.retainedBytes,\n events,\n );\n if (provisionalText !== undefined) {\n const part = owned.ownedPart;\n\n if (\n part.type === \"text-start\" ||\n part.type === \"text-delta\" ||\n part.type === \"text-end\"\n )\n provisionalText.offerUnsafe(part);\n }\n // Publish before accepting the next part. Backpressure stays interruptible.\n if (events !== undefined) yield* publishEvents(context, events);\n }\n }),\n ),\n <Value, Error, Requirements>(\n effect: Effect.Effect<Value, Error, Requirements>,\n ) => prepareWithinDeadline(context, effect),\n Effect.onExit((exit) => {\n if (Exit.isSuccess(exit)) return Effect.void;\n provisionalText?.discard();\n\n return retainFailedUsage();\n }),\n ),\n ),\n );\n }),\n ),\n ),\n );\n\n // Retry the closed native provider operation. Admitted content makes the response\n // ineligible for retry; canonical acceptance belongs to the continuation below.\n const attemptWithRetries = Effect.suspend(() => attempt(compactedOutgoing())).pipe(\n (operation) =>\n (policy.modelRetries ?? 0) === 0\n ? operation\n : Effect.retry(operation, ($) =>\n $(Schedule.exponential(MODEL_RETRY_BASE)).pipe(\n Schedule.upTo({ times: policy.modelRetries ?? 0 }),\n Schedule.while(({ input: error }) => {\n const lastPart = trace.parts.at(-1);\n const providerError: unknown = error;\n\n return (\n canRepeatModelCall &&\n !hasStreamedContent(trace) &&\n ((lastPart?.type === \"error\" && isTransientErrorPayload(lastPart.error)) ||\n (AiError.isAiError(providerError) && providerError.isRetryable))\n );\n }),\n Schedule.modifyDelay(({ input: error, duration }) =>\n Effect.gen(function* () {\n const backoff = Duration.min(duration, MODEL_RETRY_MAX_DELAY);\n const providerError: unknown = error;\n\n const retryAfter = AiError.isAiError(providerError)\n ? providerError.retryAfter\n : undefined;\n\n const requested =\n retryAfter === undefined ? backoff : Duration.max(backoff, retryAfter);\n\n // Expiration is rejected by the next native attempt. Capping only this delay\n // keeps failed-attempt accounting and canonical hooks outside interruption timers.\n const remaining = Math.max(\n 0,\n context.durationDeadlineMillis - (yield* Clock.currentTimeMillis),\n );\n\n return Duration.min(requested, Duration.millis(remaining));\n }),\n ),\n Schedule.tap(({ input: error, attempt: retry, duration }) =>\n Effect.gen(function* () {\n trace.parts.length = 0;\n trace.responsePartCount = 0;\n trace.responsePartBytes = 0;\n // The failed attempt's usage was already retained on exit.\n trace.usage = undefined;\n delete trace.response;\n delete trace.finishMetadata;\n yield* Effect.logWarning(\"agent model call retrying\").pipe(\n Effect.annotateLogs({\n runId: context.runId,\n turnId,\n retry,\n delayMillis: Duration.toMillis(duration),\n error: errorMessage(error),\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 = attemptWithRetries.pipe(\n Effect.catch(\n (\n error,\n ): Effect.Effect<\n void,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | Scope.Scope\n > => {\n if (!AiError.isAiError(error) || !isContextOverflowMessage(overflowText(error))) {\n return Effect.fail(error);\n }\n const message = overflowText(error);\n\n if (trace.parts.length > 0 || contextTokenLimit === undefined) {\n return Effect.fail(ContextOverflowError.make({ message, retried: false }));\n }\n if (context.compaction.overflowRetryTurn === turn) {\n return Effect.fail(ContextOverflowError.make({ message, retried: true }));\n }\n context.compaction.overflowRetryTurn = turn;\n context.compaction.lastCompactionTurn = turn;\n type TurnStream = Effect.Effect<\n void,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | Scope.Scope\n >;\n\n return Effect.flatten(\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 AiError.isAiError(inner) && isContextOverflowMessage(overflowText(inner))\n ? ContextOverflowError.make({\n message: overflowText(inner),\n retried: true,\n })\n : inner,\n ),\n );\n\n if (outcome.changed) 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 = attemptWithRetries.pipe(\n Effect.catchIf(\n (again): again is AiError.AiError =>\n AiError.isAiError(again) && isContextOverflowMessage(overflowText(again)),\n (again): TurnStream =>\n Effect.fail(\n ContextOverflowError.make({\n message: overflowText(again),\n retried: true,\n }),\n ),\n ),\n );\n\n const events: TurnStream = publishEvents(context, outcome.events);\n\n return events.pipe(Effect.andThen(retried));\n }),\n );\n },\n ),\n Effect.withSpan(\"AgentRuntime.model\", {\n attributes: {\n agentId: context.agentId,\n runId: context.runId,\n turnId,\n },\n }),\n );\n\n const continuation = Effect.flatten(\n Effect.sync(() => {\n if (!trace.finished) {\n return failExecution(\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 failExecution(\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 failExecution(\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 failExecution(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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\n ModelProtocolError.make({\n message: `Model stopped without required completion Tool ${agent.definition.completion.tool}`,\n }),\n );\n }\n\n const stagedResponse = Effect.gen(function* () {\n // Provider progress retains its semantic bounds even without an observer.\n if (trace.providerProgressBytes > 0) {\n yield* admitToolProgress(context, {\n value: null,\n bytes: trace.providerProgressBytes,\n });\n }\n if (trace.providerResultPayloads !== undefined) {\n for (const payload of trace.providerResultPayloads) {\n yield* publishEvent(context, () =>\n stampProviderResultEvent(context, turnId, payload),\n );\n }\n }\n if (turnCompletion !== undefined) {\n yield* publishEvent(context, () =>\n Effect.map(eventBase(context), (base) =>\n TurnCompleted.make({\n ...base,\n turnId,\n turn,\n finishReason: turnCompletion,\n }),\n ),\n );\n }\n });\n\n // Provider closure fixed these parts. Reuse their projection for history and\n // commit facts, preserving the first-use position of Prompt construction.\n let responseMessages: ReadonlyArray<Prompt.Message> | undefined;\n\n const currentResponseMessages = () =>\n (responseMessages ??= promptFromTurnParts(trace).content);\n\n /** Official history advanced through this Turn's response, plus any Tool message. */\n const historyWithResponse = (...additions: ReadonlyArray<Prompt.Message>) =>\n Prompt.fromMessages([...prompt.content, ...currentResponseMessages(), ...additions]);\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 = Effect.Effect<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | Scope.Scope\n >;\n\n const afterValidatedResponse = (\n next: Effect.Effect<\n TurnEvents,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | Scope.Scope\n >,\n ): TurnEvents =>\n stagedResponse.pipe(\n Effect.andThen(\n Effect.flatten(\n Effect.gen(function* () {\n const consumed = yield* consumeTurnUsage(trace.toolCalls.size);\n\n if (options.durability !== undefined) {\n trace.commitInputCount = context.pendingCommitInputs.length;\n trace.commitResponse = {\n messages: [...context.pendingCommitInputs, ...currentResponseMessages()],\n ...(turn !== 1 || context.pendingCommitInputs.length === 0\n ? {}\n : { runScopedPrefixLength: context.pendingCommitInputs.length }),\n calls: trace.applicationCallDescriptors,\n ...(trace.toolParameterRejections.size === 0\n ? {}\n : {\n toolParameterRejections: [...trace.toolParameterRejections.values()],\n }),\n ...(snapshot === undefined ? {} : { toolExposure: snapshot }),\n };\n }\n\n const pre: Array<RunEvent> | undefined =\n context.publish === undefined ? undefined : [...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: Effect.Effect<TurnOutput, NextError, NextRequirements>,\n ): Effect.Effect<TurnOutput, NextError, NextRequirements> =>\n pre === undefined || pre.length === 0\n ? nextStream\n : publishEvents(context, pre).pipe(Effect.andThen(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* prepareWithinDeadline(\n context,\n decodeFinalOutput(agent, trace.text.join(\"\")),\n ).pipe(\n Effect.map(Option.some),\n Effect.catch(() => Effect.succeed(Option.none())),\n );\n\n if (Option.isSome(output)) {\n trace.historyAccepted = true;\n yield* advanceHistory(context, historyWithResponse(), options);\n\n const completionUsage = yield* usageReportOf(context);\n\n return emitThen(\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 ).pipe(\n Effect.tap((event) =>\n settleTurn(context, trace, turn, turnId, options, event),\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 publishEvents(context, rejection).pipe(\n Effect.andThen(\n toolBatchContinuation(\n agent,\n context,\n trace,\n prompt,\n turn,\n turnId,\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 = Effect.fnUntraced(function* (history: Prompt.Prompt) {\n trace.historyAccepted = true;\n yield* advanceHistory(context, history, options);\n yield* settleTurn(context, trace, turn, turnId, 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 = Effect.fnUntraced(function* (history: Prompt.Prompt) {\n trace.historyAccepted = true;\n yield* advanceHistory(context, history, options);\n\n // Do not consume durable receipts that this completed Turn cannot cover.\n // Final-answer mode permits one grace Turn, but never a second finalization.\n const turnsBlocked =\n policy.onExhaustion === \"fail\" ? turn >= bounds.maxTurns : turn > bounds.maxTurns;\n\n const steering =\n turnsBlocked || context.finalizationUsed ? [] : 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 if (turnsBlocked) {\n return failExecution(\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 yield* settleTurn(context, trace, turn, turnId, options);\n const nextPrompt = yield* appendInputs(context, history, queued, options);\n\n return nextTurn(nextPrompt, turn + 1, toolCalls);\n }\n\n const output = yield* prepareWithinDeadline(\n context,\n decodeFinalOutput(agent, trace.text.join(\"\")),\n );\n\n const declaration = agent.definition.runDisposition;\n\n const runDisposition =\n finalAnswerOnly || declaration === undefined\n ? undefined\n : yield* prepareWithinDeadline(\n context,\n encodeRunDisposition(agent, output.decoded),\n );\n\n const completionUsage = yield* usageReportOf(context);\n\n return 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 ).pipe(Effect.tap((event) => settleTurn(context, trace, turn, turnId, options, event)));\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 failExecution(\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 failExecution(\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 failExecution(\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. The early Response commit 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 publishEvents(context, rejection).pipe(\n Effect.andThen(\n toolBatchContinuation(\n agent,\n context,\n trace,\n prompt,\n turn,\n turnId,\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 trace.historyAccepted = true;\n yield* advanceHistory(context, history, options);\n yield* settleTurn(context, trace, turn, turnId, 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 const response = trace.commitResponse;\n\n if (response === undefined)\n return yield* ModelProtocolError.make({\n message: \"Tool dispatch has no validated response facts\",\n });\n // Idempotency only permits replay of the original operation. Re-asking the\n // model could choose different arguments or a new key, so it keeps the barrier.\n yield* acceptTurnCommit(context, trace, options.durability, {\n _tag: \"Response\",\n turn,\n turnId,\n response,\n ...(canRepeatModelCall &&\n response.calls.every((call) => {\n const tool = toolkit.tools[call.toolName];\n\n return (\n call.executionClass === \"readonly\" &&\n call.executionKind === \"ordinary\" &&\n tool !== undefined &&\n (tool.needsApproval === undefined || tool.needsApproval === false)\n );\n })\n ? { defer: true as const }\n : {}),\n });\n }\n\n const toolResults = 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 durableResultBounds(agent.definition.policy.toolResultBounds, options, turn),\n );\n\n return toolResults.pipe(\n Effect.andThen(\n toolBatchContinuation(\n agent,\n context,\n trace,\n prompt,\n turn,\n turnId,\n toolCalls,\n options,\n ),\n ),\n );\n }),\n );\n }\n\n if (trace.finishReason !== \"stop\") {\n return failExecution(\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 // Only the model stream is cancellable. It resolves no application Tools and\n // closes its waiter before continuation can commit a response or start a Handler.\n const restartSignal =\n policy.restartOnJoinedInput === true &&\n context.modelRestarts < 2 &&\n (options.durability === undefined || options.durability.commitModelRestart !== undefined) &&\n canRepeatModelCall\n ? options.input?.awaitJoin\n : undefined;\n\n // raceFirst starts its first child immediately. Arm a lazily acquired join waiter\n // before provider execution can publish a request and cause that waiter to rotate.\n const disposableResponse =\n restartSignal !== undefined\n ? restartSignal.pipe(\n Effect.asVoid,\n Effect.tap(() =>\n Effect.sync(() => {\n restartRequested = true;\n activeProvisionalText?.discard();\n activeModelSpan?.attribute(\"effect_agent.model.outcome\", \"aborted\");\n activeModelSpan?.attribute(\"effect_agent.model.abort_reason\", \"joined-input\");\n }),\n ),\n Effect.raceFirst(\n Effect.suspend(() => {\n responseStarted = true;\n\n return response;\n }),\n ),\n )\n : response;\n\n const afterResponse = Effect.suspend(() => {\n if (!restartRequested) {\n const provisionalText = activeProvisionalText;\n\n const observed =\n provisionalText === undefined\n ? continuation\n : continuation.pipe(\n Effect.onExit((exit) => {\n if (Exit.isFailure(exit)) provisionalText.discard();\n else provisionalText.close();\n\n return Effect.void;\n }),\n );\n\n return observed.pipe(Effect.tapCause(() => retainFailedUsage()));\n }\n\n // Invalidation is observed before fallible persistence or input rendering.\n return publishEvent(context, () =>\n Effect.map(eventBase(context), (base) =>\n ModelRestarted.make({ ...base, turnId, turn, reason: \"joined-input\" }),\n ),\n ).pipe(\n Effect.andThen(\n Effect.flatten(\n Effect.gen(function* () {\n // An already-ready join can win before a provider attempt starts.\n if (responseStarted) yield* retainFailedUsage();\n context.modelRestarts++;\n if (options.durability?.commitModelRestart !== undefined)\n yield* options.durability.commitModelRestart({\n turn,\n turnId,\n restart: context.modelRestarts,\n });\n if (failedUsageCause !== undefined)\n return yield* Effect.failCause(failedUsageCause);\n const inputs = yield* drainInputs(context, options);\n const nextPrompt = yield* appendInputs(context, prompt, inputs, options);\n\n return Effect.succeed<TurnOutput>({\n _tag: \"NextTurn\",\n prompt: nextPrompt,\n turn,\n toolCalls: priorToolCalls,\n restarting: true,\n });\n }),\n ),\n ),\n );\n });\n\n const events = publishEvents(context, preEvents).pipe(\n Effect.andThen(started),\n Effect.andThen(disposableResponse),\n Effect.andThen(afterResponse),\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n (trace.historyAccepted\n ? settleTurn(context, trace, turn, turnId, options)\n : Effect.void\n ).pipe(\n Effect.catchCause((settlementCause) =>\n Effect.failCause(\n Cause.hasInterrupts(settlementCause)\n ? settlementCause\n : Cause.combine(cause, settlementCause),\n ),\n ),\n Effect.andThen(Effect.failCause(cause)),\n ),\n ),\n );\n\n return (\n modelServices === undefined ? events : Effect.provideContext(events, modelServices)\n ).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n activeProvisionalText?.discard();\n if (typeof context.windowTokens === \"function\")\n context.windowTokens = context.lastInputTokens;\n }),\n ),\n );\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 turnId: TurnId,\n toolCalls: number,\n options: RunOptions<HookError, HookRequirements>,\n): Effect.Effect<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements> | Scope.Scope\n> =>\n Effect.flatten(\n Effect.gen(function* () {\n if (trace.finalToolResultIds.size !== trace.toolCalls.size) {\n return failExecution(\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 failExecution(\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 // Closed Tool outcomes are durable before policy, input draining or completion\n // projection can fail. Observing the corresponding events does not own this commit.\n trace.historyAccepted = true;\n yield* advanceHistory(context, history, options);\n yield* settleTurn(context, trace, turn, turnId, 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 failExecution(\n ModelProtocolError.make({\n message: \"Completion Tool has no canonical call descriptor\",\n }),\n );\n }\n if (actionCompletion !== undefined) {\n selectedOutput = yield* prepareWithinDeadline(\n context,\n projectCompletionFromToolOutput(\n agent,\n actionCompletion,\n copyJson(call.parameters),\n successfulResult.encodedResult,\n ),\n );\n } else if (completion !== undefined) {\n selectedOutput = Option.some(\n yield* prepareWithinDeadline(\n context,\n projectCompletionOutput(\n agent,\n completion,\n copyJson(call.parameters),\n successfulResult.encodedResult,\n ),\n ),\n );\n }\n }\n\n // A completion Tool can admit steering while its handler runs. Only claim it\n // when another ordinary Turn can cover it; otherwise keep it queued for a new Run.\n const bounds = effectiveRunBounds(agent.definition.policy, options);\n\n const canContinue =\n turn < bounds.maxTurns &&\n (completion?.required === true\n ? toolCalls + context.programmaticToolCalls < bounds.maxToolCalls\n : toolCalls + context.programmaticToolCalls <= bounds.maxToolCalls) &&\n !context.tokenExhausted &&\n !context.finalizationUsed &&\n (yield* Clock.currentTimeMillis) < context.durationDeadlineMillis;\n\n const steering =\n Option.isSome(selectedOutput) && !canContinue ? [] : yield* drainInputs(context, options);\n\n if (Option.isSome(selectedOutput) && steering.length === 0) {\n const output = selectedOutput.value;\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* prepareWithinDeadline(context, encodeRunDisposition(agent, output.decoded));\n\n const completionUsage = yield* usageReportOf(context);\n\n return 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 ).pipe(Effect.tap((event) => settleTurn(context, trace, turn, turnId, options, event)));\n }\n const nextPrompt = yield* appendInputs(context, history, steering, options);\n\n return nextTurn(nextPrompt, turn + 1, toolCalls);\n }),\n ).pipe(\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n (trace.historyAccepted\n ? settleTurn(context, trace, turn, turnId, options)\n : Effect.void\n ).pipe(\n Effect.catchCause((settlementCause) =>\n Effect.failCause(\n Cause.hasInterrupts(settlementCause)\n ? settlementCause\n : Cause.combine(cause, settlementCause),\n ),\n ),\n Effect.andThen(Effect.failCause(cause)),\n ),\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 * the durable dispatch fence 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): Effect.Effect<\n TurnOutput,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n InterpreterRequirements<typeof agent, HookRequirements, InstructionRequirements> | Scope.Scope\n> =>\n Effect.flatten(\n Effect.gen(function* () {\n yield* checkpointExecution(context, options.durability);\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 ).pipe((effect) =>\n visibility === undefined ? effect : prepareWithinDeadline(context, effect),\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 failExecution(\n ModelProtocolError.make({\n message: \"Turn resume requires a positive integer turn number\",\n }),\n );\n }\n if (resume.calls.length === 0) {\n return failExecution(\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 responseCommitted: true,\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: context.publish === undefined ? undefined : [],\n providerStagedEventCount: 0,\n providerStagedPayloadBytes: 0,\n providerProgressBytes: 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 yield* boundEncodedToolResult(\n rejection.error,\n durableResultBounds(agent.definition.policy.toolResultBounds, options, turn),\n ),\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 failExecution(\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 failExecution(\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 const parameters = yield* decodeEventJson(call.params, \"Tool parameters\");\n\n if (!recordedSettledIds.has(call.id)) {\n yield* decodeToolCallParameters<Tools>(tool, call.name, copyJson(parameters), \"resume\");\n }\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 const executionParameters = copyJson(parameters);\n\n trace.applicationToolCalls.push({\n ...Response.makePart(\"tool-call\", {\n id: call.id,\n name: call.name,\n params: executionParameters,\n providerExecuted: false,\n }),\n params: executionParameters,\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: executionParameters,\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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\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 remains an observation of the restored response; direct\n // settlement facts below own any new canonical writes.\n const started = 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 if (context.publish === undefined) return;\n\n yield* context.publish([\n TurnStarted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n }),\n ]);\n yield* context.publish([\n TurnCompleted.make({\n ...(yield* eventBase(context)),\n turnId,\n turn,\n finishReason: \"tool-calls\",\n }),\n ]);\n\n return;\n }).pipe(Effect.withLogSpan(\"AgentRuntime.resume\"));\n\n const continueAfterBatch = () =>\n toolBatchContinuation(\n agent,\n context,\n trace,\n resumedPrompt,\n turn,\n turnId,\n toolCalls,\n options,\n );\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 Effect.andThen(publishEvents(context, rejection)),\n Effect.andThen(continueAfterBatch()),\n );\n }\n\n const toolResults = 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 durableResultBounds(agent.definition.policy.toolResultBounds, options, turn),\n settledIds,\n );\n\n return started.pipe(Effect.andThen(toolResults), Effect.andThen(continueAfterBatch()));\n }),\n );\n\nconst failExecution = <Error>(error: Error): Effect.Effect<never, Error> => Effect.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\n/**\n * Execution phases share one deadline; direct interpreter commits stay outside this timer.\n * Tool handlers may invoke durable operations within their timed native execution.\n */\nconst beforeExecutionDeadline = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n deadlineMillis: number,\n failure: AgentPolicyError,\n): Effect.Effect<A, E | AgentPolicyError, R> =>\n Effect.gen(function* () {\n const remaining = deadlineMillis - (yield* Clock.currentTimeMillis);\n\n if (remaining <= 0) return yield* failure;\n\n return yield* effect.pipe(\n Effect.timeoutOrElse({ duration: remaining, orElse: () => Effect.fail(failure) }),\n );\n });\n\nconst prepareWithinDeadline = <A, E, R>(context: RunContext, effect: Effect.Effect<A, E, R>) =>\n beforeExecutionDeadline(effect, context.durationDeadlineMillis, context.durationFailure);\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 const beforeDeadline = Effect.fnUntraced(function* <Value, Error, Requirements>(\n effect: Effect.Effect<Value, Error, Requirements>,\n ): Effect.fn.Return<Value, Error | AgentPolicyError, Requirements> {\n const now = yield* Clock.currentTimeMillis;\n const remaining = durationDeadlineMillis - now;\n\n if (remaining <= 0) {\n return yield* Effect.fail(durationLimit);\n }\n\n return yield* effect.pipe(\n Effect.timeoutOrElse({\n duration: remaining,\n orElse: () => Effect.fail(durationLimit),\n }),\n );\n });\n\n // The pull stays inside this stream and uses its current scoped services.\n const makePull = Effect.flatMap(Scope.Scope, (scope) =>\n Channel.toPullScoped(execution.channel, scope),\n ).pipe(\n // Match Channel.toPull: acquisition causes are delivered by the returned pull.\n Effect.catchCause((cause) => Effect.succeed(Effect.failCause(cause))),\n );\n\n // Guard acquisition and each pull against the same deadline. A merged timer\n // stream can deadlock at a cooperative scheduler yield (see #692).\n return Stream.fromPull(beforeDeadline(makePull).pipe(Effect.map(beforeDeadline))).pipe(\n Stream.scoped,\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\nconst guardBudgetEffect = <A, E, R, H, HR>(\n effect: Effect.Effect<A, E, R>,\n budget: RunOptions<H, HR>[\"budget\"],\n): Effect.Effect<A, E | H, R | HR> => (budget === undefined ? effect : budget.guard(effect));\n\n/** Decode input and interpret the Run, validating terminal output before committing history. */\nfunction executeWithCompletion<\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 publish?: EventPublisher,\n): Effect.Effect<\n RunCompleted,\n AgentRuntimeFailure<A, H> | CompletionError,\n | AgentRuntimeRequirements<A, R>\n | CompletionRequirements\n | ModelUsageAccounting\n | AgentUpdateAcceptance\n>;\nfunction executeWithCompletion<\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 publish?: EventPublisher,\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 Effect.flatten(\n Effect.gen(function* (): Effect.fn.Return<\n Effect.Effect<\n RunCompleted,\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({\n source: runOptions.history,\n modelContext: runOptions.history,\n });\n }\n\n const options: RunOptions<\n | HookError\n | ThreadHistoryError\n | RunContextPreparationError\n | AgentToolAuthorizationCheckError,\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, modelContext) =>\n retained\n .stageHistory({ source: next, modelContext })\n .pipe(\n Effect.andThen(() => runOptions.onHistory?.(next, modelContext) ?? Effect.void),\n ),\n }),\n };\n\n const durationFailure = durationLimitError(agent.definition.policy);\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 // 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 = Effect.map(\n Effect.context<HookRequirements>(),\n (services) => {\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 = Effect.flatten(\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\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(UpdateError.make({ reason: \"unavailable\" }))\n : (value: Schema.Json) =>\n Schema.decodeEffect(updateSchema)(value).pipe(\n Effect.provide(updateContext),\n Effect.asVoid,\n Effect.mapError(() => UpdateError.make({ reason: \"validation\" })),\n );\n\n const languageModel = yield* LanguageModel.LanguageModel;\n const resolver = Agent.isModelResolver(languageModel) ? languageModel : undefined;\n\n const context: RunContext = {\n publish,\n progressFailure: yield* Deferred.make<never, ModelProtocolError | AgentPolicyError>(),\n resolvedModel: resolver !== undefined,\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 durationFailure,\n history: options.history ?? Prompt.empty,\n pendingCommitInputs: [],\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 webSearchCalls:\n resumeUsage === undefined || resumeUsage.modelCalls === 0\n ? 0\n : resumeUsage.webSearchCalls,\n modelRestarts: resumeUsage?.modelRestarts ?? 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 failExecution(\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 failExecution(\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 failExecution(\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 failExecution(\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 = Effect.gen(function* () {\n yield* Metric.update(runCounter, 1);\n yield* Effect.logDebug(\"agent run started\").pipe(\n Effect.annotateLogs({ agentId: context.agentId, runId: context.runId }),\n );\n yield* publishEvent(context, () =>\n eventBase(context).pipe(Effect.map((base) => RunStarted.make(base))),\n );\n }).pipe(Effect.withLogSpan(\"AgentRuntime.run\"));\n\n const execution = Effect.flatten(\n Effect.gen(function* () {\n const initial = yield* prepareWithinDeadline(\n context,\n 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 if (options.retainedContext !== undefined) {\n if (typeof source === \"function\") yield* decodeInput(agent, encodedInput);\n\n return { instructions: \"\", encodedInput, inputPrompt: undefined };\n }\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\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\n const prompt =\n options.retainedContext === undefined\n ? yield* makeInitialPrompt(instructions, inputPrompt, context.history)\n : Prompt.fromMessages([\n ...context.history.content,\n ...options.retainedContext.content,\n ]);\n\n if (options.durability !== undefined) {\n if ((resumeUsage?.committedTurns ?? 0) === 0) {\n context.pendingCommitInputs.push(...prompt.content.slice(priorHistoryLength));\n }\n yield* options.durability.initialize({\n initialHistory: prompt,\n priorHistoryLength,\n });\n }\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.retainedContext !== undefined\n ? options.retainedContext.content\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 modelSource: undefined,\n sourceLength: 0,\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 readonly restarting?: boolean;\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 // A Turn's Scope closes before its successor starts. There is one execution\n // loop, independent of public progress demand and without recursive Channels.\n const turns = Effect.gen(function* () {\n let request = pending;\n\n while (request !== undefined) {\n const output: TurnOutput = yield* Effect.scoped(\n request.resume === undefined\n ? makeTurn(\n agent,\n context,\n request.prompt,\n request.turn,\n request.toolCalls,\n options,\n request.restarting,\n )\n : makeResumeTurn(\n agent,\n context,\n request.prompt,\n request.resume,\n request.toolCalls,\n options,\n ),\n );\n\n if (output._tag !== \"NextTurn\") {\n yield* checkpointExecution(context, options.durability);\n\n return output;\n }\n // Both Turn entry points check before any hook or dispatch. The\n // preceding Scope has closed, so that check also sees finalizer failures.\n request = output;\n }\n\n return yield* ModelProtocolError.make({\n message: \"Agent execution ended without RunCompleted\",\n });\n });\n\n if (resolver === undefined) return turns;\n\n const catalog = yield* eligibleCatalog(\n agent.definition,\n { threadId, runId, turn: pending.turn, input: context.input },\n options.subagentGrant,\n options.delegationDepth ?? options.parentLink?.depth ?? 0,\n );\n\n const selectionPrompt = yield* Schema.encodeEffect(\n Schema.fromJsonString(Prompt.Prompt),\n )(pending.prompt).pipe(\n Effect.mapError((cause) =>\n AiError.AiError.make({\n module: \"AgentRuntime\",\n method: \"resolveModel\",\n reason: AiError.InvalidRequestError.make({\n description: `Cannot encode model selection context: ${cause.message}`,\n }),\n }),\n ),\n );\n\n const selected = yield* prepareWithinDeadline(\n context,\n resolver.resolve({\n threadId,\n state: {\n prompt: selectionPrompt,\n tools: catalog.map(({ tool }) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n })),\n },\n }),\n );\n\n const services = yield* prepareWithinDeadline(\n context,\n Layer.build(Layer.fresh(selected)),\n );\n\n return Effect.provide(turns, services);\n }),\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: Effect.fnUntraced(function* (\n parameters: unknown,\n call: Toolkit.HandlerContext<Tool.Any>,\n ) {\n if (call.toolCallId === undefined)\n return yield* UpdateError.make({ reason: \"unavailable\" });\n\n const decoded = yield* Schema.decodeUnknownEffect(\n Schema.Struct({ value: Schema.Unknown }),\n )(parameters).pipe(\n Effect.mapError(() => UpdateError.make({ 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(() => UpdateError.make({ reason: \"validation\" })),\n );\n\n const updateId = yield* Schema.decodeEffect(IdempotencyKey)(\n `tool:${context.runId}:${call.toolCallId}`,\n ).pipe(Effect.mapError(() => UpdateError.make({ reason: \"validation\" })));\n\n const emitter = yield* Emitter;\n\n yield* emitter.emit({ target: agent.definition, updateId, value });\n\n return { emitted: true };\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 if (typeof context.windowTokens === \"function\") {\n const estimate = context.windowTokens();\n\n context.windowTokens =\n Number.isSafeInteger(estimate) && estimate >= 0\n ? estimate\n : context.lastInputTokens;\n }\n\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(UpdateError.make({ 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 Effect.andThen(execution),\n Effect.raceFirst(Deferred.await(context.progressFailure)),\n Effect.catchCauseFilter(Cause.findError, (error, cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.failCause(cause)\n : publishEvent(context, () =>\n Effect.gen(function* () {\n if (\n error instanceof AgentApprovalPending ||\n error instanceof AgentChildPending\n ) {\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 ).pipe(Effect.andThen(Effect.failCause(cause))),\n ),\n Effect.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 Effect.provide(engineToolServices),\n Effect.provideService(ContextCompactor, compactor),\n );\n }),\n );\n\n const finalized =\n options.input?.end === undefined\n ? interpreted\n : interpreted.pipe(Effect.ensuring(options.input.end()));\n\n const modeled: Effect.Effect<\n RunCompleted,\n AgentRuntimeFailure<typeof agent, HookError, InstructionError>,\n | AgentRuntimeRequirements<typeof agent, HookRequirements, InstructionRequirements>\n | ToolSpanTelemetry\n | ProgrammaticToolAuthorization\n | ModelRequires\n | ModelUsageAccounting\n | AgentUpdateAcceptance\n | Scope.Scope\n > = model === undefined\n ? finalized\n : Effect.gen(function* () {\n const services = yield* beforeExecutionDeadline(\n Layer.build(Layer.fresh(model)),\n durationDeadlineMillis,\n durationFailure,\n );\n\n return yield* Effect.provide(finalized, services);\n });\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 Effect.provideServiceEffect(ToolSpanTelemetry, ToolSpanTelemetry.make),\n Effect.provideServiceEffect(ProgrammaticToolAuthorization, programmaticAuthorization),\n );\n\n // Closing execution first joins every owned child and finalizer before validation,\n // history commit and observable success. Application Layers retain their outer Scope.\n return Effect.scoped(events).pipe(\n Effect.flatMap((terminal) =>\n Effect.gen(function* () {\n if (onCompleted !== undefined) yield* onCompleted(terminal);\n if (retained !== undefined) yield* retained.commit(terminal);\n if (publish !== undefined) yield* publish([terminal]);\n\n return terminal;\n }).pipe(\n Effect.catchCauseFilter(Cause.findError, (error, cause) => {\n if (Cause.hasInterrupts(cause)) return Effect.failCause(cause);\n\n const failed =\n publish === undefined\n ? Effect.void\n : publish([\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 ]);\n\n return failed.pipe(Effect.andThen(Effect.failCause(cause)));\n }),\n ),\n ),\n );\n }),\n );\n}\n\n/** The sole public progress adapter: one bounded queue and one scoped producer. */\nconst streamWithCompletion = <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> =>\n Stream.unwrap(\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const queue = yield* Queue.bounded<RunEvent, AgentRuntimeFailure<A, H> | Cause.Done>(\n effectiveRunBufferLimits(options?.bufferLimits).maxBufferedEvents,\n );\n\n const producer = executeWithCompletion(\n agent,\n input,\n options,\n undefined,\n undefined,\n (events) => Queue.offerAll(queue, events).pipe(Effect.asVoid),\n );\n\n yield* Effect.forkScoped(\n restore(producer).pipe(\n Effect.matchCauseEffect({\n onFailure: (cause) => Queue.failCause(queue, cause),\n onSuccess: () => Queue.end(queue),\n }),\n Effect.asVoid,\n ),\n );\n // LIFO: unblock even uninterruptible handler cleanup before joining its producer.\n yield* Effect.addFinalizer(() => Queue.shutdown(queue));\n\n return Stream.fromQueue(queue);\n }),\n ),\n ).pipe(Stream.scoped);\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 completeRun = <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 ) => Effect.Effect<RunCompleted, 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* events((completed) =>\n Effect.gen(function* () {\n const candidateOutput: unknown = completed.output;\n\n const output = yield* Schema.decodeUnknownEffect<AgentValue[\"definition\"][\"output\"]>(\n agent.definition.output,\n )(candidateOutput).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: \"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 if (result === undefined) {\n return yield* ModelProtocolError.make({\n message: \"Agent execution ended without RunCompleted\",\n });\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>) => Effect.Effect<RunCompleted, E, R>,\n) {\n return yield* completeRun(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 publish: EventPublisher,\n ) => Effect.Effect<RunCompleted, 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. Observed execution 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 = completeRun(agent, (onCompleted) =>\n events(\n executionOptions,\n onCompleted,\n (read) => {\n readUsage = read;\n },\n (events) =>\n Effect.suspend(() => {\n if (!Arr.isReadonlyArrayNonEmpty(events)) return Effect.void;\n const chunk = Arr.copy(events);\n\n captured.push(...chunk);\n\n return PubSub.publish(pubsub, chunk).pipe(Effect.asVoid);\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/** Same interpreter without a progress publisher or public Stream adapter. */\nconst executeWithUsageAccountingUnknown = <A extends ExecutableAgent, H = never, R = never>(\n agent: A,\n input: unknown,\n options?: RunOptions<H, R>,\n): Effect.Effect<\n void,\n AgentRuntimeFailure<A, H>,\n AgentRuntimeRequirements<A, R> | ModelUsageAccounting | AgentUpdateAcceptance\n> => executeWithCompletion(agent, input, options).pipe(Effect.asVoid);\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: \"definition\" in agent ? agent.definition : agent };\n\n return runProgram(program, (onCompleted) =>\n // The overload retains each Agent's R; this implementation executes an existential model binding without narrowing its services.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n executeWithCompletion(agent, input, options, onCompleted).pipe(\n Effect.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: \"definition\" in agent ? agent.definition : agent };\n\n return startProgram(\n program,\n (executionOptions, onCompleted, onUsage, publish) =>\n // The overload retains each Agent's R; detached execution captures the same existential binding inside the caller's Scope.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n executeWithCompletion(agent, input, executionOptions, onCompleted, onUsage, publish).pipe(\n Effect.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 | undefined,\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 (marker !== undefined && 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 let marker: ToolSpanFailure | undefined;\n const failureMarker = () => (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\", failureMarker(), \"propagated\"),\n ).pipe(Effect.andThen(Effect.fail(failureMarker())));\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\" ? failureMarker() : undefined,\n outcome === \"failure\" ? \"returned-to-caller\" : undefined,\n ),\n ).pipe(\n Effect.andThen(\n outcome === \"failure\" ? Effect.fail(failureMarker()) : Effect.succeed(exit.value),\n ),\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: Effect.fnUntraced(function* <Tools extends Record<string, Tool.Any>>(\n toolkit: Toolkit.WithHandler<Tools>,\n passOptions: Parameters<ToolBrokerService[\"openPass\"]>[1],\n ) {\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 declared handler services at the pass boundary once.\n const handlerServices = yield* Effect.context<Tool.HandlerServices<Tools[keyof Tools]>>();\n\n // Toolkit.handle decodes unknown parameters itself. Widen only that input boundary;\n // retain its declared schema failures and handler services for this exact Toolkit.\n const handle = toolkit.handle as (\n name: keyof Tools,\n parameters: unknown,\n id: string,\n ) => ReturnType<Toolkit.WithHandler<Tools>[\"handle\"]>;\n\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];\n\n const advertised = Object.values(binding.context.definition.toolkit.tools).some((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 handle(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: toolResultForJson(tool, result),\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))(snapshot.text);\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(\n Effect.updateContext((current: Context.Context<never>) =>\n Context.merge(current, handlerServices),\n ),\n );\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: Effect.fnUntraced(function* <Output extends Schema.Top, BodyError, BodyServices>(\n name: string,\n output: Output,\n execute: Effect.Effect<Output[\"Type\"], BodyError, BodyServices>,\n ) {\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\n return yield* Effect.acquireUseRelease(\n provideHookServices(hook.reserve(key), hookServices).pipe(\n Effect.mapError((cause) =>\n DurableStepError.make({\n toolCallId,\n stepName: name,\n reason:\n cause instanceof AgentPersistenceCapacityError\n ? \"capacity-exhausted\"\n : \"reservation-failed\",\n message:\n cause instanceof AgentPersistenceCapacityError\n ? \"Durable Step has no room for a valid saved result\"\n : \"Durable Step capacity reservation failed\",\n cause,\n }),\n ),\n ),\n () =>\n Effect.gen(function* () {\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 (release) => release,\n );\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.fnUntraced(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 with one scoped Effect owner. `stream` observes\n * that owner through a bounded producer adapter; `run` executes without progress transport.\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 executeWithUsageAccountingUnknown,\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 executeWithUsageAccountingUnknown,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B;AAChC,MAAM,uBAAuB,OAAO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