effect-agent 0.1.0-beta.103 → 0.1.0-beta.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/dist/{Agent-CM6JubNX.d.mts → Agent-Bk-mLtov.d.mts} +2 -2
  2. package/dist/{AgentError-CggcAQ7V.d.mts → AgentError-Bn1ytXRD.d.mts} +20 -4
  3. package/dist/{AgentRuntime-B1SXMVN7.d.mts → AgentRuntime-BEXToYl1.d.mts} +8 -8
  4. package/dist/{AgentRuntime-BWOnNc0d.mjs → AgentRuntime-e2M5UoXn.mjs} +4 -3
  5. package/dist/AgentRuntime-e2M5UoXn.mjs.map +1 -0
  6. package/dist/{DurableAgentRuntime-C9eRZS9N.mjs → DurableAgentRuntime-wd1x0TcB.mjs} +67 -36
  7. package/dist/DurableAgentRuntime-wd1x0TcB.mjs.map +1 -0
  8. package/dist/{EventSource-K7XUzurY.d.mts → EventSource-pH-v0k42.d.mts} +3 -3
  9. package/dist/FailureDiagnostic-BElLOoED.mjs +274 -0
  10. package/dist/FailureDiagnostic-BElLOoED.mjs.map +1 -0
  11. package/dist/FailureDiagnostic-CaAkzGHL.d.mts +223 -0
  12. package/dist/{Messaging-QMYhp297.d.mts → Messaging-Bl4SBKpR.d.mts} +3 -3
  13. package/dist/{MessagingHost-gAxs5gme.d.mts → MessagingHost-nwBMdRoh.d.mts} +3 -3
  14. package/dist/{Output-CjocJzsl.d.mts → Output-B6RQ5jRU.d.mts} +2 -2
  15. package/dist/{PreparedInputAdmission-KLk5rGFI.d.mts → PreparedInputAdmission-D3-BgmA9.d.mts} +8 -4
  16. package/dist/{Records-Bidb7ByL.d.mts → Records-B4S02MX1.d.mts} +201 -14
  17. package/dist/{RunJournal-srpbEBEy.mjs → RunJournal-BdIlgAEj.mjs} +2 -2
  18. package/dist/{RunJournal-srpbEBEy.mjs.map → RunJournal-BdIlgAEj.mjs.map} +1 -1
  19. package/dist/{RunOptions-Bruk54SE.d.mts → RunOptions-qOcPv08p.d.mts} +10 -5
  20. package/dist/{Schedule-Cy9up8Uf.d.mts → Schedule-D2TVEu3W.d.mts} +7 -2
  21. package/dist/{Scheduling-CHCsSCGo.mjs → Scheduling-DPb2QyAK.mjs} +2 -2
  22. package/dist/{Scheduling-CHCsSCGo.mjs.map → Scheduling-DPb2QyAK.mjs.map} +1 -1
  23. package/dist/{Subagent-DP0CzO16.d.mts → Subagent-BxuDuCHt.d.mts} +172 -8
  24. package/dist/{Subagent-C2s8PFrd.mjs → Subagent-uXWHXiKb.mjs} +64 -29
  25. package/dist/Subagent-uXWHXiKb.mjs.map +1 -0
  26. package/dist/{SubagentHost-CYcxkpRc.d.mts → SubagentHost-DEPw4YME.d.mts} +6 -3
  27. package/dist/{Subscription-CHyoQelH.d.mts → Subscription-nX0rz4GQ.d.mts} +3 -3
  28. package/dist/{SubscriptionInput-DqrHW-Ja.d.mts → SubscriptionInput-CAG3_pyJ.d.mts} +3 -3
  29. package/dist/{Worker--j87JI__.d.mts → Worker-Bbj9uq5H.d.mts} +5 -2
  30. package/dist/{agent-registration-ByeHejH3.mjs → agent-registration-B5CI-Ygk.mjs} +7 -5
  31. package/dist/agent-registration-B5CI-Ygk.mjs.map +1 -0
  32. package/dist/capabilities/Commands.d.mts +1 -1
  33. package/dist/capabilities/Messaging.d.mts +2 -2
  34. package/dist/capabilities/RunHooks.d.mts +1 -1
  35. package/dist/capabilities/Subagent.d.mts +2 -2
  36. package/dist/capabilities/Subagent.mjs +1 -1
  37. package/dist/core/Agent.d.mts +1 -1
  38. package/dist/core/AgentError.d.mts +2 -2
  39. package/dist/core/AgentError.mjs +19 -2
  40. package/dist/core/AgentError.mjs.map +1 -1
  41. package/dist/core/FailureDiagnostic.d.mts +2 -0
  42. package/dist/core/FailureDiagnostic.mjs +2 -0
  43. package/dist/core/Worker.d.mts +1 -1
  44. package/dist/core/Worker.mjs +4 -1
  45. package/dist/core/Worker.mjs.map +1 -1
  46. package/dist/durable/ActivityStore.d.mts +1 -1
  47. package/dist/durable/ActivityStore.mjs +1 -1
  48. package/dist/durable/Admin.d.mts +1 -1
  49. package/dist/durable/Admin.mjs +1 -1
  50. package/dist/durable/AgentRegistration.d.mts +1 -1
  51. package/dist/durable/AgentRegistration.mjs +1 -1
  52. package/dist/durable/Certification.d.mts +1 -1
  53. package/dist/durable/CommittedActivity.d.mts +1 -1
  54. package/dist/durable/CommittedActivity.mjs +1 -1
  55. package/dist/durable/Digest.d.mts +1 -1
  56. package/dist/durable/Digest.mjs +7 -7
  57. package/dist/durable/Digest.mjs.map +1 -1
  58. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  59. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  60. package/dist/durable/EventSource.d.mts +1 -1
  61. package/dist/durable/EventSource.mjs +1 -1
  62. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  63. package/dist/durable/GitHubWorkflowSource.mjs +1 -1
  64. package/dist/durable/MessageDelivery.d.mts +15 -3
  65. package/dist/durable/MessageDelivery.mjs +44 -24
  66. package/dist/durable/MessageDelivery.mjs.map +1 -1
  67. package/dist/durable/MessageDeliveryStoreConformance.d.mts +4 -1
  68. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  69. package/dist/durable/PersistentHistory.d.mts +1 -1
  70. package/dist/durable/PersistentHistory.mjs +2 -2
  71. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  72. package/dist/durable/PreparedInputAdmission.mjs +8 -4
  73. package/dist/durable/PreparedInputAdmission.mjs.map +1 -1
  74. package/dist/durable/Records.d.mts +1 -1
  75. package/dist/durable/Records.mjs +831 -2
  76. package/dist/durable/Records.mjs.map +1 -0
  77. package/dist/durable/Recovery.d.mts +1 -1
  78. package/dist/durable/Recovery.mjs +1 -1
  79. package/dist/durable/RunJournal.d.mts +1 -1
  80. package/dist/durable/RunJournal.mjs +1 -1
  81. package/dist/durable/Schedule.d.mts +1 -1
  82. package/dist/durable/Schedule.mjs +12 -3
  83. package/dist/durable/Schedule.mjs.map +1 -1
  84. package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
  85. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  86. package/dist/durable/ScheduleTransition.d.mts +1 -1
  87. package/dist/durable/ScheduleTransition.mjs +1 -1
  88. package/dist/durable/Scheduling.d.mts +2 -2
  89. package/dist/durable/Scheduling.mjs +1 -1
  90. package/dist/durable/SqlMessageDeliveryStore.mjs +13 -11
  91. package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -1
  92. package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
  93. package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
  94. package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
  95. package/dist/durable/SqlSubscriptionStore.mjs +1 -1
  96. package/dist/durable/SqlThreadNativeReads.d.mts +1 -1
  97. package/dist/durable/SqlThreadNativeReads.mjs +2 -2
  98. package/dist/durable/SubmissionLedger.d.mts +1 -1
  99. package/dist/durable/SubmissionLedger.mjs +6 -3
  100. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  101. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  102. package/dist/durable/SubmissionLedgerConformance.mjs +1 -1
  103. package/dist/durable/SubmissionStatus.d.mts +1 -1
  104. package/dist/durable/Subscription.d.mts +1 -1
  105. package/dist/durable/Subscription.mjs +1 -1
  106. package/dist/durable/SubscriptionInput.d.mts +1 -1
  107. package/dist/durable/SubscriptionInput.mjs +2 -2
  108. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  109. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  110. package/dist/durable/SubscriptionTools.d.mts +3 -3
  111. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  112. package/dist/durable/SubscriptionTransition.mjs +1 -1
  113. package/dist/durable/Subscriptions.d.mts +5 -5
  114. package/dist/durable/Subscriptions.mjs +1 -1
  115. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  116. package/dist/durable/ThreadContextHistory.mjs +1 -1
  117. package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
  118. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  119. package/dist/durable/ThreadInvariants.d.mts +1 -1
  120. package/dist/durable/ThreadInvariants.mjs +2 -2
  121. package/dist/durable/ThreadProjection.d.mts +1 -1
  122. package/dist/durable/ThreadProjection.mjs +1 -1
  123. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  124. package/dist/durable/ThreadStore.d.mts +1 -1
  125. package/dist/durable/ThreadStore.mjs +2 -2
  126. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  127. package/dist/durable/ThreadStoreConformance.mjs +1 -1
  128. package/dist/durable/ToolReconciler.mjs +1 -1
  129. package/dist/durable/WorkerHost.d.mts +3 -3
  130. package/dist/engine/AgentRuntime.d.mts +1 -1
  131. package/dist/engine/AgentRuntime.mjs +1 -1
  132. package/dist/engine/MessagingHost.d.mts +1 -1
  133. package/dist/engine/Output.d.mts +1 -1
  134. package/dist/engine/RunOptions.d.mts +1 -1
  135. package/dist/engine/RunOptions.mjs +2 -0
  136. package/dist/engine/RunOptions.mjs.map +1 -1
  137. package/dist/engine/SubagentHost.d.mts +1 -1
  138. package/dist/engine/SubagentHost.mjs.map +1 -1
  139. package/dist/index.d.mts +18 -17
  140. package/dist/index.mjs +8 -7
  141. package/package.json +1 -1
  142. package/src/capabilities/internal/subagent-background.ts +66 -23
  143. package/src/capabilities/internal/subagent-contract.ts +4 -0
  144. package/src/core/AgentError.ts +20 -0
  145. package/src/core/FailureDiagnostic.ts +343 -0
  146. package/src/core/Worker.ts +4 -1
  147. package/src/durable/Digest.ts +22 -28
  148. package/src/durable/DurableAgentRuntime.ts +37 -13
  149. package/src/durable/MessageDelivery.ts +82 -24
  150. package/src/durable/PreparedInputAdmission.ts +17 -4
  151. package/src/durable/Records.ts +5 -15
  152. package/src/durable/Schedule.ts +11 -2
  153. package/src/durable/SqlMessageDeliveryStore.ts +21 -9
  154. package/src/durable/SubmissionLedger.ts +4 -1
  155. package/src/durable/internal/agent-registration.ts +46 -14
  156. package/src/durable/internal/worker-host.ts +32 -19
  157. package/src/engine/RunOptions.ts +11 -3
  158. package/src/engine/SubagentHost.ts +3 -0
  159. package/src/engine/internal/agent-runtime.ts +23 -16
  160. package/src/index.ts +1 -0
  161. package/dist/AgentRuntime-BWOnNc0d.mjs.map +0 -1
  162. package/dist/DurableAgentRuntime-C9eRZS9N.mjs.map +0 -1
  163. package/dist/Records-D8167fHn.mjs +0 -844
  164. package/dist/Records-D8167fHn.mjs.map +0 -1
  165. package/dist/Subagent-C2s8PFrd.mjs.map +0 -1
  166. package/dist/agent-registration-ByeHejH3.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"Records-D8167fHn.mjs","names":[],"sources":["../src/core/internal/strict-schema.ts","../src/durable/Records.ts"],"sourcesContent":["import { Schema, SchemaParser, SchemaTransformation } from \"effect\";\n\n/** Keep strict parsing on nested values even when an outer parser uses its defaults. */\nexport const strictSchema = <S extends Schema.Top>(schema: S) =>\n Schema.declareConstructor<S[\"Type\"], S[\"Encoded\"]>()(\n [schema],\n ([codec]) =>\n (value, _ast, options) =>\n SchemaParser.decodeUnknownEffect(codec)(value, { ...options, onExcessProperty: \"error\" }),\n {\n toCodecJson: ([codec]) =>\n Schema.link<S[\"Encoded\"]>()(codec, SchemaTransformation.passthrough()),\n },\n );\n","import { Option, Schema } from \"effect\";\nimport { Prompt } from \"effect/unstable/ai\";\n\nimport { InputMessage } from \"../capabilities/Messaging.ts\";\nimport { PolicyLimit } from \"../core/AgentError.ts\";\nimport { AgentPolicy } from \"../core/AgentPolicy.ts\";\nimport { Update } from \"../core/AgentUpdates.ts\";\nimport {\n AgentId,\n AttemptId,\n ThreadId,\n DelegationId,\n ReceiptId,\n RunId,\n SettlementId,\n SubmissionId,\n ToolCallId,\n TurnId,\n} from \"../core/Identifiers.ts\";\nimport { strictSchema } from \"../core/internal/strict-schema.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { IdempotencyKey, Principal } from \"../core/Receipt.ts\";\nimport { ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport {\n DelegationDepth,\n SubagentBudgetReservation,\n SubagentGrant,\n SubagentParentLink,\n ToolExecutionKind,\n} from \"../core/SubagentContract.ts\";\nimport { Selection, Snapshot } from \"../core/ToolExposure.ts\";\nimport { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, RunUsageSummary, RunTotals } from \"../core/Usage.ts\";\nimport { WorkerBudgetScope, WorkerRef, WorkerSource } from \"../core/Worker.ts\";\nimport { ContextHandoff } from \"../engine/ContextWindow.ts\";\n\nconst identifier = <const Name extends string>(name: Name) =>\n Schema.NonEmptyString.pipe(Schema.brand(`@effect-agent/thread/${name}`));\n\n/** Stable identity of one canonical record. */\nexport const RecordId = identifier(\"RecordId\");\nexport type RecordId = typeof RecordId.Type;\n\n/** Stable idempotency identity of one atomic append. */\nexport const BatchId = identifier(\"BatchId\");\nexport type BatchId = typeof BatchId.Type;\n\n/** Identity of the deployment that produced a record. */\nexport const DeploymentId = identifier(\"DeploymentId\");\nexport type DeploymentId = typeof DeploymentId.Type;\n\n/** Identity of a fenced canonical-log producer. */\nexport const ProducerId = identifier(\"ProducerId\");\nexport type ProducerId = typeof ProducerId.Type;\n\n/** SHA-256 digest encoded as lowercase hexadecimal text. */\nexport const Digest = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)).pipe(\n Schema.brand(\"@effect-agent/thread/Digest\"),\n);\n\nexport type Digest = typeof Digest.Type;\n\n/** Adapter-owned resume cursor. Callers must not parse or synthesize it. */\nexport const ObservationOffset = identifier(\"ObservationOffset\");\nexport type ObservationOffset = typeof ObservationOffset.Type;\n\n/** Gap-free position in one Thread's canonical sequence. */\nexport const CanonicalSequence = Schema.Natural.pipe(\n Schema.brand(\"@effect-agent/thread/CanonicalSequence\"),\n);\n\nexport type CanonicalSequence = typeof CanonicalSequence.Type;\n\n/** Monotonic fencing epoch for a Thread producer. */\nexport const ProducerEpoch = Schema.Natural.pipe(\n Schema.brand(\"@effect-agent/thread/ProducerEpoch\"),\n);\n\nexport type ProducerEpoch = typeof ProducerEpoch.Type;\n\nconst BoundedText = Schema.String.check(Schema.isMaxLength(64 * 1024));\nconst BoundedName = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/** Stable, non-empty failure classification carried by a failed durable Settlement. */\nconst SettlementFailureTag = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/** Diagnostic text is bounded independently from the broader persisted JSON envelope. */\nconst SettlementFailureMessage = Schema.String.check(Schema.isMaxLength(16 * 1024));\n\n/**\n * The complete generic diagnostic allowed on a failed durable Settlement. It deliberately has\n * no raw Cause, stack, provider payload, or application-specific fields; those values can carry\n * secrets and do not form a stable cross-process contract.\n */\nexport const SettlementFailureDiagnostic = Schema.Struct({\n errorTag: SettlementFailureTag,\n message: SettlementFailureMessage,\n}).pipe(\n strictSchema,\n Schema.annotate({\n identifier: \"@effect-agent/thread/SettlementFailureDiagnostic\",\n }),\n);\n\nexport type SettlementFailureDiagnostic = typeof SettlementFailureDiagnostic.Type;\n\n/** Positive canonical (Run-relative, Attempt-independent) Turn number. */\nconst TurnNumber = Schema.Int.check(Schema.isGreaterThan(0));\n\nexport const MAX_PERSISTED_JSON_DEPTH = 64;\nexport const MAX_PERSISTED_JSON_COLLECTION_LENGTH = 4_096;\nexport const MAX_PERSISTED_JSON_NODES = 65_536;\nexport const MAX_PERSISTED_JSON_BYTES = 1024 * 1024;\n\n/**\n * Iteratively preflights an unknown value before Schema's recursive JSON validation. This is the\n * one narrow `Schema.declare` exception in the persistence model: Effect v4's `Unknown.decodeTo`\n * preserves `unknown` as the encoded type, which would leak through every nested record codec.\n * Schema.Json still owns the accepted value shape after this resource preflight succeeds.\n */\nconst isJson = Schema.is(Schema.Json);\n\nconst isPersistedJson = (input: unknown): input is Schema.Json => {\n const pending: Array<\n | { readonly _tag: \"visit\"; readonly value: unknown; readonly depth: number }\n | { readonly _tag: \"leave\"; readonly value: object }\n > = [{ _tag: \"visit\", value: input, depth: 0 }];\n\n // Only ancestors indicate a cycle. Shared acyclic values serialize once per occurrence,\n // so revisit them and charge every occurrence against the same resource limits.\n const ancestors = new WeakSet<object>();\n let nodes = 0;\n let textUnits = 0;\n\n try {\n while (pending.length > 0) {\n const current = pending.pop();\n\n if (current === undefined) return false;\n if (current._tag === \"leave\") {\n ancestors.delete(current.value);\n continue;\n }\n if (current.depth > MAX_PERSISTED_JSON_DEPTH || ++nodes > MAX_PERSISTED_JSON_NODES) {\n return false;\n }\n\n const value = current.value;\n\n if (value === null || typeof value === \"boolean\") continue;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return false;\n continue;\n }\n if (typeof value === \"string\") {\n textUnits += value.length;\n if (textUnits > MAX_PERSISTED_JSON_BYTES) return false;\n continue;\n }\n if (typeof value !== \"object\" || ancestors.has(value)) return false;\n ancestors.add(value);\n pending.push({ _tag: \"leave\", value });\n\n const entries = Array.isArray(value)\n ? Array.from(value, (entry, index) => [index, entry] as const)\n : Object.entries(value);\n\n if (entries.length > MAX_PERSISTED_JSON_COLLECTION_LENGTH) return false;\n for (const [key, entry] of entries) {\n textUnits += typeof key === \"string\" ? key.length : 0;\n if (textUnits > MAX_PERSISTED_JSON_BYTES) return false;\n pending.push({ _tag: \"visit\", value: entry, depth: current.depth + 1 });\n }\n }\n\n if (!isJson(input)) return false;\n const encoded = JSON.stringify(input);\n\n return encoded !== undefined && utf8ByteLength(encoded) <= MAX_PERSISTED_JSON_BYTES;\n } catch {\n return false;\n }\n};\n\n/** Canonical JSON admitted to persisted records and checkpoints under explicit resource limits. */\nexport const PersistedJson = Schema.declare(isPersistedJson, {\n identifier: \"@effect-agent/thread/PersistedJson\",\n description: \"JSON bounded by canonical persistence depth, collection, node, and byte limits\",\n});\n\nexport type PersistedJson = typeof PersistedJson.Type;\n\n/** Schema-owned replay inputs whose individual definitions are incorporated into digests. */\nexport class DefinitionDigestInput extends Schema.Class<DefinitionDigestInput>(\n \"@effect-agent/thread/DefinitionDigestInput\",\n)({\n agent: PersistedJson,\n model: PersistedJson,\n tools: PersistedJson,\n}) {}\n\n/** Admission-time operation fingerprints. Agent fingerprints remain immutable evidence only. */\nexport class ReplayContract extends Schema.Class<ReplayContract>(\n \"@effect-agent/thread/ReplayContract\",\n)({\n agent: Digest,\n /** Retained for reading earlier admissions; never selects executable code. */\n agentBehavior: Schema.optionalKey(Digest),\n tools: Schema.Record(Schema.String, Digest),\n}) {}\n\n/** Digests identify admission exactly; only an unfinished operation needs replay compatibility. */\nexport class DefinitionDigests extends Schema.Class<DefinitionDigests>(\n \"@effect-agent/thread/DefinitionDigests\",\n)({\n agent: Digest,\n model: Digest,\n tools: Digest,\n replay: Schema.optionalKey(ReplayContract),\n}) {}\n\nexport class ThreadCreated extends Schema.TaggedClass<ThreadCreated>(\n \"@effect-agent/thread/ThreadCreated\",\n)(\"ThreadCreated\", {\n agentId: AgentId,\n definitions: DefinitionDigests,\n}) {}\n\n/**\n * One recorded Thread input. `submissionId` is present only for durably accepted work;\n * retained history has no admission or settlement obligation. `kind` identifies the input seam.\n */\nexport class UserInputRecorded extends Schema.TaggedClass<UserInputRecorded>(\n \"@effect-agent/thread/UserInputRecorded\",\n)(\"UserInputRecorded\", {\n submissionId: Schema.optionalKey(SubmissionId),\n kind: Schema.Literals([\"user\", \"steering\", \"follow-up\"]),\n runId: Schema.optionalKey(RunId),\n input: PersistedJson,\n messageAdmission: Schema.optionalKey(InputMessage),\n}) {}\n\n/** Immutable Run start and per-Attempt duration allowance, before any agent execution. */\nexport class RunStartedRecord extends Schema.TaggedClass<RunStartedRecord>(\n \"@effect-agent/thread/RunStartedRecord\",\n)(\"RunStarted\", {\n runId: RunId,\n /** Older private histories cannot prove programmatic accounting and must be reset. */\n policyAccountingVersion: Schema.Literal(1),\n maxDurationMillis: Schema.Finite.check(Schema.isGreaterThan(0)),\n}) {}\n\n/** An active Attempt exhausted its execution allowance; downtime alone never writes this. */\nexport class RunDurationExhausted extends Schema.TaggedClass<RunDurationExhausted>(\n \"@effect-agent/thread/RunDurationExhausted\",\n)(\"RunDurationExhausted\", { runId: RunId }) {}\n\nconst PersistedPromptMessages = Schema.toEncoded(Prompt.Prompt);\nconst isPersistedPromptMessages = Schema.is(PersistedPromptMessages);\n\n/**\n * Final model output. Immediate history may include the exact encoded Prompt suffix of the\n * successful Run; durable execution instead journals individual ModelResponseRecorded Turns.\n */\nexport class ModelCompleted extends Schema.TaggedClass<ModelCompleted>(\n \"@effect-agent/thread/ModelCompleted\",\n)(\n \"ModelCompleted\",\n Schema.Struct({\n runId: RunId,\n output: PersistedJson,\n messages: Schema.optionalKey(PersistedJson),\n }).check(\n Schema.makeFilter(\n (record) => record.messages === undefined || isPersistedPromptMessages(record.messages),\n { title: \"Retained Run messages are Schema-encoded Effect AI Prompt messages\" },\n ),\n ),\n) {}\n\nexport class ToolCallSettled extends Schema.TaggedClass<ToolCallSettled>(\n \"@effect-agent/thread/ToolCallSettled\",\n)(\"ToolCallSettled\", {\n toolSelection: Schema.optionalKey(Selection),\n runId: RunId,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n result: PersistedJson,\n isFailure: Schema.Boolean,\n /** Explicit engine evidence, never inferred from Tool result data. */\n budgetRejected: Schema.optionalKey(Schema.Literal(true)),\n}) {}\n\n/** Compact execution evidence committed with a declaration, before any handler can start. */\nexport class ToolOperation extends Schema.Class<ToolOperation>(\n \"@effect-agent/thread/ToolOperation\",\n)({\n toolCallId: ToolCallId,\n toolName: BoundedName,\n executionClass: Schema.Literals([\"readonly\", \"idempotent\", \"uncertain\"]),\n executionKind: ToolExecutionKind,\n replay: Digest,\n}) {}\n\n/** A retired call's runtime result. Unavailable readonly work may already have been observed. */\nexport class ToolUnavailable extends Schema.TaggedClass<ToolUnavailable>()(\"ToolUnavailable\", {\n toolName: BoundedName,\n execution: Schema.Literals([\"not-executed\", \"unavailable\"]),\n message: BoundedText,\n}) {}\n\n/**\n * One committed model Turn. `messages` carries the Schema-encoded Effect AI Prompt messages this\n * Turn appended (assistant response plus any tool-call declarations), committed atomically at the\n * Turn boundary so a recovering Attempt can rebuild the next Prompt from canonical records alone.\n * `messagesDigest` pins the exact encoded content.\n */\nconst ModelResponseRecordedFields = Schema.Struct({\n /** Original operation identity/semantics, independent of later Agent and toolbox changes. */\n toolOperations: Schema.optionalKey(Schema.Array(ToolOperation)),\n /** Explicit pre-execution failures, committed with the original arguments before any approval. */\n toolParameterRejections: Schema.optionalKey(Schema.Array(ToolParameterRejection)),\n toolExposure: Schema.optionalKey(Snapshot),\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n messages: PersistedJson,\n messagesDigest: Digest,\n /**\n * Number of leading messages that belong only to this Run's evaluated instructions and wake\n * input. They remain canonical. Continuations replace the instruction messages with current\n * instructions while retaining user input; later Runs also retain that original user intent.\n * Records without this field retain their full history.\n */\n runScopedPrefixLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n /**\n * Exact normalized usage for every model call staged into this Turn. A\n * summarizer and the Turn response are distinct entries. Absent on legacy\n * records, whose aggregate totals below retain the old resume behavior.\n */\n modelUsage: Schema.optionalKey(Schema.Array(ModelCallUsage)),\n /** Observed invocations without retained accounting before this Turn committed. */\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n /** Aggregate compatibility fields used by older projections. */\n inputTokens: Schema.optionalKey(Schema.Natural),\n outputTokens: Schema.optionalKey(Schema.Natural),\n /** Estimated spend staged with the usage; recovery re-seeds the cost budget (RUN-023). */\n costMicrousd: Schema.optionalKey(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (response) =>\n response.runScopedPrefixLength === undefined ||\n (isPersistedPromptMessages(response.messages) &&\n response.runScopedPrefixLength < response.messages.content.length &&\n response.messages.content\n .slice(0, response.runScopedPrefixLength)\n .every((message) => message.role === \"system\" || message.role === \"user\")),\n {\n title:\n \"Run-scoped Prompt prefix contains only instruction/wake messages and leaves one response\",\n },\n ),\n);\n\nexport class ModelResponseRecorded extends Schema.TaggedClass<ModelResponseRecorded>(\n \"@effect-agent/thread/ModelResponseRecorded\",\n)(\"ModelResponseRecorded\", ModelResponseRecordedFields) {}\n\n/**\n * One approved uncertain/idempotent ordinary Tool Call made durable BEFORE any handler starts\n * (durability §10). `parameters` is the Schema-encoded wire form of the declared call and\n * `parametersDigest` pins it; recovery that sees this record without a matching `ToolCallSettled`\n * (or `ToolCallUnknown` → `ToolCallResolved`) must reconcile or mark unknown, never silently\n * replay (DUR-009). Ordinary `readonly`-class Tools never produce this record. Delegation\n * classification is always prepared, including for a Tool annotated `readonly`.\n */\nexport class ToolCallPrepared extends Schema.TaggedClass<ToolCallPrepared>(\n \"@effect-agent/thread/ToolCallPrepared\",\n)(\"ToolCallPrepared\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n parameters: PersistedJson,\n parametersDigest: Digest,\n /** Absent legacy evidence grants no delegation replay authority. */\n executionKind: Schema.optionalKey(ToolExecutionKind),\n executionClass: Schema.optionalKey(ToolOperation.fields.executionClass),\n replay: Schema.optionalKey(Digest),\n}) {}\n\n/** Monotonic reservations charged before programmatic execution or grace finalization. */\nexport class RunPolicyUsageReserved extends Schema.TaggedClass<RunPolicyUsageReserved>()(\n \"RunPolicyUsageReserved\",\n {\n runId: RunId,\n programmaticToolCalls: RunPolicyUsage.fields.programmaticToolCalls,\n finalizationUsed: RunPolicyUsage.fields.finalizationUsed,\n },\n) {}\n\n/**\n * A durable Unknown Outcome: the external effect of one prepared ordinary Tool Call may have\n * happened but was not confirmed canonically (DUR-009/DUR-017). It is neither success nor\n * ordinary failure; automatic continuation stops until an authorized resolution arrives.\n */\nexport class ToolCallUnknown extends Schema.TaggedClass<ToolCallUnknown>(\n \"@effect-agent/thread/ToolCallUnknown\",\n)(\"ToolCallUnknown\", {\n runId: RunId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n reason: BoundedText,\n}) {}\n\n/** How one open/unknown Tool Call was authoritatively closed (DUR-017 resolution audit). */\nexport const ToolCallResolution = Schema.Literals([\n \"completed-with-result\",\n \"failed-with-error\",\n \"never-started\",\n \"safe-retry\",\n]);\n\nexport type ToolCallResolution = typeof ToolCallResolution.Type;\n\n/**\n * The canonical audit record closing one open or unknown Tool Call: reconciler-recovered supplier\n * truth or an authorized `resolveUnknown` command. `author`/`reason` make every resolution an\n * attributable decision (DUR-017); a `completed-with-result` resolution is accompanied by the\n * per-call `ToolCallSettled` record carrying the recovered result.\n */\nexport class ToolCallResolved extends Schema.TaggedClass<ToolCallResolved>(\n \"@effect-agent/thread/ToolCallResolved\",\n)(\"ToolCallResolved\", {\n runId: RunId,\n toolCallId: ToolCallId,\n resolution: ToolCallResolution,\n author: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * One accepted Durable Step result (durability §11): exactly-once-recorded while the Step's\n * external side effect stays honestly at-least-once-executed. Only success is recorded — a failing\n * Step body fails into the handler's error channel and re-executes on re-entry. `output` is the\n * Schema-encoded Step output; `outputDigest` pins it for replay-divergence detection.\n */\nexport class ToolStepSettled extends Schema.TaggedClass<ToolStepSettled>(\n \"@effect-agent/thread/ToolStepSettled\",\n)(\"ToolStepSettled\", {\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: BoundedName,\n output: PersistedJson,\n outputDigest: Digest,\n}) {}\n\n/**\n * A canonical approval request for one declared Tool Call (CAP-006, durability §8): with this\n * record durable, \"waiting for explicit approval\" is a safe suspension boundary — the resumed\n * Attempt replays the declared batch instead of re-invoking the model.\n */\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>(\n \"@effect-agent/thread/ToolApprovalRequested\",\n)(\"ToolApprovalRequested\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n parametersDigest: Digest,\n}) {}\n\n/** The two-valued approval decision family shared by canonical records and ledger intents. */\nexport const ApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\nexport type ApprovalDecision = typeof ApprovalDecision.Type;\n\n/**\n * The canonical decision for one requested approval. Appended by the deciding Attempt (policy\n * auto-decisions) or by the resuming Attempt after a durable `resolveApproval` intent; it is the\n * deterministic decision authority for every later Attempt of the same Run.\n */\nexport class ToolApprovalDecided extends Schema.TaggedClass<ToolApprovalDecided>(\n \"@effect-agent/thread/ToolApprovalDecided\",\n)(\"ToolApprovalDecided\", {\n runId: RunId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n decision: ApprovalDecision,\n resolver: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * First-class interruption audit (durability §9): appended by a superseding Attempt before it\n * re-invokes the model for a Turn whose prior owner died without a complete canonical response.\n * Duplicate provider cost is thereby possible AND observable in canonical history.\n */\nexport class ModelResponseInterrupted extends Schema.TaggedClass<ModelResponseInterrupted>(\n \"@effect-agent/thread/ModelResponseInterrupted\",\n)(\"ModelResponseInterrupted\", {\n runId: RunId,\n supersededEpoch: ProducerEpoch,\n attemptId: AttemptId,\n reason: BoundedText,\n}) {}\n\n/**\n * One engine-native compaction committed before the pre-Turn view changes (RUN-026).\n * `coversThrough` is a Thread record sequence: the projection\n * renders records at or below it as a summary (`summarize`), a fresh window (`rollover`), or with\n * cleared tool results (kind `clear-tool-results`), never erasing source\n * history. The record carries no digest by decision: it is appended by the\n * fenced owner into the very log it covers, and re-verifying a digest would\n * re-read the covered range on every wake — the O(history) work compaction\n * exists to remove. Host-supplied ContextCompactor decisions use this same commit path.\n * Summaries exceeding BoundedText are rejected before append, never truncated.\n * `summary` is present exactly for `summarize` records; the projection\n * treats a summarize record without one as invalid and ignores it fail-safe.\n */\nexport class CompactionCreated extends Schema.TaggedClass<CompactionCreated>(\n \"@effect-agent/thread/CompactionCreated\",\n)(\"CompactionCreated\", {\n runId: RunId,\n turn: TurnNumber,\n kind: Schema.Literals([\"clear-tool-results\", \"summarize\", \"rollover\"]),\n coversThrough: CanonicalSequence,\n summary: Schema.optionalKey(BoundedText),\n handoff: Schema.optionalKey(ContextHandoff),\n}) {}\n\nexport class RunFailed extends Schema.TaggedClass<RunFailed>(\"@effect-agent/thread/RunFailed\")(\n \"RunFailed\",\n {\n runId: RunId,\n failure: PersistedJson,\n },\n) {}\n\nconst RunCompletedFields = Schema.Struct({\n runId: RunId,\n output: PersistedJson,\n /** Integrity of validated terminal values, independent of future application codecs. */\n resultDigest: Schema.optionalKey(Digest),\n /** Application disposition captured with an ordinary completion. */\n runDisposition: Schema.optionalKey(PersistedJson),\n /** Honest soft-landing marker, present exactly when `exhausted` is present. */\n finishReason: Schema.optionalKey(Schema.Literal(\"budget-exhausted\")),\n /** Budget dimension paired with `finishReason` on a soft landing. */\n exhausted: Schema.optionalKey(ExhaustedLimit),\n}).check(\n Schema.makeFilter(\n (completed) =>\n (completed.finishReason === undefined) === (completed.exhausted === undefined) &&\n (completed.runDisposition === undefined || completed.finishReason === undefined),\n { title: \"Run completion metadata matches its terminal family\" },\n ),\n);\n\nexport class RunCompleted extends Schema.TaggedClass<RunCompleted>(\n \"@effect-agent/thread/RunCompleted\",\n)(\"RunCompleted\", RunCompletedFields) {}\n\nexport class RepairAnnotated extends Schema.TaggedClass<RepairAnnotated>(\n \"@effect-agent/thread/RepairAnnotated\",\n)(\"RepairAnnotated\", {\n reason: BoundedText,\n details: PersistedJson,\n}) {}\n\n/** Terminal outcome family for one accepted Submission (DUR-002). */\nexport const SettlementOutcome = Schema.Literals([\"completed\", \"failed\", \"aborted\"]);\nexport type SettlementOutcome = typeof SettlementOutcome.Type;\n\n/**\n * A durable abort command made canonical before the active worker is interrupted (DUR-012).\n * Repeating the same abort command is idempotent; abort never rewrites a prior terminal outcome.\n */\nexport class AbortRequested extends Schema.TaggedClass<AbortRequested>(\n \"@effect-agent/thread/AbortRequested\",\n)(\"AbortRequested\", {\n submissionId: SubmissionId,\n author: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * The single canonical settlement record owed to one accepted Submission (DUR-002, DUR-011).\n * Canonical history is the outcome authority: the ledger row is finalized from this record and\n * never the other way around (DUR-015).\n */\nconst RawSubmissionSettled = Schema.Struct({\n submissionId: SubmissionId,\n settlementId: SettlementId,\n receiptId: ReceiptId,\n outcome: SettlementOutcome,\n runId: Schema.optionalKey(RunId),\n result: Schema.optionalKey(PersistedJson),\n /**\n * Application-defined, Schema-encoded disposition for an ordinary completed\n * Run. Absent for budget exhaustion and every non-completed or run-less\n * settlement; consumers decode it with the application definition's Schema.\n */\n runDisposition: Schema.optionalKey(PersistedJson),\n /**\n * Present only when a `completed` Run settled through the final-answer\n * exhaustion resolution (RUN-011, RUN-018): the durable log must be able to\n * distinguish honest-exhaustion completion from ordinary completion without\n * the live event stream. Absent for every ordinary settlement, keeping\n * existing histories and goldens byte-stable (additive, schemaVersion 1).\n */\n finishReason: Schema.optionalKey(Schema.Literal(\"budget-exhausted\")),\n /**\n * The dimension that bound a budget-exhausted completion (RUN-011,\n * RUN-025), carried verbatim from the live `RunCompleted` event so\n * consumers never reconstruct it from message text. Valid only alongside\n * `finishReason: \"budget-exhausted\"`; absent on histories persisted before\n * the dimension became durable (additive, schemaVersion 1).\n */\n exhausted: Schema.optionalKey(ExhaustedLimit),\n /**\n * The typed `AgentPolicyError.limit` of a `failed` hard-rail settlement\n * (RUN-011): which finite policy dimension failed the Run, preserved\n * alongside the bounded `{errorTag, message}` failure projection in\n * `result`. Absent for every non-policy failure and on histories persisted\n * before the limit became durable (additive, schemaVersion 1).\n */\n policyLimit: Schema.optionalKey(PolicyLimit),\n /** Canonical aggregate of all priced model calls made by this Run. */\n usageSummary: Schema.optionalKey(RunUsageSummary),\n /** Calls included in usageSummary but not in any ModelResponseRecorded, retained on failure. */\n uncommittedModelUsage: Schema.optionalKey(Schema.Array(ModelCallUsage)),\n});\n\nconst isPolicyFailureProjection = Schema.is(\n Schema.Struct({ errorTag: Schema.Literal(\"AgentPolicyError\") }),\n);\n\nconst decodeSettlementFailureDiagnostic = Schema.decodeUnknownOption(SettlementFailureDiagnostic, {\n onExcessProperty: \"error\",\n});\n\nconst hasValidSettlementFamily = (settled: typeof RawSubmissionSettled.Type): boolean =>\n (settled.finishReason === undefined || settled.outcome === \"completed\") &&\n (settled.finishReason === undefined) === (settled.exhausted === undefined) &&\n (settled.usageSummary === undefined || settled.runId !== undefined) &&\n (settled.uncommittedModelUsage === undefined ||\n (settled.runId !== undefined && settled.usageSummary !== undefined)) &&\n (settled.runDisposition === undefined ||\n (settled.outcome === \"completed\" &&\n settled.finishReason === undefined &&\n settled.runId !== undefined &&\n settled.result !== undefined)) &&\n (settled.outcome !== \"failed\" ||\n Option.isSome(decodeSettlementFailureDiagnostic(settled.result))) &&\n (settled.outcome !== \"aborted\" || settled.result === undefined) &&\n (settled.policyLimit === undefined ||\n (settled.outcome === \"failed\" && isPolicyFailureProjection(settled.result)));\n\nconst SubmissionSettledFields = RawSubmissionSettled.check(\n Schema.makeFilter(hasValidSettlementFamily, {\n title:\n \"failed settlements require a bounded diagnostic; aborted settlements carry no result; budget metadata must match its settlement family\",\n }),\n);\n\nexport class SubmissionSettled extends Schema.TaggedClass<SubmissionSettled>(\n \"@effect-agent/thread/SubmissionSettled\",\n)(\"SubmissionSettled\", SubmissionSettledFields) {}\n\n/** Canonical completed settlement; joined completion may legitimately carry no independent result. */\nexport type CompletedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"completed\";\n};\n\n/** Canonical failed settlement; its bounded diagnostic is required and typed. */\nexport type FailedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"failed\";\n readonly result: SettlementFailureDiagnostic;\n};\n\n/** Canonical aborted settlement; abort records intent rather than fabricating a terminal result. */\nexport type AbortedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"aborted\";\n readonly result?: never;\n};\n\nexport type SubmissionSettledRecord =\n | CompletedSubmissionSettled\n | FailedSubmissionSettled\n | AbortedSubmissionSettled;\n\n/**\n * Canonical-boundary view of `SubmissionSettled`: `finishReason` is valid\n * only on a `completed` outcome, `exhausted` only alongside\n * `finishReason: \"budget-exhausted\"`, every `failed` outcome requires the exact bounded\n * `SettlementFailureDiagnostic`, aborted outcomes carry no result, and `policyLimit` only occurs\n * on a `failed` outcome whose diagnostic carries the `AgentPolicyError` tag. `runDisposition`\n * occurs only on an ordinary completed settlement with a Run —\n * so a malformed persisted combination such as\n * `{ outcome: \"failed\", finishReason: \"budget-exhausted\" }` or a\n * `policyLimit` contradicting `result.errorTag` fails closed at decode\n * instead of becoming trusted audit history (STORE-006, RUN-011).\n */\nexport const SubmissionSettledRecord = SubmissionSettled.pipe(\n Schema.refine(\n (settled): settled is SubmissionSettledRecord => hasValidSettlementFamily(settled),\n {\n expected:\n \"failed settlements require a bounded diagnostic, aborted settlements carry no result, finishReason only occurs on completed settlements, exhausted only occurs with finishReason budget-exhausted, runDisposition only occurs on an ordinary completed settlement with a Run result, and policyLimit only occurs on a failed AgentPolicyError settlement\",\n },\n ),\n);\n\n/**\n * PARENT-log record of one durable child establishment request:\n * the exact parent Tool Call, delegation and target identity, the digests that pin the child's\n * Binding/input/grant, the fenced budget reservation, and the INTENDED child identity derived\n * deterministically from the parent Run and Tool Call pair (D4). `childInput` carries the\n * prepared child input in encoded form (D3) so recovery can complete child admission from this\n * record alone — no live delegation handler is required. `childPrincipal`/`childIdempotencyKey`\n * carry the ledger admission scope with the ledger's exact bounds; the layering keeps their\n * branded Schemas in the ledger port.\n */\nexport class SubagentRequested extends Schema.TaggedClass<SubagentRequested>(\n \"@effect-agent/thread/SubagentRequested\",\n)(\"SubagentRequested\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n delegationId: DelegationId,\n targetAgentId: AgentId,\n targetDigests: DefinitionDigests,\n childInput: PersistedJson,\n childInputDigest: Digest,\n grantDigest: Digest,\n reservationId: BoundedName,\n reservationDigest: Digest,\n childThreadId: ThreadId,\n childPrincipal: BoundedName,\n childIdempotencyKey: BoundedName,\n /** Effective invocation bound, already clamped to the delegation and child Definition. */\n toolCallAllowance: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n policy: Schema.optionalKey(Schema.toCodecJson(AgentPolicy)),\n budget: Schema.optionalKey(SubagentBudgetReservation),\n grant: Schema.optionalKey(SubagentGrant),\n depth: Schema.optionalKey(DelegationDepth),\n}) {}\n\n/**\n * PARENT-log record that the intended child exists as accepted work:\n * the full established child identity. It is appended only after the child Receipt\n * exists — SUB-017 holds by construction because `childReceiptId` is a required field.\n */\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>(\n \"@effect-agent/thread/SubagentStarted\",\n)(\"SubagentStarted\", {\n runId: RunId,\n toolCallId: ToolCallId,\n childThreadId: ThreadId,\n childSubmissionId: SubmissionId,\n childReceiptId: ReceiptId,\n childRunId: RunId,\n}) {}\n\n/**\n * PARENT-log record of one verified child settlement join:\n * the child's canonical Settlement identity and outcome, the digests pinning the verified child\n * result and the bounded projected parent result, the child usage summary, and the FINAL\n * consumed/released accounting decision for the reservation. It commits in ONE atomic batch with\n * the parent `ToolCallSettled` record (SUB-019); `beginChildBudgetRelease` replays\n * `finalAccounting` from this record, so canonical history authorizes the release (DUR-015).\n */\nexport class SubagentJoined extends Schema.TaggedClass<SubagentJoined>(\n \"@effect-agent/thread/SubagentJoined\",\n)(\"SubagentJoined\", {\n runId: RunId,\n toolCallId: ToolCallId,\n childSubmissionId: SubmissionId,\n childSettlementId: SettlementId,\n childOutcome: SettlementOutcome,\n childResultDigest: Digest,\n projectedResultDigest: Digest,\n usageSummary: PersistedJson,\n usage: Schema.optionalKey(RunTotals),\n delegatedUsage: Schema.optionalKey(RunTotals),\n reservationId: BoundedName,\n finalAccounting: PersistedJson,\n}) {}\n\n/**\n * CHILD-log immutable lineage: the Parent Link plus the digests that pin\n * the child's definition, input, and authority grant. It is the first record after the child's\n * `ThreadCreated` (its own single-record batch, so the generic `thread-created:{cid}`\n * batch identity is never contradicted) and the join path verifies it fail-closed — a fabricated\n * child or parent identity fails Parent Link verification (SUB-004, D10).\n */\nexport class SubagentLineageRecorded extends Schema.TaggedClass<SubagentLineageRecorded>(\n \"@effect-agent/thread/SubagentLineageRecorded\",\n)(\"SubagentLineageRecorded\", {\n parentLink: SubagentParentLink,\n parentSubmissionId: SubmissionId,\n childDefinitionDigests: DefinitionDigests,\n childInputDigest: Digest,\n grantDigest: Digest,\n /** Copied from the canonical request before readiness; restored for every child Attempt. */\n toolCallAllowance: SubagentRequested.fields.toolCallAllowance,\n policy: SubagentRequested.fields.policy,\n budget: SubagentRequested.fields.budget,\n grant: SubagentRequested.fields.grant,\n}) {}\n\nexport const WorkerReportingIntent = Schema.Struct({\n /** Omitted preserves existing application-mapped reports. */\n mode: Schema.optionalKey(Schema.Literal(\"standard\")),\n sourceDigests: DefinitionDigests,\n destinationDelegationId: Schema.optionalKey(DelegationId),\n});\n\n/** Immutable worker Thread origin. Each input has its own digest and parameters separately. */\nexport const WorkerOrigin = Schema.Struct({\n worker: WorkerRef,\n source: WorkerSource,\n /** Omitted retains source-subtree funding; worker-run renews only for a new native Run. */\n budgetScope: Schema.optionalKey(WorkerBudgetScope),\n targetDigests: DefinitionDigests,\n policy: Schema.toCodecJson(AgentPolicy),\n budget: SubagentBudgetReservation,\n grant: SubagentGrant,\n depth: DelegationDepth,\n toolCallAllowance: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n firstMessageId: IdempotencyKey,\n createdAtMillis: Schema.Natural,\n expiresAtMillis: Schema.Natural,\n /** Exact source registration owns projection; absence means reporting was not declared. */\n reporting: Schema.optionalKey(WorkerReportingIntent),\n}).check(Schema.makeFilter((value) => value.expiresAtMillis > value.createdAtMillis));\n\nexport type WorkerOrigin = typeof WorkerOrigin.Type;\n\n/** Frozen per-input metadata; it grants no attached-child or parent-abort semantics. */\nexport const WorkerAdmission = Schema.Struct({\n origin: WorkerOrigin,\n messageId: IdempotencyKey,\n parameters: PersistedJson,\n createdAtMillis: Schema.Natural,\n /** Host-bound source input whose subtree funds this input; never chosen by a model. */\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n /** Enables routed receipt lookup when the delivery is owned by a reporting child. */\n deliveryPrincipal: Schema.optionalKey(Principal),\n /** Proven framework updates use a separate bounded input-capacity partition. */\n reportKind: Schema.optionalKey(Schema.Literal(\"update\")),\n});\n\nexport type WorkerAdmission = typeof WorkerAdmission.Type;\n\n/** Source-log capacity reservation, retained independently of the source Run's settlement. */\nexport class WorkerInputRequested extends Schema.TaggedClass<WorkerInputRequested>()(\n \"WorkerInputRequested\",\n { admission: WorkerAdmission, inputDigest: Digest },\n) {}\n\n/** Child-log origin, reconstructed from a retained delivery before the child becomes ready. */\nexport class WorkerOriginRecorded extends Schema.TaggedClass<WorkerOriginRecorded>()(\n \"WorkerOriginRecorded\",\n { origin: WorkerOrigin },\n) {}\n\n/** Canonical child completion acknowledgement releases only this input's active capacity. */\nexport class WorkerInputCompleted extends Schema.TaggedClass<WorkerInputCompleted>()(\n \"WorkerInputCompleted\",\n {\n messageId: IdempotencyKey,\n workerThreadId: ThreadId,\n submissionId: SubmissionId,\n receiptId: ReceiptId,\n settlementId: SettlementId,\n completedAtMillis: Schema.Natural,\n /** New acknowledgements prove that this input's external effects are resolved. */\n effectsResolved: Schema.optionalKey(Schema.Literal(true)),\n },\n) {}\n\n/**\n * Frozen report decision for one actual Run, shared by every joined Receipt. The envelope is\n * a Schema-encoded PreparedInput, validated before append and decoded again on recovery.\n * Keeping the encoded value here avoids a Records/PreparedInput schema dependency cycle.\n */\nexport class WorkerReportPrepared extends Schema.TaggedClass<WorkerReportPrepared>()(\n \"WorkerReportPrepared\",\n {\n runId: RunId,\n messageId: IdempotencyKey,\n envelope: PersistedJson,\n createdAtMillis: Schema.Natural,\n deadlineAtMillis: Schema.Natural,\n predecessor: Schema.optionalKey(IdempotencyKey),\n },\n) {}\n\n/** Accepted update and its optional frozen parent delivery are one atomic canonical fact. */\nexport class AgentUpdateEmitted extends Schema.TaggedClass<AgentUpdateEmitted>()(\n \"AgentUpdateEmitted\",\n {\n update: Update,\n definitions: DefinitionDigests,\n delivery: Schema.optionalKey(\n Schema.Struct({\n messageId: IdempotencyKey,\n envelope: PersistedJson,\n createdAtMillis: Schema.Natural,\n deadlineAtMillis: Schema.Natural,\n predecessor: Schema.optionalKey(IdempotencyKey),\n }),\n ),\n },\n) {}\n\n/** Permanent bounded report refusal. Application errors and raw Run dispositions stay private. */\nexport class WorkerReportRefused extends Schema.TaggedClass<WorkerReportRefused>()(\n \"WorkerReportRefused\",\n {\n runId: RunId,\n messageId: IdempotencyKey,\n reason: Schema.Literals([\n \"declaration-unavailable\",\n \"destination\",\n \"projection\",\n \"input\",\n \"preparation\",\n \"timeout\",\n \"defect\",\n \"expired\",\n \"denied\",\n \"capacity\",\n ]),\n },\n) {}\n\n/** Frozen source proof of peer provenance, readable through routed canonical storage. */\nexport class PeerMessagePrepared extends Schema.TaggedClass<PeerMessagePrepared>()(\n \"PeerMessagePrepared\",\n {\n messageId: IdempotencyKey,\n sourcePrincipal: Principal,\n operation: Schema.Literals([\"send\", \"reply\"]),\n deadlineAtMillis: Schema.Int.check(Schema.isGreaterThan(0)),\n encodedEnvelope: PersistedJson,\n },\n) {}\n\n/**\n * One disjoint subtree slice shared by attached and background children of a source input.\n * The source keeps its own execution ceiling; descendants spend only the remaining allocation.\n * Reservations include future descendant slots and never refund, including after interruption.\n * resultBytes reserves the terminal/projection result, not cumulative Tool output bytes.\n */\nexport class SubtreeBudgetReserved extends Schema.TaggedClass<SubtreeBudgetReserved>()(\n \"SubtreeBudgetReserved\",\n {\n reservationId: BoundedName,\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n childThreadId: ThreadId,\n lifetime: Schema.Literals([\"attached\", \"background\"]),\n depth: DelegationDepth,\n policy: Schema.toCodecJson(AgentPolicy),\n grant: SubagentGrant,\n budget: SubagentBudgetReservation,\n },\n) {}\n\n/**\n * Current private-development canonical payload family. Phase 5 adds the seven durable-Tool tags\n * (prepared/unknown/resolved/step/approval-request/approval-decision/interrupted) additively; S2\n * adds the four durable-Subagent tags (requested/started/joined/lineage) additively, so the\n * envelope keeps `schemaVersion: 1` (P4 precedent for additive payload tags).\n */\nexport const CanonicalRecordPayload = Schema.Union([\n ThreadCreated,\n UserInputRecorded,\n RunStartedRecord,\n RunDurationExhausted,\n RunPolicyUsageReserved,\n ModelCompleted,\n ModelResponseRecorded,\n ToolCallPrepared,\n ToolCallSettled,\n ToolCallUnknown,\n ToolCallResolved,\n ToolStepSettled,\n ToolApprovalRequested,\n ToolApprovalDecided,\n ModelResponseInterrupted,\n CompactionCreated,\n RunFailed,\n RunCompleted,\n AbortRequested,\n SubmissionSettledRecord,\n SubagentRequested,\n SubagentStarted,\n SubagentJoined,\n SubagentLineageRecorded,\n WorkerInputRequested,\n WorkerOriginRecorded,\n WorkerInputCompleted,\n WorkerReportPrepared,\n AgentUpdateEmitted,\n WorkerReportRefused,\n PeerMessagePrepared,\n SubtreeBudgetReserved,\n RepairAnnotated,\n]);\n\nexport type CanonicalRecordPayload = typeof CanonicalRecordPayload.Type;\n\n/**\n * Versioned record envelope stored in an atomic batch. Thread ordering is assigned only\n * when the batch is committed.\n */\nexport class RecordEnvelope extends Schema.Class<RecordEnvelope>(\n \"@effect-agent/thread/RecordEnvelope\",\n)({\n recordId: RecordId,\n family: Schema.Literal(\"thread\"),\n schemaVersion: Schema.Literal(1),\n createdAt: Schema.DateTimeUtcFromString,\n deploymentId: DeploymentId,\n payload: CanonicalRecordPayload,\n}) {}\n\n/** Backward-compatible domain name for a canonical record. */\nexport const CanonicalRecord = RecordEnvelope;\nexport type CanonicalRecord = RecordEnvelope;\n\n/** One non-empty, bounded, idempotent atomic append unit. */\nexport class CanonicalBatch extends Schema.Class<CanonicalBatch>(\n \"@effect-agent/thread/CanonicalBatch\",\n)({\n batchId: BatchId,\n producerId: ProducerId,\n records: Schema.NonEmptyArray(RecordEnvelope).check(Schema.isMaxLength(256)),\n}) {}\n\n/**\n * A committed record with its Thread ordering and opaque resumable observation cursor.\n */\nexport class CanonicalRecordEnvelope extends Schema.Class<CanonicalRecordEnvelope>(\n \"@effect-agent/thread/CanonicalRecordEnvelope\",\n)({\n threadId: ThreadId,\n batchId: BatchId,\n sequence: CanonicalSequence,\n offset: ObservationOffset,\n record: RecordEnvelope,\n}) {}\n\nexport const CURRENT_CANONICAL_SCHEMA_VERSION = 1 as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGA,MAAa,gBAAsC,WACjD,OAAO,mBAA4C,CAAC,CAClD,CAAC,MAAM,IACN,CAAC,YACC,OAAO,MAAM,YACZ,aAAa,oBAAoB,KAAK,CAAC,CAAC,OAAO;CAAE,GAAG;CAAS,kBAAkB;AAAQ,CAAC,GAC5F,EACE,cAAc,CAAC,WACb,OAAO,KAAmB,CAAC,CAAC,OAAO,qBAAqB,YAAY,CAAC,EACzE,CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACwBF,MAAM,cAAyC,SAC7C,OAAO,eAAe,KAAK,OAAO,MAAM,wBAAwB,MAAM,CAAC;;AAGzE,MAAa,WAAW,WAAW,UAAU;;AAI7C,MAAa,UAAU,WAAW,SAAS;;AAI3C,MAAa,eAAe,WAAW,cAAc;;AAIrD,MAAa,aAAa,WAAW,YAAY;;AAIjD,MAAa,SAAS,OAAO,OAAO,MAAM,OAAO,UAAU,gBAAgB,CAAC,CAAC,CAAC,KAC5E,OAAO,MAAM,6BAA6B,CAC5C;;AAKA,MAAa,oBAAoB,WAAW,mBAAmB;;AAI/D,MAAa,oBAAoB,OAAO,QAAQ,KAC9C,OAAO,MAAM,wCAAwC,CACvD;;AAKA,MAAa,gBAAgB,OAAO,QAAQ,KAC1C,OAAO,MAAM,oCAAoC,CACnD;AAIA,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC;AACrE,MAAM,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C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"Subagent-C2s8PFrd.mjs","names":["background","IdGenerator","backgroundDeclaration"],"sources":["../src/capabilities/internal/subagent-contract.ts","../src/capabilities/internal/subagent-policy.ts","../src/capabilities/internal/subagent-reporting.ts","../src/capabilities/internal/subagent-background.ts","../src/capabilities/Subagent.ts"],"sourcesContent":["import { Duration, Schema } from \"effect\";\n\nimport { AgentId, DelegationId } from \"../../core/Identifiers.ts\";\nimport { SubagentDelegationCaps, SubagentReservationAmounts } from \"../../core/SubagentContract.ts\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\nconst Natural = Schema.Natural;\n\nconst FinitePositiveDuration = Schema.Duration.pipe(\n Schema.refine(\n (duration): duration is Duration.Duration =>\n Duration.isFinite(duration) && Duration.isPositive(duration),\n { expected: \"a finite positive duration\" },\n ),\n);\n\nconst SubagentPolicyFields = Schema.Struct({\n /** Total invocation slots, including reserved descendants, available through this delegation budget. */\n maxChildren: PositiveInt,\n /** Concurrently executing children per parent Run. */\n maxConcurrency: PositiveInt,\n /** Invocation slots held for the entire descendant subtree; omitted reserves zero. */\n descendantInvocations: Schema.optionalKey(Natural),\n /** Model turns reserved for each child invocation. */\n maxTurns: PositiveInt,\n /** Tool Calls reserved for each child invocation. */\n maxToolCalls: PositiveInt,\n /** Wall-clock duration reserved for each child invocation. */\n maxDuration: FinitePositiveDuration,\n maxInputTokens: Schema.optionalKey(PositiveInt),\n maxOutputTokens: Schema.optionalKey(PositiveInt),\n maxCostMicrousd: Schema.optionalKey(Natural),\n maxResultBytes: Schema.optionalKey(PositiveInt),\n});\n\ntype SubagentPolicyFields = typeof SubagentPolicyFields.Type;\n\n/** Inputs normalized and validated by `SubagentPolicy.make`. */\nexport type SubagentPolicyInput = Readonly<\n Omit<SubagentPolicyFields, \"maxDuration\"> & {\n /** Finite, positive wall-clock duration accepted in any Effect Duration input form. */\n readonly maxDuration: Duration.Input;\n }\n>;\n\n/**\n * Finite delegation bounds declared by one Subagent capability.\n * Structural limits are hard limits; token\n * and cost caps are optional and enforced only as honestly as provider\n * reporting allows.\n */\nexport class SubagentPolicy extends Schema.Class<SubagentPolicy>(\n \"@effect-agent/capabilities/SubagentPolicy\",\n)(SubagentPolicyFields) {\n /** Normalize and validate finite delegation bounds, throwing on invalid input. */\n static override make(input: SubagentPolicyInput): SubagentPolicy {\n return super.make({\n ...input,\n maxDuration: Duration.fromInputUnsafe(input.maxDuration),\n });\n }\n}\n\nconst BoundedFailureText = Schema.String.check(Schema.isMaxLength(4 * 1024));\n\n/**\n * Delegation preflight denied before any child started.\n * No reservation, identity, or event exists for the\n * denied invocation; retry requires a new authorized parent Tool Call.\n */\nexport class SubagentPrestartDenied extends Schema.TaggedError<SubagentPrestartDenied>()(\n \"SubagentPrestartDenied\",\n {\n delegationId: DelegationId,\n targetAgentId: AgentId,\n reason: Schema.Literals([\"nested-delegation\", \"grant-violation\", \"budget-conflict\"]),\n message: BoundedFailureText,\n },\n) {}\n\n/**\n * Input or result projection failed its Schema or bounds.\n * Fail closed: the message is a fixed description and\n * never carries the raw child value.\n */\nexport class SubagentProjectionFailure extends Schema.TaggedError<SubagentProjectionFailure>()(\n \"SubagentProjectionFailure\",\n {\n delegationId: DelegationId,\n stage: Schema.Literals([\"input\", \"result\"]),\n message: BoundedFailureText,\n },\n) {}\n\nexport {\n SubagentExecutionFailureClassification,\n SubagentExecutionFailure,\n maxErrorTagLength,\n} from \"../../core/SubagentContract.ts\";\n\nconst millisOfMaxDuration = (policy: SubagentPolicy): number =>\n Math.max(1, Math.ceil(Duration.toMillis(policy.maxDuration)));\n\n/**\n * Derive the parent-Run delegation caps registered with\n * `SubagentReservations` from one delegation policy: the per-invocation\n * bounds scaled by `maxChildren` plus the invocation and concurrency limits.\n */\nexport const delegationCapsFromPolicy = (policy: SubagentPolicy): SubagentDelegationCaps =>\n SubagentDelegationCaps.make({\n maxTotalChildInvocations: policy.maxChildren,\n maxConcurrentChildren: policy.maxConcurrency,\n maxTurns: policy.maxChildren * policy.maxTurns,\n maxToolCalls: policy.maxChildren * policy.maxToolCalls,\n maxDurationMillis: policy.maxChildren * millisOfMaxDuration(policy),\n ...(policy.maxInputTokens === undefined\n ? {}\n : { maxInputTokens: policy.maxChildren * policy.maxInputTokens }),\n ...(policy.maxOutputTokens === undefined\n ? {}\n : { maxOutputTokens: policy.maxChildren * policy.maxOutputTokens }),\n ...(policy.maxCostMicrousd === undefined\n ? {}\n : { maxCostMicrousd: policy.maxChildren * policy.maxCostMicrousd }),\n ...(policy.maxResultBytes === undefined\n ? {}\n : { maxResultBytes: policy.maxChildren * policy.maxResultBytes }),\n });\n\n/** Derive the all-or-nothing per-invocation reservation from one delegation policy. */\nexport const delegationAllocationFromPolicy = (\n policy: SubagentPolicy,\n): SubagentReservationAmounts =>\n SubagentReservationAmounts.make({\n turns: policy.maxTurns,\n toolCalls: policy.maxToolCalls,\n durationMillis: millisOfMaxDuration(policy),\n inputTokens: policy.maxInputTokens ?? 0,\n outputTokens: policy.maxOutputTokens ?? 0,\n costMicrousd: policy.maxCostMicrousd ?? 0,\n resultBytes: policy.maxResultBytes ?? 0,\n });\n","import { Duration } from \"effect\";\n\nimport type { AnyDefinition } from \"../../core/Agent.ts\";\nimport { AgentPolicy } from \"../../core/AgentPolicy.ts\";\nimport {\n SubagentDelegationCaps,\n type SubagentBudgetReservation,\n} from \"../../core/SubagentContract.ts\";\nimport {\n SubagentPolicy,\n delegationCapsFromPolicy,\n delegationAllocationFromPolicy,\n} from \"./subagent-contract.ts\";\n\nexport const resolveSubagentPolicy = (\n delegation: {\n readonly target: Pick<AnyDefinition, \"policy\" | \"policyOverrides\">;\n readonly policy?: SubagentPolicy | undefined;\n },\n parent: AgentPolicy,\n parentCaps?: SubagentDelegationCaps,\n mode: \"root-attached\" | \"conserved\" = \"conserved\",\n resolvedTarget?: AgentPolicy,\n) => {\n // A root attached declaration has its own explicit pool. Child overrides retain\n // that established behavior; background and inherited subtree launches also obey\n // the source's own ceilings, before their shared reservation checks the residual.\n const parentCeiling = mode === \"conserved\" ? parent : undefined;\n\n const inherited =\n resolvedTarget ??\n AgentPolicy.resolve(delegation.target.policyOverrides ?? delegation.target.policy, parent);\n\n const policy =\n delegation.policy ??\n SubagentPolicy.make({\n maxChildren: parent.maxToolCalls,\n maxConcurrency: parent.toolConcurrency,\n maxTurns: Math.min(inherited.maxTurns, parent.maxTurns),\n maxToolCalls: Math.min(inherited.maxToolCalls, parent.maxToolCalls),\n maxDuration: Duration.min(inherited.maxDuration, parent.maxDuration),\n ...(parent.tokenBudget === undefined\n ? {}\n : { maxInputTokens: parent.tokenBudget, maxOutputTokens: parent.tokenBudget }),\n ...(parent.costBudgetMicrousd === undefined\n ? {}\n : { maxCostMicrousd: parent.costBudgetMicrousd }),\n maxResultBytes: parent.toolResultBounds.maxBytes,\n });\n\n const tokenCeiling =\n policy.maxInputTokens === undefined || policy.maxOutputTokens === undefined\n ? Math.min(inherited.tokenBudget ?? Infinity, parentCeiling?.tokenBudget ?? Infinity)\n : Math.min(\n inherited.tokenBudget ?? Infinity,\n parentCeiling?.tokenBudget ?? Infinity,\n policy.maxInputTokens + policy.maxOutputTokens,\n );\n\n const childPolicy = AgentPolicy.make({\n ...inherited,\n maxTurns: Math.min(inherited.maxTurns, policy.maxTurns, parentCeiling?.maxTurns ?? Infinity),\n maxToolCalls: Math.min(\n inherited.maxToolCalls,\n policy.maxToolCalls,\n parentCeiling?.maxToolCalls ?? Infinity,\n ),\n maxDuration: Duration.min(\n Duration.min(inherited.maxDuration, policy.maxDuration),\n parentCeiling?.maxDuration ?? Duration.infinity,\n ),\n toolConcurrency: Math.min(\n inherited.toolConcurrency,\n parentCeiling?.toolConcurrency ?? Infinity,\n ),\n ...(parentCeiling === undefined\n ? {}\n : {\n toolResultBounds: {\n maxBytes: Math.min(\n inherited.toolResultBounds.maxBytes,\n parentCeiling.toolResultBounds.maxBytes,\n Math.max(256, policy.maxResultBytes ?? Infinity),\n ),\n },\n }),\n ...(tokenCeiling === Infinity\n ? {}\n : {\n tokenBudget: tokenCeiling,\n completionReserveTokens: Math.min(inherited.completionReserveTokens, tokenCeiling),\n }),\n ...(Math.min(\n inherited.costBudgetMicrousd ?? Infinity,\n parentCeiling?.costBudgetMicrousd ?? Infinity,\n policy.maxCostMicrousd ?? Infinity,\n ) === Infinity\n ? {}\n : {\n costBudgetMicrousd: Math.min(\n inherited.costBudgetMicrousd ?? Infinity,\n parentCeiling?.costBudgetMicrousd ?? Infinity,\n policy.maxCostMicrousd ?? Infinity,\n ),\n }),\n });\n\n const caps =\n parentCaps ??\n (delegation.policy === undefined\n ? SubagentDelegationCaps.make({\n maxTotalChildInvocations: parent.maxToolCalls,\n maxConcurrentChildren: parent.toolConcurrency,\n maxTurns: parent.maxTurns,\n maxToolCalls: parent.maxToolCalls,\n maxDurationMillis: Math.ceil(Duration.toMillis(parent.maxDuration)),\n ...(parent.tokenBudget === undefined\n ? {}\n : { maxInputTokens: parent.tokenBudget, maxOutputTokens: parent.tokenBudget }),\n ...(parent.costBudgetMicrousd === undefined\n ? {}\n : { maxCostMicrousd: parent.costBudgetMicrousd }),\n })\n : delegationCapsFromPolicy(policy));\n\n return { policy, childPolicy, allocation: delegationAllocationFromPolicy(policy), caps };\n};\n\nexport const resolveToolCallAllowance = <Parameters>(\n option:\n | {\n readonly default: number;\n readonly fromParameters?: (parameters: Parameters) => number | undefined;\n }\n | undefined,\n parameters: Parameters,\n policy: SubagentPolicy,\n childPolicy: AgentPolicy,\n): number => {\n if (option === undefined) return childPolicy.maxToolCalls;\n const extracted = option.fromParameters?.(parameters);\n\n // A non-finite parameter falls back to the author default, then the reservation.\n const requested =\n extracted !== undefined && Number.isFinite(extracted)\n ? extracted\n : Number.isFinite(option.default)\n ? option.default\n : policy.maxToolCalls;\n\n return Math.min(\n Math.max(1, Math.floor(requested)),\n policy.maxToolCalls,\n childPolicy.maxToolCalls,\n );\n};\n\n/** Conservative subtree remainder after reserving this Run's own full execution ceiling. */\nexport const residualSubagentCaps = (\n declared: SubagentDelegationCaps,\n parent: AgentPolicy,\n inherited: SubagentBudgetReservation,\n independentRun = false,\n): SubagentDelegationCaps => {\n const allocation = inherited.allocation;\n\n const remaining = (allocated: number, own: number, cap: number | undefined) =>\n Math.min(cap ?? Infinity, Math.max(0, allocated - own));\n\n return SubagentDelegationCaps.make({\n maxTotalChildInvocations: Math.min(\n declared.maxTotalChildInvocations ?? Infinity,\n inherited.descendantInvocations ?? 0,\n ),\n maxConcurrentChildren: Math.min(\n declared.maxConcurrentChildren ?? Infinity,\n parent.toolConcurrency,\n inherited.descendantInvocations ?? 0,\n ),\n maxTurns: remaining(allocation.turns, parent.maxTurns, declared.maxTurns),\n maxToolCalls: remaining(allocation.toolCalls, parent.maxToolCalls, declared.maxToolCalls),\n maxDurationMillis: remaining(\n allocation.durationMillis,\n Math.ceil(Duration.toMillis(parent.maxDuration)),\n declared.maxDurationMillis,\n ),\n ...(independentRun &&\n inherited.caps.maxInputTokens === undefined &&\n allocation.inputTokens === 0 &&\n parent.tokenBudget === undefined\n ? declared.maxInputTokens === undefined\n ? {}\n : { maxInputTokens: declared.maxInputTokens }\n : {\n maxInputTokens: remaining(\n allocation.inputTokens,\n parent.tokenBudget ?? allocation.inputTokens,\n declared.maxInputTokens,\n ),\n }),\n ...(independentRun &&\n inherited.caps.maxOutputTokens === undefined &&\n allocation.outputTokens === 0 &&\n parent.tokenBudget === undefined\n ? declared.maxOutputTokens === undefined\n ? {}\n : { maxOutputTokens: declared.maxOutputTokens }\n : {\n maxOutputTokens: remaining(\n allocation.outputTokens,\n parent.tokenBudget ?? allocation.outputTokens,\n declared.maxOutputTokens,\n ),\n }),\n ...(independentRun &&\n inherited.caps.maxCostMicrousd === undefined &&\n allocation.costMicrousd === 0 &&\n parent.costBudgetMicrousd === undefined\n ? declared.maxCostMicrousd === undefined\n ? {}\n : { maxCostMicrousd: declared.maxCostMicrousd }\n : {\n maxCostMicrousd: remaining(\n allocation.costMicrousd,\n parent.costBudgetMicrousd ?? allocation.costMicrousd,\n declared.maxCostMicrousd,\n ),\n }),\n maxResultBytes: remaining(\n allocation.resultBytes,\n parent.toolResultBounds.maxBytes,\n declared.maxResultBytes,\n ),\n });\n};\n","import { Effect, Schema } from \"effect\";\n\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\nimport { Receipt } from \"../../core/Receipt.ts\";\nimport { type WorkerReport, WorkerCompletion } from \"../../core/Worker.ts\";\nimport {\n WorkerReportPreparationFailure,\n type WorkerReporting,\n type WorkerRunReport,\n} from \"../../engine/SubagentHost.ts\";\nimport { type Declaration } from \"./subagent-background.ts\";\nimport { SubagentExecutionFailure } from \"./subagent-contract.ts\";\n\nexport { WorkerReport } from \"../../core/Worker.ts\";\n\nconst projectReport = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n) =>\n Effect.fn(\"Subagent.projectReport\")(function* (report: WorkerRunReport) {\n const { worker, observation } = report;\n const invalid = () => WorkerReportPreparationFailure.make({ stage: \"projection\" });\n\n if (\n worker.delegationId !== declaration.delegationId ||\n worker.targetAgentId !== declaration.target.id ||\n observation.receipt.threadId !== worker.threadId\n )\n return yield* invalid();\n\n const base = {\n _tag: \"Settled\" as const,\n worker,\n receipt: yield* Schema.decodeEffect(Receipt)(observation.receipt).pipe(\n Effect.mapError(invalid),\n ),\n runId: observation.runId,\n settlementId: observation.settlementId,\n };\n\n let projected: WorkerReport<Success>;\n let encodedResult: Schema.Json = null;\n\n if (observation.outcome === \"completed\") {\n const parameters = yield* Schema.decodeUnknownEffect(declaration.parameters)(\n observation.encodedParameters,\n ).pipe(Effect.mapError(invalid));\n\n const output = yield* Schema.decodeUnknownEffect(declaration.target.output)(\n observation.encodedResult,\n ).pipe(Effect.mapError(invalid));\n\n const result = yield* declaration.projectResult(\n output,\n { budgetExhausted: observation.budgetExhausted },\n parameters,\n );\n\n const encoded = yield* Schema.encodeEffect(declaration.success)(result).pipe(\n Effect.mapError(invalid),\n );\n\n const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError(invalid),\n );\n\n if (\n utf8ByteLength(JSON.stringify(json)) >\n (declaration.policy?.maxResultBytes ?? declaration.target.policy.toolResultBounds.maxBytes)\n )\n return yield* invalid();\n projected = { ...base, outcome: \"completed\", result };\n encodedResult = json;\n } else {\n projected = {\n ...base,\n outcome: observation.outcome,\n failure: SubagentExecutionFailure.make({\n delegationId: declaration.delegationId,\n targetAgentId: declaration.target.id,\n classification: observation.outcome === \"failed\" ? \"child-failed\" : \"child-aborted\",\n childThreadId: worker.threadId,\n childSubmissionId: observation.receipt.submissionId,\n childRunId: observation.runId,\n errorTag: observation.outcome === \"failed\" ? \"WorkerFailed\" : \"WorkerAborted\",\n message:\n observation.outcome === \"failed\" ? \"Worker input failed\" : \"Worker input was aborted\",\n }),\n };\n }\n\n return { projected, encodedResult };\n });\n\n/** Framework reporting shares the same bounded declaration projection as custom mapping. */\nexport const automaticReporting = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n) => ({\n delegationId: declaration.delegationId,\n target: declaration.target,\n mode: \"standard\" as const,\n prepare: Effect.fn(\"Subagent.automaticReport\")(function* (report: WorkerRunReport) {\n const { projected, encodedResult } = yield* projectReport(declaration)(report);\n\n const encoded =\n projected.outcome === \"completed\"\n ? { ...projected, result: encodedResult }\n : {\n ...projected,\n failure: yield* Schema.encodeEffect(SubagentExecutionFailure)(projected.failure).pipe(\n Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: \"projection\" })),\n ),\n };\n\n const message = yield* Schema.decodeEffect(WorkerCompletion)({\n _tag: \"WorkerCompletion\",\n schemaVersion: 1,\n report: encoded,\n budgetExhausted: report.observation.budgetExhausted,\n }).pipe(Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: \"projection\" })));\n\n return { encodedInput: null, message };\n }),\n});\n\n/**\n * Define an optional application-specific conversion for `background({ reportToParent: report })`.\n * Existing Agent Registration `reporting` arrays remain supported. The input Schema must be the coordinator Definition's exact input Schema.\n * Preparation is bounded by the durable host; a retained prepared envelope is never reprojected\n * during delivery retries. The callback should be deterministic and have no external side effects.\n */\nexport const reporting = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n CoordinatorInput extends Schema.Top,\n ReportFailure extends Schema.Top = typeof Schema.Never,\n ReportRequirements = never,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n options: {\n readonly input: CoordinatorInput;\n readonly failure?: ReportFailure;\n readonly prepare: (\n report: WorkerReport<Success>,\n ) => Effect.Effect<CoordinatorInput[\"Type\"], ReportFailure[\"Type\"], ReportRequirements>;\n },\n): WorkerReporting<\n Failure[\"Type\"] | ReportFailure[\"Type\"],\n | Parameters[\"DecodingServices\"]\n | Output[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | CoordinatorInput[\"EncodingServices\"]\n | Project\n | ReportRequirements\n> => {\n const prepare = Effect.fn(\"Subagent.reporting.prepare\")(function* (report: WorkerRunReport) {\n const { projected } = yield* projectReport(declaration)(report);\n const input = yield* options.prepare(projected);\n\n const encoded = yield* Schema.encodeEffect(options.input)(input).pipe(\n Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: \"input\" })),\n );\n\n const encodedInput = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError(() => WorkerReportPreparationFailure.make({ stage: \"input\" })),\n );\n\n return { encodedInput };\n });\n\n return Object.freeze({\n delegationId: declaration.delegationId,\n target: declaration.target,\n input: options.input,\n prepare,\n });\n};\n\n/**\n * Adapt a report expressed in a receiving worker declaration's Parameters to its Agent input.\n * Use this on that worker's registration when it can itself launch reporting workers. This\n * explicit conversion preserves custom Parameters and charges the next input to its ancestor.\n */\nexport const reportingToWorker = <\n E,\n R,\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n report: WorkerReporting<E, R>,\n destination: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n): WorkerReporting<\n E | Failure[\"Type\"],\n R | Prepare | Parameters[\"DecodingServices\"] | Input[\"EncodingServices\"]\n> => {\n if (report.input !== destination.parameters) {\n throw new TypeError(\n \"Worker reporting must use the destination declaration's Parameters Schema\",\n );\n }\n\n return Object.freeze({\n delegationId: report.delegationId,\n target: report.target,\n input: destination.target.input,\n destination: { delegationId: destination.delegationId, target: destination.target },\n prepare: Effect.fn(\"Subagent.reportingToWorker.prepare\")(function* (run: WorkerRunReport) {\n const encodedParameters = (yield* report.prepare(run)).encodedInput;\n const invalid = () => WorkerReportPreparationFailure.make({ stage: \"input\" });\n\n const parameters = yield* Schema.decodeEffect(destination.parameters)(encodedParameters).pipe(\n Effect.mapError(invalid),\n );\n\n const input = yield* destination.prepareInput(parameters, {\n source: \"programmatic\",\n delegationId: destination.delegationId,\n parent: { agentId: run.context.source.agentId, threadId: run.context.source.threadId },\n });\n\n const encoded = yield* Schema.encodeEffect(destination.target.input)(input).pipe(\n Effect.mapError(invalid),\n );\n\n const encodedInput = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError(invalid),\n );\n\n return { encodedInput, encodedParameters };\n }),\n });\n};\n","import type { Scope } from \"effect\";\nimport { Context, Crypto, Effect, Encoding, Layer, Option, Schema, Stream } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport type { AnyDefinition } from \"../../core/Agent.ts\";\nimport { RunId, SettlementId, ThreadId } from \"../../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\nimport { IdempotencyKey, JoinedToHost, Receipt } from \"../../core/Receipt.ts\";\nimport {\n BackgroundSpawnTool,\n narrowSubagentGrant,\n SubagentBudgetReservation,\n SubagentGrant,\n} from \"../../core/SubagentContract.ts\";\nimport {\n WorkerContext,\n type WorkerBudgetScope,\n WorkerError,\n WorkerOperationTool,\n WorkerPage,\n WorkerRef,\n WorkerStarted,\n WorkerSummary,\n} from \"../../core/Worker.ts\";\nimport {\n SubagentHost,\n BackgroundReporting,\n WorkerReportPreparationFailure,\n type WorkerReporting,\n type WorkerObservation as HostObservation,\n} from \"../../engine/SubagentHost.ts\";\nimport type { SubagentDefineOptions, SubagentPrepareContext } from \"../Subagent.ts\";\nimport {\n SubagentExecutionFailure,\n SubagentPrestartDenied,\n SubagentProjectionFailure,\n} from \"./subagent-contract.ts\";\nimport { resolveSubagentPolicy, resolveToolCallAllowance } from \"./subagent-policy.ts\";\nimport { automaticReporting } from \"./subagent-reporting.ts\";\nimport { utf8Bytes } from \"./utf8.ts\";\n\nexport type Declaration<\n Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n> = Pick<\n SubagentDefineOptions<\n Input,\n Output,\n unknown,\n Record<string, Tool.Any>,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project\n >,\n | \"parameters\"\n | \"success\"\n | \"failure\"\n | \"prepareInput\"\n | \"projectResult\"\n | \"policy\"\n | \"toolCallAllowance\"\n | \"needsApproval\"\n> & {\n readonly name: Name;\n readonly delegationId: WorkerRef[\"delegationId\"];\n readonly target: AnyDefinition & { readonly input: Input; readonly output: Output };\n readonly grant: SubagentGrant;\n};\n\ntype WorkerDeclaration<Name extends string> = {\n readonly name: Name;\n readonly delegationId: WorkerRef[\"delegationId\"];\n readonly target: Pick<AnyDefinition, \"id\">;\n};\n\n/** Portable identity checked against this declaration; possession grants no authority. */\nexport const Worker = <const Name extends string>(declaration: WorkerDeclaration<Name>) =>\n WorkerRef.check(\n Schema.makeFilter(\n (worker) =>\n worker.delegationId === declaration.delegationId &&\n worker.targetAgentId === declaration.target.id,\n ),\n ).pipe(Schema.brand(`@effect-agent/Worker/${declaration.name}`));\n\nexport type Worker<Name extends string> = ReturnType<typeof Worker<Name>>[\"Type\"];\n\n/** Observes one exact Receipt. Terminal failure data never includes raw child output. */\nexport const WorkerObservation = <Success extends Schema.Top>(success: Success) =>\n Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Pending\"), receipt: Receipt }),\n Schema.Struct({\n _tag: Schema.Literal(\"Settled\"),\n receipt: Receipt,\n runId: RunId,\n settlementId: SettlementId,\n outcome: Schema.Literal(\"completed\"),\n result: success,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Settled\"),\n receipt: Receipt,\n runId: Schema.optionalKey(RunId),\n settlementId: SettlementId,\n outcome: Schema.Literals([\"failed\", \"aborted\"]),\n failure: SubagentExecutionFailure,\n }),\n ]);\n\nexport type WorkerObservation<Success extends Schema.Top> = ReturnType<\n typeof WorkerObservation<Success>\n>[\"Type\"];\n\nconst host: Effect.Effect<SubagentHost[\"Service\"], WorkerError, SubagentHost> =\n Effect.serviceOption(SubagentHost).pipe(\n Effect.flatMap((service) =>\n Option.match(service, {\n onNone: () => WorkerError.make({ operation: \"context\", reason: \"unavailable\" }),\n onSome: Effect.succeed,\n }),\n ),\n );\n\nconst receiptEqual = (left: Receipt, right: Receipt): boolean =>\n left.threadId === right.threadId &&\n left.submissionId === right.submissionId &&\n left.receiptId === right.receiptId &&\n left.queueSequence === right.queueSequence;\n\nconst operations = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n) => {\n const workerSchema = Worker(declaration);\n\n const projectionFailure = (stage: \"input\" | \"result\") =>\n SubagentProjectionFailure.make({\n delegationId: declaration.delegationId,\n stage,\n message:\n stage === \"input\"\n ? \"Worker input did not satisfy the declaration Schema\"\n : \"Worker result did not satisfy the declaration Schema\",\n });\n\n const validateWorker = (worker: unknown, operation: WorkerError[\"operation\"]) =>\n Schema.decodeUnknownEffect(workerSchema)(worker).pipe(\n Effect.mapError(() => WorkerError.make({ operation, reason: \"worker-mismatch\" })),\n );\n\n const validateReceipt = (\n worker: WorkerRef,\n receipt: Receipt,\n operation: WorkerError[\"operation\"],\n ) =>\n Schema.decodeEffect(\n Receipt.check(Schema.makeFilter((value) => value.threadId === worker.threadId)),\n )(receipt).pipe(\n Effect.mapError(() => WorkerError.make({ operation, reason: \"receipt-mismatch\" })),\n );\n\n const context: Effect.Effect<WorkerContext, WorkerError, SubagentHost> = host.pipe(\n Effect.flatMap((service) => service.context),\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.toType(WorkerContext))),\n Effect.mapError((error) =>\n Schema.is(WorkerError)(error)\n ? error\n : WorkerError.make({ operation: \"context\", reason: \"corrupt\" }),\n ),\n );\n\n const prepare = Effect.fn(\"Subagent.prepareWorkerInput\")(function* (\n parameters: Parameters[\"Type\"],\n caller: WorkerContext,\n ) {\n const encodedParameters = yield* Schema.encodeEffect(declaration.parameters)(parameters).pipe(\n Effect.mapError(() => projectionFailure(\"input\")),\n );\n\n const source = caller.source;\n\n const preparation: SubagentPrepareContext =\n source._tag === \"tool\"\n ? {\n source: \"tool\",\n delegationId: declaration.delegationId,\n toolCallId: source.toolCallId,\n parent: { agentId: source.agentId, threadId: source.threadId, runId: source.runId },\n }\n : {\n source: \"programmatic\",\n delegationId: declaration.delegationId,\n parent: { agentId: source.agentId, threadId: source.threadId },\n };\n\n const input = yield* declaration.prepareInput(parameters, preparation);\n\n const encodedInput = yield* Schema.encodeEffect(declaration.target.input)(input).pipe(\n Effect.mapError(() => projectionFailure(\"input\")),\n );\n\n return { encodedParameters, encodedInput };\n });\n\n const validateKey = (key: IdempotencyKey, operation: \"start\" | \"followUp\") =>\n Schema.decodeEffect(IdempotencyKey)(key).pipe(\n Effect.mapError(() => WorkerError.make({ operation, reason: \"idempotency-conflict\" })),\n );\n\n const start = Effect.fn(\"Subagent.start\")(function* (\n parameters: Parameters[\"Type\"],\n options: { readonly idempotencyKey: IdempotencyKey; readonly budgetScope?: WorkerBudgetScope },\n ) {\n const service = yield* host;\n const caller = yield* context;\n const key = yield* validateKey(options.idempotencyKey, \"start\");\n\n const grant = narrowSubagentGrant(declaration.grant, caller.grant);\n\n if (caller.depth + 1 > grant.maxDepth) {\n return yield* SubagentPrestartDenied.make({\n delegationId: declaration.delegationId,\n targetAgentId: declaration.target.id,\n reason: \"nested-delegation\",\n message: \"Worker start exceeds the inherited depth ceiling\",\n });\n }\n if (!(caller.grant?.childLifetimes ?? [\"attached\", \"background\"]).includes(\"background\")) {\n return yield* SubagentPrestartDenied.make({\n delegationId: declaration.delegationId,\n targetAgentId: declaration.target.id,\n reason: \"grant-violation\",\n message: \"The inherited grant does not permit background children\",\n });\n }\n\n const prepared = yield* prepare(parameters, caller);\n\n const effectiveTarget = yield* service.resolveTargetPolicy({\n target: declaration.target,\n encodedInput: prepared.encodedInput,\n });\n\n const resolvedTarget = Option.getOrUndefined(effectiveTarget);\n\n const resolved = resolveSubagentPolicy(\n declaration,\n options.budgetScope === \"worker-run\"\n ? (resolvedTarget ?? declaration.target.policy)\n : caller.policy,\n undefined,\n options.budgetScope === \"worker-run\" ? \"root-attached\" : \"conserved\",\n resolvedTarget,\n );\n\n const encodedGrant = yield* Schema.encodeEffect(SubagentGrant)(grant).pipe(\n Effect.mapError(() => projectionFailure(\"input\")),\n );\n\n const started = yield* service.start({\n ...prepared,\n delegationId: declaration.delegationId,\n target: declaration.target,\n idempotencyKey: key,\n ...(options.budgetScope === undefined ? {} : { budgetScope: options.budgetScope }),\n encodedGrant,\n policy: resolved.childPolicy,\n budget: SubagentBudgetReservation.make({\n caps: resolved.caps,\n allocation: resolved.allocation,\n ...(resolved.policy.descendantInvocations === undefined\n ? {}\n : { descendantInvocations: resolved.policy.descendantInvocations }),\n }),\n toolCallAllowance: resolveToolCallAllowance(\n declaration.toolCallAllowance,\n parameters,\n resolved.policy,\n resolved.childPolicy,\n ),\n });\n\n const validated = yield* Schema.decodeEffect(WorkerStarted)(started).pipe(\n Effect.mapError(() => WorkerError.make({ operation: \"start\", reason: \"corrupt\" })),\n );\n\n return { worker: yield* validateWorker(validated.worker, \"start\"), receipt: validated.receipt };\n });\n\n const followUp = Effect.fn(\"Subagent.followUp\")(function* (\n worker: Worker<Name>,\n parameters: Parameters[\"Type\"],\n options: { readonly idempotencyKey: IdempotencyKey },\n ) {\n const service = yield* host;\n const validated = yield* validateWorker(worker, \"followUp\");\n const caller = yield* context;\n const key = yield* validateKey(options.idempotencyKey, \"followUp\");\n const prepared = yield* prepare(parameters, caller);\n\n return yield* validateReceipt(\n validated,\n yield* service.followUp({\n ...prepared,\n worker: validated,\n target: declaration.target,\n idempotencyKey: key,\n }),\n \"followUp\",\n );\n });\n\n const observe = Effect.fn(\"Subagent.observeWorker\")(function* (\n operation: \"inspect\" | \"await\",\n worker: Worker<Name>,\n receipt: Receipt,\n ): Effect.fn.Return<\n WorkerObservation<Success>,\n WorkerError | SubagentProjectionFailure | Failure[\"Type\"],\n | SubagentHost\n | Parameters[\"DecodingServices\"]\n | Output[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Project\n > {\n const service = yield* host;\n const validated = yield* validateWorker(worker, operation);\n const requested = yield* validateReceipt(validated, receipt, operation);\n\n const observed: HostObservation = yield* service[operation]({\n worker: validated,\n target: declaration.target,\n receipt: requested,\n });\n\n const returned = yield* validateReceipt(validated, observed.receipt, operation);\n\n if (!receiptEqual(returned, requested))\n return yield* WorkerError.make({ operation, reason: \"receipt-mismatch\" });\n if (observed._tag === \"Pending\") {\n if (operation === \"await\") return yield* WorkerError.make({ operation, reason: \"corrupt\" });\n\n return { _tag: \"Pending\", receipt: returned };\n }\n\n const base = {\n _tag: \"Settled\" as const,\n receipt: returned,\n ...(observed.runId === undefined\n ? {}\n : {\n runId: yield* Schema.decodeEffect(RunId)(observed.runId).pipe(\n Effect.mapError(() => WorkerError.make({ operation, reason: \"corrupt\" })),\n ),\n }),\n settlementId: yield* Schema.decodeEffect(SettlementId)(observed.settlementId).pipe(\n Effect.mapError(() => WorkerError.make({ operation, reason: \"corrupt\" })),\n ),\n };\n\n if (observed.outcome === \"failed\" || observed.outcome === \"aborted\") {\n return {\n ...base,\n outcome: observed.outcome,\n failure: SubagentExecutionFailure.make({\n delegationId: declaration.delegationId,\n targetAgentId: declaration.target.id,\n classification: observed.outcome === \"failed\" ? \"child-failed\" : \"child-aborted\",\n childThreadId: worker.threadId,\n childSubmissionId: returned.submissionId,\n ...(base.runId === undefined ? {} : { childRunId: base.runId }),\n errorTag: observed.outcome === \"failed\" ? \"WorkerFailed\" : \"WorkerAborted\",\n message:\n observed.outcome === \"failed\" ? \"Worker input failed\" : \"Worker input was aborted\",\n }),\n };\n }\n if (\n observed.outcome !== \"completed\" ||\n base.runId === undefined ||\n typeof observed.budgetExhausted !== \"boolean\"\n ) {\n return yield* WorkerError.make({ operation, reason: \"corrupt\" });\n }\n\n const parameters = yield* Schema.decodeUnknownEffect(declaration.parameters)(\n observed.encodedParameters,\n ).pipe(Effect.mapError(() => projectionFailure(\"result\")));\n\n const output = yield* Schema.decodeUnknownEffect(declaration.target.output)(\n observed.encodedResult,\n ).pipe(Effect.mapError(() => projectionFailure(\"result\")));\n\n const result = yield* declaration.projectResult(\n output,\n { budgetExhausted: observed.budgetExhausted },\n parameters,\n );\n\n const encoded = yield* Schema.encodeEffect(declaration.success)(result).pipe(\n Effect.mapError(() => projectionFailure(\"result\")),\n );\n\n const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError(() => projectionFailure(\"result\")),\n );\n\n const caller = yield* context;\n\n if (\n utf8ByteLength(JSON.stringify(json)) >\n (declaration.policy?.maxResultBytes ?? caller.policy.toolResultBounds.maxBytes)\n ) {\n return yield* projectionFailure(\"result\");\n }\n\n return yield* Schema.decodeUnknownEffect(Schema.toType(WorkerObservation(declaration.success)))(\n { ...base, outcome: \"completed\", result },\n ).pipe(Effect.mapError(() => projectionFailure(\"result\")));\n });\n\n const list = Effect.fn(\"Subagent.list\")(function* (\n options: { readonly limit?: number; readonly after?: ThreadId } = {},\n ) {\n const service = yield* host;\n\n const limit = yield* Schema.decodeEffect(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n )(options.limit ?? 20).pipe(\n Effect.mapError(() => WorkerError.make({ operation: \"list\", reason: \"capacity\" })),\n );\n\n const page = yield* service.list({\n delegationId: declaration.delegationId,\n target: declaration.target,\n limit,\n ...(options.after === undefined ? {} : { after: options.after }),\n });\n\n const validated = yield* Schema.decodeEffect(WorkerPage)(page).pipe(\n Effect.mapError(() => WorkerError.make({ operation: \"list\", reason: \"corrupt\" })),\n );\n\n if (validated.items.length > limit)\n return yield* WorkerError.make({ operation: \"list\", reason: \"corrupt\" });\n const items = [];\n\n for (const item of validated.items) {\n const worker = yield* validateWorker(item.worker, \"list\");\n\n const latestReceipt =\n item.latestReceipt === null\n ? null\n : yield* validateReceipt(worker, item.latestReceipt, \"list\");\n\n items.push({ ...item, worker, latestReceipt });\n }\n\n return { items, next: validated.next };\n });\n\n const cancel = Effect.fn(\"Subagent.cancel\")(function* (worker: Worker<Name>, receipt: Receipt) {\n const service = yield* host;\n const validated = yield* validateWorker(worker, \"cancel\");\n const requested = yield* validateReceipt(validated, receipt, \"cancel\");\n\n yield* service.cancel({ worker: validated, target: declaration.target, receipt: requested });\n });\n\n return { start, followUp, observe, list, cancel };\n};\n\n/** Start a host-managed worker. Retrying the same explicit key reuses the accepted input. */\nexport const start = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n parameters: Parameters[\"Type\"],\n options: { readonly idempotencyKey: IdempotencyKey; readonly budgetScope?: WorkerBudgetScope },\n) => operations(declaration).start(parameters, options);\n\n/** Admit typed follow-up parameters to the same worker Thread. */\nexport const followUp = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n worker: Worker<Name>,\n parameters: Parameters[\"Type\"],\n options: { readonly idempotencyKey: IdempotencyKey },\n) => operations(declaration).followUp(worker, parameters, options);\n\n/** Inspect a continuing worker with the same summary contract returned by list. */\nexport const summary = <const Name extends string>(\n declaration: WorkerDeclaration<Name> & { readonly target: AnyDefinition },\n worker: Worker<Name>,\n) =>\n Effect.gen(function* () {\n const service = yield* host;\n\n const validated = yield* Schema.decodeEffect(Worker(declaration))(worker).pipe(\n Effect.mapError(() => WorkerError.make({ operation: \"inspect\", reason: \"worker-mismatch\" })),\n );\n\n const result = yield* service.summary({ worker: validated, target: declaration.target });\n\n const value = yield* Schema.decodeEffect(WorkerSummary)(result).pipe(\n Effect.mapError(() => WorkerError.make({ operation: \"inspect\", reason: \"corrupt\" })),\n );\n\n if (\n value.worker.threadId !== validated.threadId ||\n value.worker.delegationId !== validated.delegationId ||\n value.worker.targetAgentId !== validated.targetAgentId ||\n (value.latestReceipt !== null && value.latestReceipt.threadId !== validated.threadId)\n )\n return yield* WorkerError.make({ operation: \"inspect\", reason: \"worker-mismatch\" });\n\n return { ...value, worker: validated };\n });\n\n/** Inspect the worker, or pass a Receipt to observe that exact accepted input. */\nexport function inspect<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n worker: Worker<Name>,\n): ReturnType<typeof summary<Name>>;\n\nexport function inspect<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n worker: Worker<Name>,\n receipt: Receipt,\n): ReturnType<\n ReturnType<\n typeof operations<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>\n >[\"observe\"]\n>;\n\nexport function inspect<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n worker: Worker<Name>,\n receipt?: Receipt,\n) {\n return receipt === undefined\n ? summary(declaration, worker)\n : operations(declaration).observe(\"inspect\", worker, receipt);\n}\n\n/** Read an authorized finite history snapshot; pass the last emitted sequence to resume. */\nexport const observe = <const Name extends string>(\n declaration: WorkerDeclaration<Name> & { readonly target: AnyDefinition },\n worker: Worker<Name>,\n options: { readonly after?: number } = {},\n) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const service = yield* host;\n\n const validated = yield* Schema.decodeEffect(Worker(declaration))(worker).pipe(\n Effect.mapError(() =>\n WorkerError.make({ operation: \"observe\", reason: \"worker-mismatch\" }),\n ),\n );\n\n const after =\n options.after === undefined\n ? undefined\n : yield* Schema.decodeEffect(Schema.Natural)(options.after).pipe(\n Effect.mapError(() => WorkerError.make({ operation: \"observe\", reason: \"corrupt\" })),\n );\n\n return service.observe({\n worker: validated,\n target: declaration.target,\n ...(after === undefined ? {} : { after }),\n });\n }),\n );\n\n/** Wait for the exact Receipt. Interrupting this Effect never cancels accepted work. */\nexport const awaitWorker = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n worker: Worker<Name>,\n receipt: Receipt,\n) => operations(declaration).observe(\"await\", worker, receipt);\n\n/** List only workers visible through the caller-bound host facet. */\nexport const list = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n options: { readonly limit?: number; readonly after?: ThreadId } = {},\n) => operations(declaration).list(options);\n\n/** Request cancellation of exactly one Receipt; JoinedToHost remains a typed conflict. */\nexport const cancel = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n worker: Worker<Name>,\n receipt: Receipt,\n) => operations(declaration).cancel(worker, receipt);\n\n/** Opt in to each model-facing operation. Waiting remains programmatic only. */\nexport interface BackgroundOptions {\n /** Deliver a standard completion, or use an optional application input mapper. */\n readonly reportToParent?: true | WorkerReporting<unknown, unknown>;\n readonly start?: true;\n readonly followUp?: true;\n readonly inspect?: true;\n readonly summary?: true;\n readonly list?: true;\n readonly cancel?: true;\n /** Author-owned funding request for starts; every native admission separately authorizes it. */\n readonly budgetScope?: WorkerBudgetScope;\n}\n\ntype Operation = Exclude<keyof BackgroundOptions, \"budgetScope\" | \"reportToParent\">;\ntype Suffix = {\n start: \"start\";\n followUp: \"follow_up\";\n inspect: \"inspect\";\n summary: \"summary\";\n list: \"list\";\n cancel: \"cancel\";\n};\n\nconst ReceiptParameters = <Name extends string>(declaration: WorkerDeclaration<Name>) =>\n Schema.Struct({ worker: Worker(declaration), receipt: Receipt });\n\nconst WorkerParameters = <Name extends string>(declaration: WorkerDeclaration<Name>) =>\n Schema.Struct({ worker: Worker(declaration) });\n\nconst Summary = <Name extends string>(declaration: WorkerDeclaration<Name>) =>\n Schema.Struct({\n worker: Worker(declaration),\n latestReceipt: Schema.NullOr(Receipt),\n state: Schema.Literals([\"starting\", \"active\", \"idle\"]),\n });\n\nconst FollowUpParameters = <Name extends string, Parameters extends Schema.Top>(\n declaration: WorkerDeclaration<Name>,\n parameters: Parameters,\n) => Schema.Struct({ worker: Worker(declaration), parameters });\n\nconst ListParameters = Schema.Struct({\n limit: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ),\n after: Schema.optionalKey(ThreadId),\n});\n\nconst Started = <Name extends string>(declaration: WorkerDeclaration<Name>) =>\n Schema.Struct({ worker: Worker(declaration), receipt: Receipt }).check(\n Schema.makeFilter((value) => value.worker.threadId === value.receipt.threadId),\n );\n\nconst Page = <Name extends string>(declaration: WorkerDeclaration<Name>) =>\n Schema.Struct({\n items: Schema.Array(\n Schema.Struct({\n worker: Worker(declaration),\n latestReceipt: Schema.NullOr(Receipt),\n state: Schema.Literals([\"starting\", \"active\", \"idle\"]),\n }),\n ).check(Schema.isMaxLength(100)),\n next: Schema.NullOr(ThreadId),\n });\n\nconst preparationFailure = <Failure extends Schema.Top>(failure: Failure) =>\n Schema.Union([failure, SubagentProjectionFailure, WorkerError]);\n\nconst startFailure = <Failure extends Schema.Top>(failure: Failure) =>\n Schema.Union([failure, SubagentProjectionFailure, SubagentPrestartDenied, WorkerError]);\n\nconst cancelFailure = Schema.Union([WorkerError, JoinedToHost]);\n\ntype ToolSchemas<\n Name extends string,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n> = {\n start: {\n parameters: Parameters;\n success: ReturnType<typeof Started<Name>>;\n failure: ReturnType<typeof startFailure<Failure>>;\n };\n followUp: {\n parameters: ReturnType<typeof FollowUpParameters<Name, Parameters>>;\n success: typeof Receipt;\n failure: ReturnType<typeof preparationFailure<Failure>>;\n };\n inspect: {\n parameters: ReturnType<typeof ReceiptParameters<Name>>;\n success: ReturnType<typeof WorkerObservation<Success>>;\n failure: ReturnType<typeof preparationFailure<Failure>>;\n };\n summary: {\n parameters: ReturnType<typeof WorkerParameters<Name>>;\n success: ReturnType<typeof Summary<Name>>;\n failure: typeof WorkerError;\n };\n list: {\n parameters: typeof ListParameters;\n success: ReturnType<typeof Page<Name>>;\n failure: typeof WorkerError;\n };\n cancel: {\n parameters: ReturnType<typeof ReceiptParameters<Name>>;\n success: typeof Schema.Void;\n failure: typeof cancelFailure;\n };\n};\n\ntype BackgroundToolMap<\n Name extends string,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n> = {\n start: Tool.Tool<\n `${Name}_start`,\n ToolSchemas<Name, Parameters, Success, Failure>[\"start\"] & { readonly failureMode: \"error\" },\n SubagentHost | Crypto.Crypto\n >;\n followUp: Tool.Tool<\n `${Name}_follow_up`,\n ToolSchemas<Name, Parameters, Success, Failure>[\"followUp\"] & { readonly failureMode: \"error\" },\n SubagentHost | Crypto.Crypto\n >;\n inspect: Tool.Tool<\n `${Name}_inspect`,\n ToolSchemas<Name, Parameters, Success, Failure>[\"inspect\"] & { readonly failureMode: \"error\" },\n SubagentHost\n >;\n summary: Tool.Tool<\n `${Name}_summary`,\n ToolSchemas<Name, Parameters, Success, Failure>[\"summary\"] & { readonly failureMode: \"error\" },\n SubagentHost\n >;\n list: Tool.Tool<\n `${Name}_list`,\n ToolSchemas<Name, Parameters, Success, Failure>[\"list\"] & { readonly failureMode: \"error\" },\n SubagentHost\n >;\n cancel: Tool.Tool<\n `${Name}_cancel`,\n ToolSchemas<Name, Parameters, Success, Failure>[\"cancel\"] & { readonly failureMode: \"error\" },\n SubagentHost\n >;\n};\n\n/**\n * Native Tool names and schemas expose statically guaranteed selections. The handler Layer also\n * requires services for operations whose conditional flags may enable them at runtime.\n */\nexport type BackgroundTools<\n Name extends string,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Selected extends BackgroundOptions,\n> = {\n readonly [\n Op in Operation as Selected[Op] extends true ? `${Name}_${Suffix[Op]}` : never\n ]: BackgroundToolMap<Name, Parameters, Success, Failure>[Op];\n};\n\nconst modelKey = Effect.fn(\"Subagent.workerToolKey\")(function* (operation: \"start\" | \"followUp\") {\n const service = yield* host;\n const caller = yield* service.context;\n\n if (caller.source._tag !== \"tool\")\n return yield* WorkerError.make({ operation, reason: \"denied\" });\n const source = caller.source;\n const crypto = yield* Crypto.Crypto;\n\n const bytes = utf8Bytes(\n JSON.stringify([\n \"worker-tool-v1\",\n operation,\n source.agentId,\n source.threadId,\n source.runId,\n source.toolCallId,\n ]),\n );\n\n const digest = yield* crypto\n .digest(\"SHA-256\", bytes)\n .pipe(Effect.mapError(() => WorkerError.make({ operation, reason: \"unavailable\" })));\n\n return yield* Schema.decodeEffect(IdempotencyKey)(`worker:${Encoding.encodeHex(digest)}`).pipe(\n Effect.mapError(() => WorkerError.make({ operation, reason: \"unavailable\" })),\n );\n});\n\n// Construction-local service keys distinguish projections for co-registered parent versions.\n// These keys are never persisted; worker/run identity and registration digests remain canonical.\nlet reportingServiceId = 0;\n\n/**\n * Derive optional native AI Tools and their handler Layer from one immutable declaration.\n * Projection services are captured by the Layer; the host and stable-key Crypto service remain\n * invocation dependencies. The attached `.tool` and its suspension behavior are unchanged.\n */\nexport const background = <\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n const Selected extends BackgroundOptions,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n selected: Selected,\n) => {\n const report =\n selected.reportToParent === true ? automaticReporting(declaration) : selected.reportToParent;\n\n if (\n report !== undefined &&\n (report.delegationId !== declaration.delegationId || report.target !== declaration.target)\n )\n throw new TypeError(\"Background reporting must use the same subagent declaration and target\");\n\n const reportService = Context.Service<WorkerReporting<WorkerReportPreparationFailure>>(\n `@effect-agent/capabilities/BackgroundReport/${declaration.name}/${reportingServiceId++}`,\n );\n\n const descriptor: WorkerReporting<WorkerReportPreparationFailure> | undefined =\n report === undefined\n ? undefined\n : {\n ...report,\n prepare: (value) =>\n Effect.flatMap(Effect.serviceOption(reportService), (service) =>\n Option.isSome(service)\n ? service.value.prepare(value)\n : WorkerReportPreparationFailure.make({ stage: \"preparation\" }),\n ),\n };\n\n const ops = operations(declaration);\n const failure = preparationFailure(declaration.failure);\n const receiptParameters = ReceiptParameters(declaration);\n\n const startTool = Tool.make(`${declaration.name}_start` as const, {\n description: `Start ${declaration.name} in the background and return its worker identity and Receipt.`,\n parameters: declaration.parameters,\n success: Started(declaration),\n failure: startFailure(declaration.failure),\n })\n .annotate(WorkerOperationTool, true)\n .annotate(BackgroundSpawnTool, true)\n .addDependency(SubagentHost)\n .addDependency(Crypto.Crypto);\n\n const followUpTool = Tool.make(`${declaration.name}_follow_up` as const, {\n description: `Send typed follow-up input to an existing ${declaration.name} worker.`,\n parameters: FollowUpParameters(declaration, declaration.parameters),\n success: Receipt,\n failure,\n })\n .annotate(WorkerOperationTool, true)\n .addDependency(SubagentHost)\n .addDependency(Crypto.Crypto);\n\n const inspectTool = Tool.make(`${declaration.name}_inspect` as const, {\n description: `Inspect one exact ${declaration.name} Receipt without waiting.`,\n parameters: receiptParameters,\n success: WorkerObservation(declaration.success),\n failure,\n })\n .annotate(WorkerOperationTool, true)\n .addDependency(SubagentHost);\n\n const summaryTool = Tool.make(`${declaration.name}_summary` as const, {\n description: `Inspect ${declaration.name}'s continuing worker state and latest accepted input.`,\n parameters: WorkerParameters(declaration),\n success: Summary(declaration),\n failure: WorkerError,\n })\n .annotate(WorkerOperationTool, true)\n .addDependency(SubagentHost);\n\n const listTool = Tool.make(`${declaration.name}_list` as const, {\n description: `List visible ${declaration.name} workers.`,\n parameters: ListParameters,\n success: Page(declaration),\n failure: WorkerError,\n })\n .annotate(WorkerOperationTool, true)\n .addDependency(SubagentHost);\n\n const cancelTool = Tool.make(`${declaration.name}_cancel` as const, {\n description: `Request cancellation of one exact ${declaration.name} Receipt.`,\n parameters: receiptParameters,\n success: Schema.Void,\n failure: cancelFailure,\n })\n .annotate(WorkerOperationTool, true)\n .addDependency(SubagentHost);\n\n const available = {\n start: startTool,\n followUp: followUpTool,\n inspect: inspectTool,\n summary: summaryTool,\n list: listTool,\n cancel: cancelTool,\n };\n\n const chosen = Object.entries(available)\n .filter(([operation]) => selected[operation as Operation] === true)\n .map(([, tool]) => tool.annotate(BackgroundReporting, descriptor));\n\n type Tools = BackgroundTools<Name, Parameters, Success, Failure, Selected>;\n // The mapped keys depend on literal selection flags; the runtime filter applies exactly those flags.\n const toolkit = Toolkit.make(...chosen) as unknown as Toolkit.Toolkit<Tools>;\n\n type PrepareServices = Prepare | Parameters[\"EncodingServices\"] | Input[\"EncodingServices\"];\n type ProjectServices =\n | Project\n | Parameters[\"DecodingServices\"]\n | Output[\"DecodingServices\"]\n | Success[\"EncodingServices\"];\n type ReportServices<Report> = Report extends true\n ? Exclude<ProjectServices, Scope.Scope>\n : Report extends WorkerReporting<infer _E, infer R>\n ? Exclude<R, Scope.Scope>\n : never;\n type Services = PrepareServices | ProjectServices;\n type SelectionServices<Flag, Requirements> = Flag extends true ? Requirements : never;\n\n const build = Effect.gen(function* () {\n const captured = yield* Effect.context<Services>();\n\n const handlers = {\n [startTool.name]: (parameters: Parameters[\"Type\"]) =>\n Effect.gen(function* () {\n const service = yield* host;\n const idempotencyKey = yield* modelKey(\"start\");\n\n return yield* ops\n .start(parameters, {\n idempotencyKey,\n ...(selected.budgetScope === undefined ? {} : { budgetScope: selected.budgetScope }),\n })\n .pipe(Effect.provideService(SubagentHost, service), Effect.provide(captured));\n }),\n [followUpTool.name]: (parameters: {\n readonly worker: Worker<Name>;\n readonly parameters: Parameters[\"Type\"];\n }) =>\n Effect.gen(function* () {\n const service = yield* host;\n const idempotencyKey = yield* modelKey(\"followUp\");\n\n return yield* ops\n .followUp(parameters.worker, parameters.parameters, { idempotencyKey })\n .pipe(Effect.provideService(SubagentHost, service), Effect.provide(captured));\n }),\n [inspectTool.name]: (parameters: {\n readonly worker: Worker<Name>;\n readonly receipt: Receipt;\n }) =>\n Effect.gen(function* () {\n const service = yield* host;\n\n return yield* ops\n .observe(\"inspect\", parameters.worker, parameters.receipt)\n .pipe(Effect.provideService(SubagentHost, service), Effect.provide(captured));\n }),\n [listTool.name]: (parameters: typeof ListParameters.Type) => ops.list(parameters),\n [summaryTool.name]: (parameters: { readonly worker: Worker<Name> }) =>\n summary(declaration, parameters.worker),\n [cancelTool.name]: (parameters: {\n readonly worker: Worker<Name>;\n readonly receipt: Receipt;\n }) => ops.cancel(parameters.worker, parameters.receipt),\n };\n\n // Each handler above is paired with its native schema; computed generic names need this bridge.\n return handlers as unknown as Toolkit.HandlersFrom<Tools>;\n });\n\n type SelectedServices =\n | SelectionServices<Selected[\"start\"], PrepareServices>\n | SelectionServices<Selected[\"followUp\"], PrepareServices>\n | SelectionServices<Selected[\"inspect\"], ProjectServices>\n | ReportServices<Selected[\"reportToParent\"]>;\n\n // Unselected handlers are never installed. Only selected operations consume projection services.\n const reportingLayer =\n report === undefined\n ? Layer.empty\n : Layer.effect(\n reportService,\n Effect.map(\n Effect.context<Effect.Services<ReturnType<typeof report.prepare>>>(),\n (context): WorkerReporting<WorkerReportPreparationFailure> => ({\n ...report,\n prepare: (value) =>\n Effect.scoped(Effect.suspend(() => report.prepare(value))).pipe(\n Effect.provide(context),\n Effect.mapError((error) =>\n Schema.is(WorkerReportPreparationFailure)(error)\n ? error\n : WorkerReportPreparationFailure.make({ stage: \"preparation\" }),\n ),\n ),\n }),\n ),\n );\n\n const layer = Layer.merge(toolkit.toLayer(build), reportingLayer) as Layer.Layer<\n Tool.HandlersFor<Tools>,\n never,\n SelectedServices\n >;\n\n return Object.freeze({ tools: toolkit.tools, toolkit, layer });\n};\n","import type { Layer } from \"effect\";\nimport { Cause, Clock, Duration, Effect, Exit, Option, Ref, Schema, Scope } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n type Definition,\n type InputPromptSource,\n type InstructionSource,\n type RunDispositionDeclaration,\n} from \"../core/Agent.ts\";\nimport type { AgentPolicy } from \"../core/AgentPolicy.ts\";\nimport { type AgentId, DelegationId, ToolCallId } from \"../core/Identifiers.ts\";\nimport { IdGenerator } from \"../core/IdGenerator.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport type { SubagentDelegationCaps } from \"../core/SubagentContract.ts\";\nimport {\n DelegationTool,\n narrowSubagentGrant,\n SubagentBudgetReservation,\n SubagentGrant,\n SubagentReservationAmounts,\n} from \"../core/SubagentContract.ts\";\nimport { type RunTotals, RunUsageReport, unknownRunTotals } from \"../core/Usage.ts\";\nimport {\n type AgentRuntimeFailure,\n type AgentRuntimeRequirements,\n AgentSpawner,\n type AgentSpawnerParent,\n type AgentSpawnerService,\n type RuntimeBinding,\n type SpawnRunOptions,\n SubagentDurability,\n type SubagentDurabilityDurable,\n SubagentDurabilityError,\n ToolCallWaiting,\n} from \"../engine/AgentRuntime.ts\";\nimport {\n RunEventSink,\n type SubagentEventBasePayload,\n type SubagentEventPayload,\n} from \"../engine/RunEventSink.ts\";\nimport {\n type RunContextPreparation,\n type RunBudgetHook,\n type RunSubagentChildIdentity,\n type RunSubagentDigests,\n type RunUsageDelta,\n} from \"../engine/RunOptions.ts\";\nimport { type ThreadHistory } from \"../engine/ThreadHistory.ts\";\nimport type {\n SubagentPolicy,\n SubagentExecutionFailureClassification,\n} from \"./internal/subagent-contract.ts\";\nimport {\n SubagentPrestartDenied,\n SubagentProjectionFailure,\n SubagentExecutionFailure,\n maxErrorTagLength,\n} from \"./internal/subagent-contract.ts\";\nimport {\n resolveSubagentPolicy,\n resolveToolCallAllowance,\n residualSubagentCaps,\n} from \"./internal/subagent-policy.ts\";\nimport {\n type BudgetReservationId,\n makeBudgetReservationId,\n SubagentBudgetExhausted,\n SubagentObservedUsage,\n SubagentReservationRequest,\n SubagentReservations,\n} from \"./SubagentReservations.ts\";\n\nexport { WorkerCompletion } from \"../core/Worker.ts\";\n\nexport { SubagentGrant } from \"../core/SubagentContract.ts\";\n\nexport {\n SubagentPolicy,\n type SubagentPolicyInput,\n SubagentPrestartDenied,\n SubagentProjectionFailure,\n SubagentExecutionFailureClassification,\n SubagentExecutionFailure,\n delegationCapsFromPolicy,\n delegationAllocationFromPolicy,\n} from \"./internal/subagent-contract.ts\";\n\nimport {\n background as backgroundDeclaration,\n type BackgroundOptions,\n type Declaration,\n} from \"./internal/subagent-background.ts\";\n\nconst decodeDelegationId = Schema.decodeSync(DelegationId);\n\n/**\n * Bounded parent metadata visible to `prepareInput`.\n * It never contains the parent transcript, prompt, or a root runtime Context.\n */\nexport type SubagentPrepareContext = {\n readonly delegationId: DelegationId;\n} & (\n | {\n readonly source: \"tool\";\n readonly toolCallId: ToolCallId;\n readonly parent: AgentSpawnerParent;\n }\n | {\n readonly source: \"programmatic\";\n readonly parent: Pick<AgentSpawnerParent, \"agentId\" | \"threadId\">;\n }\n);\n\n/**\n * Bounded framework context handed to `projectResult` (SUB-034).\n * `budgetExhausted` is true exactly when the child settled through the\n * final-answer exhaustion resolution (RUN-018) — on the ephemeral path from\n * the child result's `finishReason`, on the durable path from the child\n * Settlement's honest marker — so the projection can surface a\n * budget-truncated partial to the orchestrator.\n */\nexport interface SubagentResultContext {\n readonly budgetExhausted: boolean;\n /** Own and disjoint attached-descendant usage; absent only for legacy/custom hosts. */\n readonly usage?: RunTotals;\n readonly delegatedUsage?: RunTotals;\n}\n\n/** Default delegation result, preserving partial-output information. */\nexport const SubagentResult = <Output extends Schema.Top>(output: Output) =>\n Schema.Struct({ output, budgetExhausted: Schema.Boolean });\n\nexport type SubagentResult<Output extends Schema.Top> = ReturnType<typeof SubagentResult<Output>>;\n\n/**\n * The delegation Tool failure Schema: the author's declared failure plus the\n * framework's preflight/budget/projection/durable-execution failure family.\n * With the default `failureMode: \"error\"`, exactly\n * this union (plus Effect AI's own error) can enter the parent handler `E`.\n *\n * The engine-owned `ToolCallWaiting` suspension signal and the typed\n * `SubagentDurabilityError` are members so the durable branch's waiting\n * signal and coordinator-seam failures travel typed through\n * `failureMode: \"error\"` (S2 plan §2); neither ever reaches an ephemeral\n * caller, and a waiting signal is not a Tool failure — the batch executor\n * keeps the raising call open and suspends the Run.\n */\nexport type SubagentToolFailure<Failure extends Schema.Top> = Schema.Union<\n readonly [\n Failure,\n typeof SubagentPrestartDenied,\n typeof SubagentBudgetExhausted,\n typeof SubagentProjectionFailure,\n typeof SubagentExecutionFailure,\n typeof ToolCallWaiting,\n typeof SubagentDurabilityError,\n ]\n>;\n\n/**\n * Resolution for expected delegation failures (SUB-033, ADR-0019 S2).\n * `\"error\"` (the default) keeps today's semantics: every expected failure\n * travels the Effect error channel and fails the parent Tool batch (D-008).\n * `\"return\"` contains them: the declared child failure and the framework\n * failure family become model-visible result data instead of parent-fatal\n * errors, so one dead child cannot detonate the whole parent Run.\n *\n * Effect AI's native `failureMode: \"return\"` is deliberately NOT used: its\n * `Stream.catch` converts every handler failure into a result, which would\n * encode the engine-owned `ToolCallWaiting` suspension signal as data and\n * silently orphan a durable child. Containment therefore lives in the\n * delegation handler — the underlying Tool keeps Effect AI\n * `failureMode: \"error\"`, the Tool success Schema widens to a union of the\n * declared success and the contained failure family, and exactly\n * `ToolCallWaiting` and `SubagentDurabilityError` stay in the error channel,\n * preserving durable suspension semantics by construction.\n */\nexport type SubagentFailureMode = \"error\" | \"return\";\n\n/**\n * The failure family that becomes model-visible result data under\n * `failureMode: \"return\"`: the author-declared failure plus every expected\n * framework delegation failure. The engine-signal members are excluded by\n * construction.\n */\nexport type SubagentContainedFailure<Failure extends Schema.Top> = Schema.Union<\n readonly [\n Failure,\n typeof SubagentPrestartDenied,\n typeof SubagentBudgetExhausted,\n typeof SubagentProjectionFailure,\n typeof SubagentExecutionFailure,\n ]\n>;\n\n/**\n * The only failures a `\"return\"`-mode delegation Tool can raise: the\n * engine-owned waiting signal (consumed by the batch executor, never a Tool\n * failure) and the durable coordinator-seam error. Neither ever reaches an\n * ephemeral caller.\n */\nexport type SubagentReturnModeFailure = Schema.Union<\n readonly [typeof ToolCallWaiting, typeof SubagentDurabilityError]\n>;\n\n/**\n * The native Effect AI Tool created by `Subagent.make` (SUB-001, SUB-003).\n * Its per-call dependencies are exactly the engine-provided `AgentSpawner`,\n * `RunEventSink`, and `SubagentDurability`; every child\n * requirement except the inherited Thread history policy is a construction requirement\n * of `Subagent.layer`. The engine excludes its own per-batch services from the runtime's\n * public requirements. Runtime IDs use the overridable default reference.\n */\nexport type SubagentTool<\n Name extends string,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Mode extends SubagentFailureMode = \"error\",\n> = Mode extends \"return\"\n ? Tool.Tool<\n Name,\n {\n readonly parameters: Parameters;\n readonly success: Schema.Union<readonly [Success, SubagentContainedFailure<Failure>]>;\n readonly failure: SubagentReturnModeFailure;\n readonly failureMode: \"error\";\n },\n AgentSpawner | RunEventSink | SubagentDurability\n >\n : Tool.Tool<\n Name,\n {\n readonly parameters: Parameters;\n readonly success: Success;\n readonly failure: SubagentToolFailure<Failure>;\n readonly failureMode: \"error\";\n },\n AgentSpawner | RunEventSink | SubagentDurability\n >;\n\n/** Singleton Tool record provided by one `Subagent.layer`. */\nexport type SubagentTools<\n Name extends string,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Mode extends SubagentFailureMode = \"error\",\n> = {\n readonly [Key in Name]: SubagentTool<Name, Parameters, Success, Failure, Mode>;\n};\n\n/** Explicit options accepted by `Subagent.make`. */\nexport interface SubagentDefineOptions<\n TargetInput extends Schema.Top,\n TargetOutput extends Schema.Top,\n TargetInstructions,\n TargetTools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n PrepareRequirements = never,\n ProjectRequirements = never,\n Mode extends SubagentFailureMode = \"error\",\n> {\n /**\n * Expected-failure resolution (SUB-033): `\"error\"` (default) fails the\n * parent Tool batch; `\"return\"` contains the declared failure and the\n * framework failure family as model-visible result data while\n * `ToolCallWaiting`/`SubagentDurabilityError` stay in the error channel.\n */\n readonly failureMode?: Mode;\n /** Model-visible description of the delegated capability. */\n readonly description?: string | undefined;\n /** The model-agnostic child Agent Definition this delegation targets (SUB-002). */\n readonly target: Definition<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n Toolkit.Toolkit<TargetTools>,\n RunDispositionDeclaration<TargetOutput[\"Type\"], Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n >;\n /** Schema for the model-decoded delegation parameters. */\n readonly parameters: Parameters;\n /** Schema for the bounded parent Tool result. */\n readonly success: Success;\n /** Schema for the author-declared delegation failure data. */\n readonly failure: Failure;\n /**\n * Effectful, typed projection from decoded parameters and bounded parent\n * metadata to the child Agent input. It never\n * receives the parent transcript or a root Context; its expected failures\n * are already the declared Tool failure.\n */\n readonly prepareInput: (\n parameters: Parameters[\"Type\"],\n context: SubagentPrepareContext,\n ) => Effect.Effect<\n TargetInput[\"Type\"],\n Failure[\"Type\"] | SubagentProjectionFailure,\n PrepareRequirements\n >;\n /**\n * Bounded result projection from the Schema-decoded child output, result\n * context, and original Schema-decoded Tool parameters to the declared Tool\n * success value. This is the explicit\n * declassification boundary for child output: the parameters let it bind\n * echoed identity and scope to the exact request without prompt parsing.\n * The context carries the\n * framework's honest exhaustion marker (SUB-034): when `budgetExhausted` is\n * true the child settled through the final-answer resolution (RUN-018) and\n * its output is a budget-truncated partial — surface it in the declared\n * success Schema so the orchestrator can decide to re-delegate with a\n * raised `toolCallAllowance`.\n */\n readonly projectResult: (\n output: TargetOutput[\"Type\"],\n context: SubagentResultContext,\n parameters: Parameters[\"Type\"],\n ) => Effect.Effect<\n Success[\"Type\"],\n Failure[\"Type\"] | SubagentProjectionFailure,\n ProjectRequirements\n >;\n /**\n * Per-invocation child Tool Call allowance (SUB-034): a tightening-only\n * bound below the child Definition's own `maxToolCalls`, additionally\n * clamped to this delegation's `SubagentPolicy.maxToolCalls` (the\n * per-invocation reservation slice). `fromParameters` lets the orchestrator\n * model grant a larger allowance through an author-owned parameter field —\n * the budget-extension flow is a fresh re-delegation with a raised\n * allowance, never a mid-flight top-up. Durable establishment records the\n * effective allowance before child admission and restores it on every Attempt.\n */\n readonly toolCallAllowance?:\n | {\n /** Applied when `fromParameters` is absent or yields nothing. */\n readonly default: number;\n /** Extract the model-granted allowance from the decoded parameters. */\n readonly fromParameters?: (parameters: Parameters[\"Type\"]) => number | undefined;\n }\n | undefined;\n /** Per-child ceilings. When omitted, reserve from the parent policy's shared delegation pool. */\n readonly policy?: SubagentPolicy | undefined;\n /**\n * Authority ceiling for the child. Defaults to\n * exactly the target's declared Tool names at depth ceiling one. The engine\n * exposes only permitted Tools; nested launches also require depth and lifetime authority.\n */\n readonly grant?: SubagentGrant | undefined;\n /**\n * Native Effect AI approval metadata for establishment only (SUB-026):\n * parent approval never authorizes child actions, siblings, or retries.\n */\n readonly needsApproval?: Tool.NeedsApproval<Parameters> | undefined;\n}\n\n/**\n * An immutable Subagent capability: one target Agent Definition exposed to\n * a parent as one Effect AI Tool with explicit projections, policy, and\n * authority ceiling. It owns no acquired resources and\n * is not executable until `Subagent.layer` supplies the child's model Layer.\n */\nexport interface SubagentDelegation<\n Name extends string,\n TargetInput extends Schema.Top,\n TargetOutput extends Schema.Top,\n TargetInstructions,\n TargetTools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n PrepareRequirements = never,\n ProjectRequirements = never,\n Mode extends SubagentFailureMode = \"error\",\n> extends SubagentDefineOptions<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Parameters,\n Success,\n Failure,\n PrepareRequirements,\n ProjectRequirements,\n Mode\n> {\n readonly name: Name;\n /** Stable delegation identity; S1 derives it from the unique Tool name. */\n readonly delegationId: DelegationId;\n readonly grant: SubagentGrant;\n /** The resolved expected-failure resolution (SUB-033); never absent after `make`. */\n readonly failureMode: Mode;\n /**\n * The canonical contained-failure family for this delegation (SUB-033):\n * the declared failure plus the framework members. Consumers that classify\n * returned failure data (for example a coverage gate) MUST decode through\n * this value rather than reconstructing the union, so a framework change\n * to the contained family can never diverge from their decoder.\n */\n readonly containedFailure: SubagentContainedFailure<Failure>;\n /** The real Effect AI Tool to include in the parent Toolkit (SUB-001). */\n readonly tool: SubagentTool<Name, Parameters, Success, Failure, Mode>;\n}\n\n/**\n * Declare one attached delegation as a pure value.\n *\n * The returned `.tool` is a native Effect AI Tool whose handler dependencies\n * are exactly the engine-owned `AgentSpawner`, `RunEventSink`, and\n * `SubagentDurability` (SUB-003); runtime IDs have an overridable default.\n * The concrete child Binding arrives only through\n * `Subagent.layer`. Throws on an invalid delegation name. Nested declarations remain inert unless the\n * effective inherited grant and reserved subtree budget permit their lifetime and depth.\n */\nconst makeExplicit = <\n const Name extends string,\n TargetInput extends Schema.Top,\n TargetOutput extends Schema.Top,\n TargetInstructions,\n TargetTools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n PrepareRequirements = never,\n ProjectRequirements = never,\n Mode extends SubagentFailureMode = \"error\",\n>(\n name: Name,\n options: SubagentDefineOptions<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Parameters,\n Success,\n Failure,\n PrepareRequirements,\n ProjectRequirements,\n Mode\n >,\n): SubagentDelegation<\n Name,\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Parameters,\n Success,\n Failure,\n PrepareRequirements,\n ProjectRequirements,\n Mode\n> => {\n const delegationId = decodeDelegationId(name);\n\n const grant =\n options.grant ??\n SubagentGrant.make({\n allowedToolNames: Object.keys(options.target.toolkit.tools),\n maxDepth: 1,\n });\n\n // `Mode` defaults to `\"error\"` exactly when `failureMode` is absent, so the\n // resolved literal always inhabits `Mode`; the assertion bridges only that\n // inference gap and crosses no schema boundary.\n const failureMode = (options.failureMode ?? \"error\") as Mode;\n\n const containedFailure = Schema.Union([\n options.failure,\n SubagentPrestartDenied,\n SubagentBudgetExhausted,\n SubagentProjectionFailure,\n SubagentExecutionFailure,\n ]);\n\n const returnModeTool = Tool.make(name, {\n description: options.description,\n parameters: options.parameters,\n // Containment (SUB-033): the contained failure family is model-visible\n // RESULT data, so it lives in the success union; only the engine-signal\n // members remain raisable. The underlying Effect AI failureMode stays\n // \"error\" so the waiting signal is never encoded as a result.\n success: Schema.Union([options.success, containedFailure]),\n failure: Schema.Union([ToolCallWaiting, SubagentDurabilityError]),\n needsApproval: options.needsApproval,\n });\n\n const errorModeTool = Tool.make(name, {\n description: options.description,\n parameters: options.parameters,\n success: options.success,\n failure: Schema.Union([\n options.failure,\n SubagentPrestartDenied,\n SubagentBudgetExhausted,\n SubagentProjectionFailure,\n SubagentExecutionFailure,\n ToolCallWaiting,\n SubagentDurabilityError,\n ]),\n needsApproval: options.needsApproval,\n });\n\n // Each branch is exactly `SubagentTool<..., Mode>` at its concrete `Mode`;\n // TypeScript cannot relate a runtime branch to the conditional generic, so\n // this assertion bridges only that limitation and crosses no schema\n // boundary (the schemas above are constructed per mode, never reinterpreted).\n const tool = (failureMode === \"return\" ? returnModeTool : errorModeTool)\n .annotate(DelegationTool, true)\n .addDependency(AgentSpawner)\n .addDependency(RunEventSink)\n .addDependency(SubagentDurability)\n .addDependency(IdGenerator) as unknown as SubagentTool<\n Name,\n Parameters,\n Success,\n Failure,\n Mode\n >;\n\n return Object.freeze({\n ...options,\n name,\n delegationId,\n grant,\n failureMode,\n containedFailure,\n tool,\n });\n};\n\n/** Pure Subagent authoring surface. */\n/** Optional authoring fields; schemas default to the child's input and result envelope. */\nexport type SubagentDeclarationOptions<\n Input extends Schema.Top,\n Output extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n Mode extends SubagentFailureMode,\n> = Omit<\n SubagentDefineOptions<\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n Mode\n >,\n \"parameters\" | \"success\" | \"failure\" | \"prepareInput\" | \"projectResult\"\n> & {\n readonly parameters?: Parameters;\n readonly success?: Success;\n readonly failure?: Failure;\n readonly prepareInput?: SubagentDefineOptions<\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n Mode\n >[\"prepareInput\"];\n readonly projectResult?: SubagentDefineOptions<\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n Mode\n >[\"projectResult\"];\n};\n\n/**\n * Expose one child Agent as an attached Effect AI Tool. The nonempty application\n * name is preserved as both Tool name and delegation identity; no prefix is required.\n * Parameters and result projections default to the child's input and result envelope.\n * Throws when the name is empty. Nested Tool visibility follows the effective inherited grant.\n */\nfunction make<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top = Input,\n Success extends Schema.Top = SubagentResult<Output>,\n Failure extends Schema.Top = typeof Schema.Never,\n Prepare = never,\n Project = never,\n Target extends Definition<\n Input,\n Output,\n Instructions,\n Toolkit.Toolkit<Tools>,\n RunDispositionDeclaration<Output[\"Type\"], Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n > = Definition<\n Input,\n Output,\n Instructions,\n Toolkit.Toolkit<Tools>,\n RunDispositionDeclaration<Output[\"Type\"], Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n >,\n>(\n name: Name,\n options: SubagentDeclarationOptions<\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n \"return\"\n > & { readonly failureMode: \"return\"; readonly target: Target },\n): SubagentDelegation<\n Name,\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n \"return\"\n> & { readonly target: Target };\nfunction make<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top = Input,\n Success extends Schema.Top = SubagentResult<Output>,\n Failure extends Schema.Top = typeof Schema.Never,\n Prepare = never,\n Project = never,\n Target extends Definition<\n Input,\n Output,\n Instructions,\n Toolkit.Toolkit<Tools>,\n RunDispositionDeclaration<Output[\"Type\"], Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n > = Definition<\n Input,\n Output,\n Instructions,\n Toolkit.Toolkit<Tools>,\n RunDispositionDeclaration<Output[\"Type\"], Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n >,\n>(\n name: Name,\n options: SubagentDeclarationOptions<\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n \"error\"\n > & { readonly target: Target },\n): SubagentDelegation<\n Name,\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project\n> & { readonly target: Target };\nfunction make<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n>(\n name: Name,\n options: SubagentDeclarationOptions<\n Input,\n Output,\n Instructions,\n Tools,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n SubagentFailureMode\n >,\n): unknown {\n const success: Schema.Codec<\n Success[\"Type\"] | SubagentResult<Output>[\"Type\"],\n Success[\"Encoded\"] | SubagentResult<Output>[\"Encoded\"],\n Success[\"DecodingServices\"] | Output[\"DecodingServices\"],\n Success[\"EncodingServices\"] | Output[\"EncodingServices\"]\n > = options.success ?? SubagentResult(options.target.output);\n\n const parameters = options.parameters ?? options.target.input;\n\n const failure: Schema.Codec<\n Failure[\"Type\"],\n Failure[\"Encoded\"],\n Failure[\"DecodingServices\"],\n Failure[\"EncodingServices\"]\n > = options.failure ?? Schema.Never;\n\n const inputValue = Schema.decodeUnknownEffect(Schema.toType(options.target.input));\n const resultValue = Schema.decodeUnknownEffect(Schema.toType(success));\n const needsApproval = options.needsApproval;\n const prepareInput = options.prepareInput;\n const projectResult = options.projectResult;\n\n const projectionFailure = (stage: \"input\" | \"result\") =>\n SubagentProjectionFailure.make({\n delegationId: decodeDelegationId(name),\n stage,\n message:\n stage === \"input\"\n ? \"Delegation parameters did not satisfy the child input Schema\"\n : \"Child output did not satisfy the delegation success Schema\",\n });\n\n const resolved = {\n ...options,\n needsApproval:\n typeof needsApproval === \"function\"\n ? (input: Parameters[\"Type\"], context: Tool.NeedsApprovalContext) =>\n needsApproval(input, context)\n : needsApproval,\n description: options.description ?? options.target.description,\n parameters,\n success,\n failure,\n prepareInput: (input: Parameters[\"Type\"], context: SubagentPrepareContext) =>\n prepareInput === undefined\n ? inputValue(input).pipe(Effect.mapError(() => projectionFailure(\"input\")))\n : prepareInput(input, context),\n projectResult: (\n output: Output[\"Type\"],\n context: SubagentResultContext,\n input: Parameters[\"Type\"],\n ) =>\n projectResult === undefined\n ? resultValue({ output, budgetExhausted: context.budgetExhausted }).pipe(\n Effect.mapError(() => projectionFailure(\"result\")),\n )\n : projectResult(output, context, input),\n };\n\n return options.failureMode === \"return\"\n ? makeExplicit<\n Name,\n Input,\n Output,\n Instructions,\n Tools,\n Input | Parameters,\n typeof success,\n typeof failure,\n Prepare,\n Project,\n \"return\"\n >(name, { ...resolved, failureMode: \"return\" })\n : makeExplicit<\n Name,\n Input,\n Output,\n Instructions,\n Tools,\n Input | Parameters,\n typeof success,\n typeof failure,\n Prepare,\n Project\n >(name, { ...resolved, failureMode: \"error\" });\n}\n\nexport { make };\n\n/** @deprecated Use `Subagent.make`. */\nexport const define: typeof make = make;\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\n/**\n * Every expected child Run failure the delegation's total mapping must cover:\n * the child's inferred Agent failures plus\n * the interpreter's policy, protocol, and approval failures. Interruption and\n * defects are not members; they retain their distinct semantics.\n */\nexport type SubagentChildRunFailure<\n TargetInput extends Schema.Top,\n TargetOutput extends Schema.Top,\n TargetInstructions,\n TargetTools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError = InstructionErrorOf<TargetInstructions, TargetInput[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<TargetInstructions, TargetInput[\"Type\"]>,\n InputPromptValue extends InputPromptSource<TargetInput[\"Type\"], unknown, unknown> | undefined =\n undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n RunDispositionValue extends\n | RunDispositionDeclaration<TargetOutput[\"Type\"], Schema.Top>\n | undefined = undefined,\n> = AgentRuntimeFailure<\n RuntimeBinding<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n never,\n InstructionError\n>;\n\n/**\n * Construction requirements of one `Subagent.layer`: the child\n * Binding's full runtime requirements (Model Layer requirements, child Tool\n * handlers and their services, Schema services), both projection\n * requirements, and the parent-owned reservation service. Nothing here leaks\n * into the per-call Tool handler requirements. ThreadHistory and RunContextPreparation belong\n * to the parent Run's AgentSpawner and are inherited at invocation rather than captured here.\n */\nexport type SubagentLayerRequirements<\n TargetInput extends Schema.Top,\n TargetOutput extends Schema.Top,\n TargetInstructions,\n TargetTools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n PrepareRequirements,\n ProjectRequirements,\n HookRequirements = never,\n InstructionError = InstructionErrorOf<TargetInstructions, TargetInput[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<TargetInstructions, TargetInput[\"Type\"]>,\n InputPromptValue extends InputPromptSource<TargetInput[\"Type\"], unknown, unknown> | undefined =\n undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n RunDispositionValue extends\n | RunDispositionDeclaration<TargetOutput[\"Type\"], Schema.Top>\n | undefined = undefined,\n> =\n | Exclude<\n AgentRuntimeRequirements<\n RuntimeBinding<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\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 | TargetInput[\"EncodingServices\"]\n | PrepareRequirements\n | ProjectRequirements\n | SubagentReservations;\n\n/**\n * Optional construction-fixed digest override for durable delegation.\n * The coordinator normally resolves the exact target Definition through its\n * existing host registration. An override must agree with that registration.\n */\nexport interface SubagentDurableOptions {\n /**\n * Exact digests from the target's host registration. Fixed once at handler\n * Layer construction and checked against that registration at establishment.\n * Recovery uses the canonical request's recorded digests, never current code.\n */\n readonly targetDigests: RunSubagentDigests;\n}\n\n/**\n * The conservative final accounting summary the durable delegation handler\n * attaches to every settlement join. The handler has no live child usage stream at durable join\n * time, so every dimension conservatively consumes its full reservation and\n * releases nothing — unreported usage never creates budget. The coordinator\n * owns the canonical accounting decision on `SubagentJoined` and may replace\n * structural dimensions from canonical child evidence; this value is opaque\n * encoded policy math to the engine and to storage adapters (D8).\n */\nexport class SubagentDurableAccounting extends Schema.Class<SubagentDurableAccounting>(\n \"@effect-agent/capabilities/SubagentDurableAccounting\",\n)({\n /** The per-invocation allocation reserved at establishment. */\n allocation: SubagentReservationAmounts,\n /** Final consumed decision per dimension. */\n consumed: SubagentReservationAmounts,\n /** Amounts returned to the parent: `allocation - consumed` per dimension. */\n released: SubagentReservationAmounts,\n /** How the decision was computed; the handler only ever reports conservatively. */\n basis: Schema.Literals([\"reserved-conservative\"]),\n}) {}\n\n/** Options accepted by `Subagent.layer`. */\nexport interface SubagentRuntimeOptions<\n Failure extends Schema.Top,\n ChildFailure,\n HookRequirements = never,\n> {\n /**\n * Optional exact digest override. Without it, the durable coordinator resolves\n * the target Definition from its existing host registrations.\n */\n readonly durable?: SubagentDurableOptions | undefined;\n /**\n * Total mapping from every expected child Run failure to the declared Tool\n * failure (SUB-028). The parameter type is the child Binding's complete\n * expected failure union, so a mapping that covers only part of it is a\n * compile error. Interruption stays interruption and defects stay defects;\n * neither reaches this mapping.\n * When omitted, failures become bounded `SubagentExecutionFailure` values.\n */\n readonly mapChildFailure?: ((failure: ChildFailure) => Failure[\"Type\"]) | undefined;\n /**\n * Override the parent-Run delegation caps registered with\n * `SubagentReservations`. An explicit policy uses `delegationCapsFromPolicy(policy)`;\n * an omitted policy uses one pool sized from the parent policy.\n * Supply shared caps explicitly when one parent Run uses several delegation\n * Tools, because re-registering different caps denies start fail-closed.\n */\n readonly parentCaps?: SubagentDelegationCaps | undefined;\n /**\n * Seed child Run options (approval, context, input hooks) so child actions\n * follow their own ordinary approval and policy (SUB-026). Hook failures\n * must be handled inside the hook (`never` in `E`); a supplied budget hook\n * is composed after the reservation's own usage observation.\n */\n readonly child?: SpawnRunOptions<never, HookRequirements> | undefined;\n}\n\nconst maxEventTextLength = 4 * 1024;\n\nconst boundedEventText = (text: string): string =>\n text.length <= maxEventTextLength ? text : `${text.slice(0, maxEventTextLength - 1)}…`;\n\nconst ErrorMessage = Schema.Struct({ message: Schema.String });\nconst ErrorTag = Schema.Struct({ _tag: Schema.NonEmptyString });\n\nconst errorMessageOf = (error: unknown): string =>\n Option.match(Schema.decodeUnknownOption(ErrorMessage)(error), {\n onNone: () => String(error),\n onSome: ({ message }) => message,\n });\n\nconst errorTagOf = (error: unknown): string =>\n Option.match(Schema.decodeUnknownOption(ErrorTag)(error), {\n onNone: () => \"UnknownError\",\n onSome: ({ _tag }) => _tag,\n });\n\nconst boundedErrorTag = (tag: string): string => {\n const nonEmpty = tag.length === 0 ? \"UnknownError\" : tag;\n\n return nonEmpty.length <= maxErrorTagLength ? nonEmpty : nonEmpty.slice(0, maxErrorTagLength);\n};\n\n/**\n * The coordinator's bounded projection of a failed/aborted child Settlement\n * result (S2 plan §1.6, D5): `{errorTag, message}`, never a raw Cause. The\n * fallback tolerates any other bounded shape without ever surfacing the raw\n * value beyond a tag and message.\n */\nconst ChildFailureProjection = Schema.Struct({\n errorTag: Schema.NonEmptyString,\n message: Schema.String,\n});\n\nconst childFailureProjectionOf = (\n encodedResult: unknown,\n): { readonly errorTag: string; readonly message: string } =>\n Option.match(Schema.decodeUnknownOption(ChildFailureProjection)(encodedResult), {\n onNone: () => ({\n errorTag: errorTagOf(encodedResult),\n message: errorMessageOf(encodedResult),\n }),\n onSome: (projection) => projection,\n });\n\nconst zeroReservationAmounts = SubagentReservationAmounts.make({\n turns: 0,\n toolCalls: 0,\n durationMillis: 0,\n inputTokens: 0,\n outputTokens: 0,\n costMicrousd: 0,\n resultBytes: 0,\n});\n\nconst encodeDurableAccounting = Schema.encodeEffect(SubagentDurableAccounting);\nconst encodeProjectionFailure = Schema.encodeEffect(SubagentProjectionFailure);\nconst encodeBudgetFailure = Schema.encodeEffect(SubagentBudgetExhausted);\nconst encodeExecutionFailure = Schema.encodeEffect(SubagentExecutionFailure);\nconst encodeGrant = Schema.encodeEffect(SubagentGrant);\nconst encodeAllocationAmounts = Schema.encodeEffect(SubagentReservationAmounts);\n\nconst toNatural = (value: number): number =>\n Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n\nconst observedUsageFromDelta = (delta: RunUsageDelta): SubagentObservedUsage =>\n SubagentObservedUsage.make({\n turns: delta.modelCalls,\n toolCalls: toNatural(delta.toolCalls),\n inputTokens: toNatural(delta.inputTokens),\n outputTokens: toNatural(delta.outputTokens),\n costMicrousd: toNatural(delta.costMicrousd),\n });\n\n/** A child that never started consumed nothing; observing zeros releases everything. */\nconst neverStartedUsage = SubagentObservedUsage.make({\n turns: 0,\n toolCalls: 0,\n durationMillis: 0,\n inputTokens: 0,\n outputTokens: 0,\n costMicrousd: 0,\n resultBytes: 0,\n});\n\n/**\n * Finalizer-driven settlement: observe honest final usage, then release the\n * unused allocation exactly once. Runs on every handler exit path — success,\n * declared failure, interruption, and defect — through the reservation's\n * `Effect.acquireRelease`; a missing reservation after a successful reserve\n * is a ledger invariant violation and therefore a defect.\n */\nconst settleReservation = (\n reservations: SubagentReservations[\"Service\"],\n reservationId: BudgetReservationId,\n startedAt: Ref.Ref<number | undefined>,\n conservative?: {\n readonly parentRunId: AgentSpawnerParent[\"runId\"];\n readonly allocation: SubagentReservationAmounts;\n },\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const started = yield* Ref.get(startedAt);\n\n if (started === undefined) {\n yield* reservations.observe(reservationId, neverStartedUsage);\n } else {\n const now = yield* Clock.currentTimeMillis;\n\n yield* reservations.observe(\n reservationId,\n SubagentObservedUsage.make({ durationMillis: Math.max(0, Math.floor(now - started)) }),\n );\n }\n if (started !== undefined && conservative !== undefined) {\n const snapshot = yield* reservations.parentSnapshot(conservative.parentRunId);\n const own = snapshot.reservations.find((entry) => entry.reservationId === reservationId);\n\n if (own === undefined)\n return yield* Effect.die(\"Missing subtree reservation during finalization\");\n\n const additional = (key: keyof typeof conservative.allocation) =>\n Math.max(0, conservative.allocation[key] - (own.observedConsumed[key] ?? 0));\n\n yield* reservations.observe(\n reservationId,\n SubagentObservedUsage.make({\n turns: additional(\"turns\"),\n toolCalls: additional(\"toolCalls\"),\n durationMillis: additional(\"durationMillis\"),\n inputTokens: additional(\"inputTokens\"),\n outputTokens: additional(\"outputTokens\"),\n costMicrousd: additional(\"costMicrousd\"),\n resultBytes: additional(\"resultBytes\"),\n }),\n );\n }\n yield* reservations.release(reservationId);\n }).pipe(Effect.orDie);\n\n/**\n * Module-private provenance wrapper (SUB-033 hardening): ONLY the operations\n * that can genuinely produce the engine signals wrap them here, so\n * containment classification never trusts the runtime identity of classes an\n * author could declare in their own failure Schema — a spoofed\n * `ToolCallWaiting` in author data is contained as data, never rethrown as a\n * suspension signal.\n */\nclass GenuineEngineSignal {\n readonly _tag = \"GenuineEngineSignal\";\n constructor(readonly signal: ToolCallWaiting | SubagentDurabilityError) {}\n}\n\nconst wrapEngineSignal = (signal: ToolCallWaiting | SubagentDurabilityError) =>\n new GenuineEngineSignal(signal);\n\ntype SubagentHandler<\n Name extends string,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Mode extends SubagentFailureMode = \"error\",\n> = (\n parameters: Parameters[\"Type\"],\n context: Toolkit.HandlerContext<SubagentTool<Name, Parameters, Success, Failure, Mode>>,\n) => Effect.Effect<\n Mode extends \"return\"\n ? Success[\"Type\"] | SubagentContainedFailure<Failure>[\"Type\"]\n : Success[\"Type\"],\n Mode extends \"return\" ? SubagentReturnModeFailure[\"Type\"] : SubagentToolFailure<Failure>[\"Type\"],\n Tool.HandlerServices<SubagentTool<Name, Parameters, Success, Failure, Mode>>\n>;\n\n/**\n * Build the Toolkit handler Layer for one delegation Tool from a model Layer or\n * an explicit child Agent Binding.\n *\n * Construction requirements carry the child Binding's full runtime needs and\n * both projections; they are captured once via `Effect.context` so the\n * per-call handler requirements stay exactly the Tool's declared engine\n * dependencies. The handler dispatches on the engine-provided per-batch\n * `SubagentDurability` service mode:\n *\n * - **ephemeral** (the explicit engine default when no durable coordinator\n * supplied `RunOptions.subagent`): the S1 path unchanged — preflight, an\n * in-process scoped child Run (SUB-011/012), stable lifecycle events,\n * total-mapped expected child failures, and Scope-finalizer reservation\n * settlement on every exit path.\n * - **durable** (S2): the same fail-closed preflight and input projection,\n * then idempotent establishment through the coordinator (spec §12 steps\n * 2-9) with construction-fixed child Binding digests, encoded grant, and\n * encoded allocation; the engine-owned waiting signal while the attached\n * child is nonterminal; and, on re-entry with a settled child, output\n * decoding, `projectResult`, and ONE atomic settlement join carrying the\n * conservative accounting summary. Failed children join as the bounded\n * `SubagentExecutionFailure`; no in-process child fiber ever starts.\n */\nexport const layer = <\n Name extends string,\n TargetInput extends Schema.Top,\n TargetOutput extends Schema.Top,\n TargetInstructions,\n TargetTools extends Record<string, Tool.Any>,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n PrepareRequirements,\n ProjectRequirements,\n Provider,\n ModelProvides,\n ModelRequires,\n HookRequirements = never,\n Mode extends SubagentFailureMode = \"error\",\n InstructionError = InstructionErrorOf<TargetInstructions, TargetInput[\"Type\"]>,\n InstructionRequirements = InstructionRequirementsOf<TargetInstructions, TargetInput[\"Type\"]>,\n InputPromptValue extends InputPromptSource<TargetInput[\"Type\"], unknown, unknown> | undefined =\n undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n RunDispositionValue extends\n | RunDispositionDeclaration<TargetOutput[\"Type\"], Schema.Top>\n | undefined = undefined,\n>(\n delegation: SubagentDelegation<\n Name,\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Parameters,\n Success,\n Failure,\n PrepareRequirements,\n ProjectRequirements,\n Mode\n > & {\n readonly target: {\n readonly instructions: InstructionSource<\n TargetInput[\"Type\"],\n NoInfer<InstructionError>,\n NoInfer<InstructionRequirements>\n >;\n readonly inputPrompt?: InputPromptValue | undefined;\n readonly updates?: UpdatesSchema | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n };\n },\n modelOrBinding:\n | RuntimeBinding<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >\n | RuntimeBinding<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >[\"model\"],\n options: SubagentRuntimeOptions<\n Failure,\n SubagentChildRunFailure<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n InputPromptValue,\n UpdatesSchema,\n RunDispositionValue\n >,\n HookRequirements\n > = {},\n): Layer.Layer<\n Tool.HandlersFor<SubagentTools<Name, Parameters, Success, Failure, Mode>>,\n never,\n SubagentLayerRequirements<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n PrepareRequirements,\n ProjectRequirements,\n HookRequirements,\n InstructionError,\n InstructionRequirements,\n InputPromptValue,\n UpdatesSchema,\n RunDispositionValue\n >\n> => {\n const childBinding =\n \"definition\" in modelOrBinding\n ? modelOrBinding\n : { definition: delegation.target, model: modelOrBinding };\n\n if (childBinding.definition !== delegation.target) {\n throw new Error(\"Subagent.layer requires the delegation's exact target Definition\");\n }\n\n const resolvePolicy = (spawner: AgentSpawnerService) =>\n resolveSubagentPolicy(\n delegation,\n spawner.policy,\n options.parentCaps,\n spawner.depth === 0 && spawner.budget === undefined ? \"root-attached\" : \"conserved\",\n );\n\n // `Toolkit.ToolsByName` cannot reduce its mapped-as key while `Name` is\n // generic (it degrades to a string index signature); at every concrete\n // `Name` the two records are identical, so this assertion bridges only that\n // compiler limitation and crosses no schema boundary.\n const toolkit = Toolkit.make(delegation.tool as Tool.Any) as unknown as Toolkit.Toolkit<\n SubagentTools<Name, Parameters, Success, Failure, Mode>\n >;\n\n // Containment (SUB-033): under `failureMode: \"return\"` every expected\n // delegation failure becomes the handler's SUCCESS value (the Tool success\n // Schema is the union of the declared success and the contained family);\n // exactly the engine signals stay raisable, so the durable waiting\n // suspension and coordinator-seam errors keep their semantics.\n const contained = delegation.failureMode === \"return\";\n const encodeChildInput = Schema.encodeEffect(delegation.target.input);\n const encodeSuccess = Schema.encodeEffect(delegation.success);\n const decodeChildOutput = Schema.decodeUnknownEffect(delegation.target.output);\n\n const encodeResultProjectionFailure = Schema.encodeEffect(\n Schema.Union([delegation.failure, SubagentProjectionFailure]),\n );\n\n const childToolCallAllowance = (\n parameters: Parameters[\"Type\"],\n policy: SubagentPolicy,\n childPolicy: AgentPolicy,\n ) => resolveToolCallAllowance(delegation.toolCallAllowance, parameters, policy, childPolicy);\n\n // Capture an explicit digest override without retaining mutable author options.\n const durableDeclaration: SubagentDurableOptions | undefined =\n options.durable === undefined\n ? undefined\n : {\n targetDigests: {\n agent: options.durable.targetDigests.agent,\n model: options.durable.targetDigests.model,\n tools: options.durable.targetDigests.tools,\n },\n };\n\n const executionFailure = (\n classification: SubagentExecutionFailureClassification,\n errorTag: string,\n message: string,\n child?: RunSubagentChildIdentity,\n ): SubagentExecutionFailure =>\n SubagentExecutionFailure.make({\n delegationId: delegation.delegationId,\n targetAgentId: delegation.target.id,\n classification,\n errorTag: boundedErrorTag(errorTag),\n message: boundedEventText(message),\n ...(child === undefined\n ? {}\n : {\n childThreadId: child.childThreadId,\n childSubmissionId: child.childSubmissionId,\n childRunId: child.childRunId,\n }),\n });\n\n const prestartDenied = (\n reason: SubagentPrestartDenied[\"reason\"],\n message: string,\n ): SubagentPrestartDenied =>\n SubagentPrestartDenied.make({\n delegationId: delegation.delegationId,\n targetAgentId: delegation.target.id,\n reason,\n message: boundedEventText(message),\n });\n\n const build = Effect.gen(function* () {\n const captured =\n yield* Effect.context<\n SubagentLayerRequirements<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n PrepareRequirements,\n ProjectRequirements,\n HookRequirements,\n InstructionError,\n InstructionRequirements,\n InputPromptValue,\n UpdatesSchema,\n RunDispositionValue\n >\n >();\n\n const invoke = Effect.fn(`SubagentRuntime.${delegation.name}`)(function* (\n parameters: Parameters[\"Type\"],\n handlerContext: Toolkit.HandlerContext<\n SubagentTool<Name, Parameters, Success, Failure, Mode>\n >,\n ) {\n const spawner = yield* AgentSpawner;\n const resolved = resolvePolicy(spawner);\n const { policy, childPolicy, allocation } = resolved;\n\n const caps =\n spawner.budget === undefined\n ? resolved.caps\n : residualSubagentCaps(\n resolved.caps,\n spawner.policy,\n spawner.budget,\n spawner.budgetScope === \"worker-run\",\n );\n\n const sink = yield* RunEventSink;\n const reservations = yield* SubagentReservations;\n\n // The interpreter supplies the parent Tool Call identity for every\n // executed Tool Call; its absence is an engine defect, not an expected\n // failure of the delegation.\n const toolCallId = yield* Schema.decodeUnknownEffect(ToolCallId)(\n handlerContext.toolCallId,\n ).pipe(Effect.orDie);\n\n const grant = narrowSubagentGrant(delegation.grant, spawner.grant);\n const depth = spawner.depth + 1;\n\n if (depth > grant.maxDepth) {\n return yield* prestartDenied(\n \"nested-delegation\",\n \"Delegation exceeds the inherited depth ceiling\",\n );\n }\n if (!(spawner.grant?.childLifetimes ?? [\"attached\", \"background\"]).includes(\"attached\")) {\n return yield* prestartDenied(\n \"grant-violation\",\n \"The inherited grant does not permit attached children\",\n );\n }\n if (spawner.depth > 0 && spawner.budget === undefined) {\n return yield* prestartDenied(\n \"budget-conflict\",\n \"Nested ephemeral delegation requires an inherited subtree reservation\",\n );\n }\n\n const prepared = yield* delegation.prepareInput(parameters, {\n source: \"tool\",\n delegationId: delegation.delegationId,\n toolCallId,\n parent: spawner.parent,\n });\n\n const encodedInput = yield* encodeChildInput(prepared).pipe(\n Effect.mapError(() =>\n SubagentProjectionFailure.make({\n delegationId: delegation.delegationId,\n stage: \"input\",\n message: \"Prepared child input did not satisfy the target Agent input Schema\",\n }),\n ),\n );\n\n const parentRunId = spawner.parent.runId;\n\n yield* reservations\n .registerParent(parentRunId, caps)\n .pipe(\n Effect.catchTag(\"SubagentParentBudgetConflict\", () =>\n Effect.fail(\n prestartDenied(\n \"budget-conflict\",\n \"The parent Run is already registered with different delegation caps; supply shared parentCaps explicitly\",\n ),\n ),\n ),\n );\n\n const reservationId = makeBudgetReservationId(parentRunId, toolCallId);\n const startedAt = yield* Ref.make<number | undefined>(undefined);\n\n // Reservation settlement is finalizer-driven from this point on: every\n // exit path — success, declared failure, interruption, defect — settles\n // accounting exactly once when the handler scope closes.\n yield* Effect.acquireRelease(\n reservations\n .reserve(\n SubagentReservationRequest.make({\n parentRunId,\n parentToolCallId: toolCallId,\n allocation,\n ...(policy.descendantInvocations === undefined\n ? {}\n : { descendantInvocations: policy.descendantInvocations }),\n }),\n )\n .pipe(\n // A same-key conflict or unregistered parent after a successful\n // registerParent is a ledger invariant violation, not an expected\n // delegation failure.\n Effect.catchTags({\n SubagentReservationConflict: (conflict) => Effect.die(conflict),\n SubagentParentBudgetUnknown: (unknown) => Effect.die(unknown),\n }),\n ),\n () =>\n settleReservation(\n reservations,\n reservationId,\n startedAt,\n (policy.descendantInvocations ?? 0) > 0 ? { parentRunId, allocation } : undefined,\n ),\n );\n // Scope-owned concurrency permit: interruption while queued frees the\n // slot, and the settlement finalizer above releases the reservation.\n yield* reservations\n .acquireChildSlot(parentRunId, 1 + (policy.descendantInvocations ?? 0))\n .pipe(Effect.catchTag(\"SubagentParentBudgetUnknown\", (unknown) => Effect.die(unknown)));\n\n const seededChild = options.child;\n const seededBudget = seededChild?.budget;\n\n const budget: RunBudgetHook<never, HookRequirements> = {\n guard:\n seededBudget === undefined ? (effect) => effect : (effect) => seededBudget.guard(effect),\n consume: (delta) =>\n reservations\n .observe(reservationId, observedUsageFromDelta(delta))\n .pipe(\n Effect.orDie,\n Effect.andThen(\n seededBudget === undefined ? Effect.void : seededBudget.consume(delta),\n ),\n ),\n };\n\n const toolCallAllowance = childToolCallAllowance(parameters, policy, childPolicy);\n\n const childOptions: SpawnRunOptions<never, HookRequirements> = {\n ...seededChild,\n subagentGrant: grant,\n delegationDepth: depth,\n subagentBudget: SubagentBudgetReservation.make({\n caps,\n allocation,\n ...(policy.descendantInvocations === undefined\n ? {}\n : { descendantInvocations: policy.descendantInvocations }),\n }),\n budget,\n ...(toolCallAllowance === undefined ? {} : { toolCallAllowance }),\n };\n\n yield* Ref.set(startedAt, yield* Clock.currentTimeMillis);\n\n const childScope = yield* Scope.make();\n\n yield* Effect.addFinalizer((exit) => Scope.close(childScope, exit));\n\n const child = yield* spawner\n .spawn<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n Provider,\n ModelProvides,\n ModelRequires,\n never,\n HookRequirements,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >(\n { ...childBinding, definition: { ...childBinding.definition, policy: childPolicy } },\n encodedInput,\n { delegationId: delegation.delegationId, parentToolCallId: toolCallId },\n childOptions,\n )\n .pipe(Scope.provide(childScope));\n\n const payload: SubagentEventBasePayload = {\n toolCallId,\n delegationId: delegation.delegationId,\n childThreadId: child.threadId,\n childRunId: child.runId,\n targetAgentId: delegation.target.id,\n depth: child.parentLink.depth,\n };\n\n // The sink cannot be closed while this Tool batch is live; a closed\n // sink here is an engine defect.\n const emit = (event: SubagentEventPayload): Effect.Effect<void> =>\n sink.emit(event).pipe(Effect.orDie);\n\n yield* emit({ _tag: \"SubagentRequested\", ...payload });\n yield* emit({ _tag: \"SubagentStarted\", ...payload });\n\n const joined = Effect.gen(function* () {\n const result = yield* child.await.pipe(\n Effect.catch((childFailure) =>\n child.usageReport.pipe(\n Effect.flatMap((report) =>\n emit({\n _tag: \"SubagentFailed\",\n ...payload,\n ...report,\n errorTag: errorTagOf(childFailure),\n message: boundedEventText(errorMessageOf(childFailure)),\n }),\n ),\n Effect.andThen(\n Effect.fail(\n options.mapChildFailure === undefined\n ? executionFailure(\n \"child-failed\",\n errorTagOf(childFailure),\n \"The child Run failed\",\n )\n : options.mapChildFailure(childFailure),\n ),\n ),\n ),\n ),\n Effect.timeoutOrElse({\n duration: Duration.millis(allocation.durationMillis),\n orElse: () => Effect.succeed(undefined),\n }),\n Effect.tapCause((cause) =>\n Cause.hasDies(cause)\n ? child.usageReport.pipe(\n Effect.flatMap((report) =>\n emit({\n _tag: \"SubagentFailed\",\n ...payload,\n ...report,\n errorTag: \"Defect\",\n message: \"The child Run ended with a defect\",\n }),\n ),\n Effect.ignore,\n )\n : Effect.void,\n ),\n );\n\n if (result === undefined) {\n // Choose the timeout before interrupting the child; otherwise its interrupted await\n // can win the timeout race and replace the typed delegation failure.\n yield* Scope.close(childScope, Exit.void);\n const report = yield* child.usageReport;\n\n yield* emit({\n _tag: \"SubagentFailed\",\n ...payload,\n ...report,\n errorTag: \"SubagentBudgetExhausted\",\n message: `Attached child exceeded its ${allocation.durationMillis}ms delegation duration budget`,\n });\n\n return yield* SubagentBudgetExhausted.make({\n parentRunId,\n dimension: \"duration\",\n limitValue: allocation.durationMillis,\n observedValue: allocation.durationMillis,\n });\n }\n const report = yield* child.usageReport;\n\n yield* emit({\n _tag: \"SubagentCompleted\",\n ...payload,\n ...report,\n turns: result.turns,\n finishReason: result.finishReason,\n ...(result.exhausted !== undefined ? { exhausted: result.exhausted } : {}),\n });\n\n const projected = yield* delegation.projectResult(\n result.output,\n {\n budgetExhausted: result.finishReason === \"budget-exhausted\",\n ...report,\n },\n parameters,\n );\n\n const encodedResult = yield* encodeSuccess(projected).pipe(\n Effect.mapError(() =>\n SubagentProjectionFailure.make({\n delegationId: delegation.delegationId,\n stage: \"result\",\n message: \"Projected child result did not satisfy the delegation success Schema\",\n }),\n ),\n );\n\n const resultBytes = utf8ByteLength(JSON.stringify(encodedResult) ?? \"\");\n\n yield* reservations\n .observe(reservationId, SubagentObservedUsage.make({ resultBytes }))\n .pipe(Effect.orDie);\n if (policy.maxResultBytes !== undefined && resultBytes > policy.maxResultBytes) {\n yield* emit({\n _tag: \"SubagentFailed\",\n ...payload,\n ...report,\n errorTag: \"SubagentBudgetExhausted\",\n message: `Projected child result of ${resultBytes} bytes exceeds the ${policy.maxResultBytes}-byte delegation budget`,\n });\n\n return yield* SubagentBudgetExhausted.make({\n parentRunId,\n dimension: \"result-bytes\",\n limitValue: policy.maxResultBytes,\n observedValue: resultBytes,\n });\n }\n yield* emit({ _tag: \"SubagentJoined\", ...payload, ...report });\n\n return projected;\n });\n\n // Join the interrupted child before observing its final usage. Keep the original\n // interruption even when the closing parent can no longer accept lifecycle events.\n return yield* joined.pipe(\n Effect.onInterrupt(() =>\n Scope.close(childScope, Exit.void).pipe(\n Effect.andThen(child.usageReport),\n Effect.flatMap((report) =>\n sink.emit({\n _tag: \"SubagentInterrupted\",\n ...payload,\n ...report,\n reason: \"Parent Run interrupted the attached child before it settled\",\n }),\n ),\n Effect.ignore,\n ),\n ),\n );\n });\n\n /**\n * Durable branch: establishment through the\n * coordinator's idempotent protocol instead of an in-process spawn. No\n * child fiber ever starts here, and the S1 in-memory reservation service\n * is deliberately not consulted — its Scope-finalizer settlement\n * contradicts a handler that exits with the waiting signal while the\n * child keeps running; durable budget lives in the coordinator's fenced\n * ledger reservation built from `encodedAllocation`.\n */\n const invokeDurable = Effect.fn(`SubagentRuntime.${delegation.name}.durable`)(function* (\n parameters: Parameters[\"Type\"],\n handlerContext: Toolkit.HandlerContext<\n SubagentTool<Name, Parameters, Success, Failure, Mode>\n >,\n durability: SubagentDurabilityDurable,\n ) {\n const spawner = yield* AgentSpawner;\n const { policy, childPolicy, allocation, caps } = resolvePolicy(spawner);\n const encodedAllocation = yield* encodeAllocationAmounts(allocation).pipe(Effect.orDie);\n\n const conservativeAccounting = yield* encodeDurableAccounting(\n SubagentDurableAccounting.make({\n allocation,\n consumed: allocation,\n released: zeroReservationAmounts,\n basis: \"reserved-conservative\",\n }),\n ).pipe(Effect.orDie);\n\n const sink = yield* RunEventSink;\n\n const toolCallId = yield* Schema.decodeUnknownEffect(ToolCallId)(\n handlerContext.toolCallId,\n ).pipe(Effect.orDie);\n\n const emit = (event: SubagentEventPayload): Effect.Effect<void> =>\n sink.emit(event).pipe(Effect.orDie);\n\n // Resume cannot restore authority removed by an ancestor.\n const grant = narrowSubagentGrant(delegation.grant, spawner.grant);\n const depth = spawner.depth + 1;\n\n if (depth > grant.maxDepth) {\n return yield* prestartDenied(\n \"nested-delegation\",\n \"Delegation exceeds the inherited depth ceiling\",\n );\n }\n if (!(spawner.grant?.childLifetimes ?? [\"attached\", \"background\"]).includes(\"attached\")) {\n return yield* prestartDenied(\n \"grant-violation\",\n \"The inherited grant does not permit attached children\",\n );\n }\n const encodedGrant = yield* encodeGrant(grant).pipe(Effect.orDie);\n\n const prepared = yield* delegation.prepareInput(parameters, {\n source: \"tool\",\n delegationId: delegation.delegationId,\n toolCallId,\n parent: spawner.parent,\n });\n\n const encodedInput = yield* encodeChildInput(prepared).pipe(\n Effect.mapError(() =>\n SubagentProjectionFailure.make({\n delegationId: delegation.delegationId,\n stage: \"input\",\n message: \"Prepared child input did not satisfy the target Agent input Schema\",\n }),\n ),\n );\n\n // Establishment is idempotent by construction (SUB-016): the identical\n // request replays spec §12 steps 2-9 under the parent fence and\n // converges on the one existing child; a divergent replay (changed\n // digests, grant, allocation, or input) is denied fail-closed by the\n // coordinator and surfaces below as `\"establishment-denied\"`.\n const status = yield* Effect.mapError(wrapEngineSignal)(\n durability.establish({\n toolCallId,\n delegationId: delegation.delegationId,\n target: delegation.target,\n targetAgentId: delegation.target.id,\n depth,\n ...(durableDeclaration === undefined\n ? {}\n : { targetDigests: durableDeclaration.targetDigests }),\n encodedChildInput: encodedInput,\n encodedGrant,\n encodedAllocation,\n toolCallAllowance: childToolCallAllowance(parameters, policy, childPolicy),\n policy: childPolicy,\n budget: {\n caps,\n allocation,\n ...(policy.descendantInvocations === undefined\n ? {}\n : { descendantInvocations: policy.descendantInvocations }),\n },\n }),\n );\n\n switch (status._tag) {\n case \"denied\": {\n return yield* executionFailure(\"establishment-denied\", status.errorTag, status.message);\n }\n case \"waiting\": {\n const payload: SubagentEventBasePayload = {\n toolCallId,\n delegationId: delegation.delegationId,\n childThreadId: status.childThreadId,\n childRunId: status.childRunId,\n targetAgentId: delegation.target.id,\n depth,\n };\n\n yield* emit({ _tag: \"SubagentRequested\", ...payload });\n yield* emit({ _tag: \"SubagentStarted\", ...payload });\n\n // The handler ends here and never returns: the engine keeps the\n // call open (no Tool failure, no batch failure policy), siblings\n // finish, and the Run suspends waitingForChild — never polling,\n // never respawning (SUB-018, SUB-030).\n return yield* Effect.mapError(wrapEngineSignal)(durability.waiting(toolCallId, status));\n }\n case \"settled\": {\n const payload: SubagentEventBasePayload = {\n toolCallId,\n delegationId: delegation.delegationId,\n childThreadId: status.childThreadId,\n childRunId: status.childRunId,\n targetAgentId: delegation.target.id,\n depth,\n };\n\n const report = RunUsageReport.make({\n usage: status.usage ?? unknownRunTotals(),\n delegatedUsage: status.delegatedUsage ?? unknownRunTotals(),\n });\n\n // Every terminal projection of a settled child — success or typed\n // failure — goes through ONE atomic join (SUB-019): the coordinator\n // appends `SubagentJoined` + the parent `ToolCallSettled` in one\n // canonical batch and applies the accounting decision. The handler\n // then fails/returns the same value so the live batch continues\n // with exactly what canonical history recorded.\n const settleFailure = <F>(\n failure: F,\n encodedFailure: unknown,\n ): Effect.Effect<never, F | GenuineEngineSignal> =>\n emit({\n _tag: \"SubagentFailed\",\n ...payload,\n ...report,\n errorTag: errorTagOf(failure),\n message: boundedEventText(errorMessageOf(failure)),\n }).pipe(\n Effect.andThen(\n Effect.mapError(wrapEngineSignal)(\n durability.join({\n toolCallId,\n encodedResult: encodedFailure,\n // Canonical history must record exactly what the live\n // batch continues with (SUB-019): under containment the\n // failure is the call's model-visible RESULT (the dispatch\n // wrapper converts the fail below into a success), so the\n // joined settlement records it as a non-failure result;\n // the child's own failed Settlement and the\n // `SubagentFailed` event stay the honest failure record.\n isFailure: !contained,\n encodedAccounting: conservativeAccounting,\n }),\n ),\n ),\n Effect.andThen(Effect.fail(failure)),\n );\n\n if (status.outcome !== \"completed\") {\n const projection = childFailureProjectionOf(status.encodedResult);\n\n const failure = executionFailure(\n status.outcome === \"aborted\"\n ? \"child-aborted\"\n : projection.errorTag === \"ChildCompatibilityFailure\"\n ? \"child-compatibility\"\n : \"child-failed\",\n projection.errorTag,\n projection.message,\n status,\n );\n\n const encodedFailure = yield* encodeExecutionFailure(failure).pipe(Effect.orDie);\n\n return yield* settleFailure(failure, encodedFailure);\n }\n\n // The coordinator already verified lineage, target, digests, and\n // settlement identity fail-closed (spec §12 join steps 1-2); the\n // handler still refuses settled output that escapes the target\n // output Schema — hostile child output cannot cross the\n // declassification boundary undecoded, and the fixed message never\n // carries the raw value.\n const decoded = yield* decodeChildOutput(status.encodedResult).pipe(\n Effect.catch(() => {\n const failure = SubagentProjectionFailure.make({\n delegationId: delegation.delegationId,\n stage: \"result\",\n message: \"Settled child output did not satisfy the target Agent output Schema\",\n });\n\n return encodeProjectionFailure(failure).pipe(\n Effect.orDie,\n Effect.flatMap((encodedFailure) => settleFailure(failure, encodedFailure)),\n );\n }),\n );\n\n const projected = yield* delegation\n .projectResult(\n decoded,\n {\n budgetExhausted: status.finishReason === \"budget-exhausted\",\n ...report,\n },\n parameters,\n )\n .pipe(\n Effect.catch((declared) =>\n encodeResultProjectionFailure(declared).pipe(\n Effect.orDie,\n Effect.flatMap((encodedFailure) => settleFailure(declared, encodedFailure)),\n ),\n ),\n );\n\n const encodedResult = yield* encodeSuccess(projected).pipe(\n Effect.catch(() => {\n const failure = SubagentProjectionFailure.make({\n delegationId: delegation.delegationId,\n stage: \"result\",\n message: \"Projected child result did not satisfy the delegation success Schema\",\n });\n\n return encodeProjectionFailure(failure).pipe(\n Effect.orDie,\n Effect.flatMap((encodedFailure) => settleFailure(failure, encodedFailure)),\n );\n }),\n );\n\n const resultBytes = utf8ByteLength(JSON.stringify(encodedResult) ?? \"\");\n\n if (policy.maxResultBytes !== undefined && resultBytes > policy.maxResultBytes) {\n const failure = SubagentBudgetExhausted.make({\n parentRunId: spawner.parent.runId,\n dimension: \"result-bytes\",\n limitValue: policy.maxResultBytes,\n observedValue: resultBytes,\n });\n\n const encodedFailure = yield* encodeBudgetFailure(failure).pipe(Effect.orDie);\n\n return yield* settleFailure(failure, encodedFailure);\n }\n yield* Effect.mapError(wrapEngineSignal)(\n durability.join({\n toolCallId,\n encodedResult,\n isFailure: false,\n encodedAccounting: conservativeAccounting,\n }),\n );\n yield* emit({ _tag: \"SubagentJoined\", ...payload, ...report });\n\n return projected;\n }\n }\n });\n\n // Containment boundary (SUB-033): under `\"return\"`, every expected\n // delegation failure becomes the handler's success value; exactly the\n // GENUINE engine signals re-fail unwrapped. Provenance comes from the\n // module-private `GenuineEngineSignal` wrapper applied at the only\n // operations that can produce those signals — an author-declared failure\n // that happens to use the exported signal classes is contained as data,\n // never rethrown as a suspension signal.\n const containSignals = (\n failure: SubagentToolFailure<Failure>[\"Type\"] | GenuineEngineSignal,\n ): Effect.Effect<\n SubagentContainedFailure<Failure>[\"Type\"],\n ToolCallWaiting | SubagentDurabilityError\n > =>\n failure instanceof GenuineEngineSignal\n ? Effect.fail(failure.signal)\n : Effect.succeed(failure);\n\n // Error mode still unwraps genuine signals so the engine sees the raw\n // `ToolCallWaiting`/`SubagentDurabilityError` it owns.\n const unwrapSignals = (\n failure: SubagentToolFailure<Failure>[\"Type\"] | GenuineEngineSignal,\n ): SubagentToolFailure<Failure>[\"Type\"] =>\n failure instanceof GenuineEngineSignal ? failure.signal : failure;\n\n const handlerImpl = (\n parameters: Parameters[\"Type\"],\n handlerContext: Toolkit.HandlerContext<\n SubagentTool<Name, Parameters, Success, Failure, Mode>\n >,\n ) =>\n Effect.gen(function* () {\n // Resolve the engine-provided per-call services before providing the\n // captured construction context and re-provide them innermost: if the\n // Layer was constructed inside another Run's Tool batch, the captured\n // context would otherwise shadow this Run's `AgentSpawner` (and its\n // delegation depth), this batch's live `RunEventSink`, and this\n // batch's live `SubagentDurability` mode.\n const spawner = yield* AgentSpawner;\n const sink = yield* RunEventSink;\n const durability = yield* SubagentDurability;\n\n // Service-mode dispatch (S2 plan §2): the engine states ephemeral\n // mode explicitly when no durable coordinator supplied the hook, so\n // absence keeps the S1 in-process spawn semantics honestly.\n if (durability.mode === \"durable\") {\n const durable = invokeDurable(parameters, handlerContext, durability).pipe(\n Effect.scoped,\n Effect.provideService(AgentSpawner, spawner),\n Effect.provideService(RunEventSink, sink),\n Effect.provideService(SubagentDurability, durability),\n Effect.provide(captured),\n );\n\n return yield* contained\n ? durable.pipe(Effect.catch(containSignals))\n : durable.pipe(Effect.mapError(unwrapSignals));\n }\n\n const ephemeral = invoke(parameters, handlerContext).pipe(\n Effect.scoped,\n Effect.provideService(AgentSpawner, spawner),\n Effect.provideService(RunEventSink, sink),\n Effect.provideService(SubagentDurability, durability),\n Effect.provide(captured),\n );\n\n return yield* contained\n ? ephemeral.pipe(Effect.catch(containSignals))\n : ephemeral.pipe(Effect.mapError(unwrapSignals));\n });\n\n // `handlerImpl`'s channels are the UNION of both modes because\n // `contained` is a runtime branch TypeScript cannot relate to the\n // conditional generic `Mode`; at every concrete `Mode` the branch taken\n // matches `SubagentHandler`'s channels exactly (proven by the mode type\n // tests), so this assertion bridges only that limitation and crosses no\n // schema boundary.\n const handler = handlerImpl as SubagentHandler<Name, Parameters, Success, Failure, Mode>;\n\n // TypeScript cannot relate a computed single-key object literal to the\n // generic mapped key `Name`; `handler` is fully checked against the\n // Tool's declared handler signature above, so this assertion bridges only\n // that compiler limitation and crosses no schema boundary.\n return { [delegation.name]: handler } as Toolkit.HandlersFrom<\n SubagentTools<Name, Parameters, Success, Failure, Mode>\n >;\n });\n\n return toolkit.toLayer(build);\n};\n\nexport { reporting, reportingToWorker, WorkerReport } from \"./internal/subagent-reporting.ts\";\n\nexport {\n Worker,\n WorkerObservation,\n start,\n followUp,\n inspect,\n observe,\n awaitWorker as await,\n list,\n cancel,\n type BackgroundOptions,\n type BackgroundTools,\n} from \"./internal/subagent-background.ts\";\n\n/**\n * Derive selected background Tools directly from a child Agent, using its ID as the delegation\n * name and its input/output Schemas as the default contract. Pass an explicit Subagent.make\n * declaration to customize the name, projections, grants, or policy bounds.\n */\nexport function background<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n const Selected extends BackgroundOptions,\n>(\n target: Definition<\n Input,\n Output,\n Instructions,\n Toolkit.Toolkit<Tools>,\n RunDispositionDeclaration<Output[\"Type\"], Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n > & {\n readonly id: AgentId & Name;\n },\n selected: Selected,\n): ReturnType<\n typeof backgroundDeclaration<\n Name,\n Input,\n Output,\n Input,\n SubagentResult<Output>,\n typeof Schema.Never,\n never,\n never,\n Selected\n >\n>;\n\nexport function background<\n const Name extends string,\n Input extends Schema.Top,\n Output extends Schema.Top,\n Parameters extends Schema.Top,\n Success extends Schema.Top,\n Failure extends Schema.Top,\n Prepare,\n Project,\n const Selected extends BackgroundOptions,\n>(\n declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>,\n selected: Selected,\n): ReturnType<\n typeof backgroundDeclaration<\n Name,\n Input,\n Output,\n Parameters,\n Success,\n Failure,\n Prepare,\n Project,\n Selected\n >\n>;\n\nexport function background(\n targetOrDeclaration:\n | Definition<\n Schema.Top,\n Schema.Top,\n unknown,\n Toolkit.Toolkit<Record<string, Tool.Any>>,\n RunDispositionDeclaration<unknown, Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n >\n | Declaration<\n string,\n Schema.Top,\n Schema.Top,\n Schema.Top,\n Schema.Top,\n Schema.Top,\n unknown,\n unknown\n >,\n selected: BackgroundOptions,\n): unknown {\n const declaration =\n \"target\" in targetOrDeclaration\n ? targetOrDeclaration\n : make(targetOrDeclaration.id, { target: targetOrDeclaration });\n\n return backgroundDeclaration(declaration, selected);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAKA,MAAM,cAAc,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC5D,MAAM,UAAU,OAAO;AAEvB,MAAM,y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