effect-agent 0.1.0-beta.113 → 0.1.0-beta.115
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Agent-1DMSO_Fl.mjs.map +1 -1
- package/dist/{Agent-DriBcXBN.d.mts → Agent-D9cXqfF3.d.mts} +9 -2
- package/dist/{AgentRuntime-DLwPoEVH.mjs → AgentRuntime-Cp1hAb-W.mjs} +8 -4
- package/dist/AgentRuntime-Cp1hAb-W.mjs.map +1 -0
- package/dist/{AgentRuntime-CWkHuzyt.d.mts → AgentRuntime-DyZv8uu2.d.mts} +6 -6
- package/dist/{DurableAgentRuntime-BIrgxwRl.mjs → DurableAgentRuntime-tNrkJZNo.mjs} +254 -162
- package/dist/DurableAgentRuntime-tNrkJZNo.mjs.map +1 -0
- package/dist/{DurableFailpoint-mx3-nsxU.d.mts → DurableFailpoint-Cnr3wx1L.d.mts} +3 -3
- package/dist/{EventSource-ARs56eBq.d.mts → EventSource-DPRdlvhV.d.mts} +3 -3
- package/dist/{Messaging-DaZDlBqh.d.mts → Messaging-JYYN3oYS.d.mts} +3 -3
- package/dist/{MessagingHost-e1Sbzfao.d.mts → MessagingHost-CqzpxbGz.d.mts} +3 -3
- package/dist/{MessagingHost-D89X7ma8.mjs → MessagingHost-DfsbMPvq.mjs} +2 -2
- package/dist/{MessagingHost-D89X7ma8.mjs.map → MessagingHost-DfsbMPvq.mjs.map} +1 -1
- package/dist/{Output-CAFJTAbP.d.mts → Output-V-6YL1_Z.d.mts} +2 -2
- package/dist/{PreparedInputAdmission-_WYg-D0f.d.mts → PreparedInputAdmission-DqQUjA9k.d.mts} +4 -4
- package/dist/{Records-BtxMy8xD.d.mts → Records-Byeb70tt.d.mts} +89 -31
- package/dist/{RunOptions-BoESJrxw.d.mts → RunOptions-CSBsSj0X.d.mts} +3 -3
- package/dist/{Schedule-DGPyXBzK.d.mts → Schedule-krSnBcbU.d.mts} +2 -2
- package/dist/{Subagent-D9eYdGTl.mjs → Subagent-Di8EEjWZ.mjs} +67 -105
- package/dist/Subagent-Di8EEjWZ.mjs.map +1 -0
- package/dist/{Subagent-F72tuaxy.d.mts → Subagent-gw9KD6eb.d.mts} +310 -35
- package/dist/{SubagentHost-CmiNTOBZ.d.mts → SubagentHost-P9zB_TfV.d.mts} +24 -18
- package/dist/{Subscription-B9VszlF9.d.mts → Subscription-Xnwd42Sm.d.mts} +6 -3
- package/dist/{SubscriptionInput-BJWZqCWP.d.mts → SubscriptionInput-CqtJ58vl.d.mts} +3 -3
- package/dist/{Worker-T_3RbaKc.mjs → Worker-CfwzMZEK.mjs} +66 -5
- package/dist/Worker-CfwzMZEK.mjs.map +1 -0
- package/dist/{Worker-Du9dhVnp.d.mts → Worker-fwWkBg12.d.mts} +199 -6
- package/dist/{agent-registration-B5CI-Ygk.mjs → agent-registration-CKNsrpwo.mjs} +7 -7
- package/dist/agent-registration-CKNsrpwo.mjs.map +1 -0
- package/dist/capabilities/Commands.d.mts +1 -1
- package/dist/capabilities/Messaging.d.mts +1 -1
- package/dist/capabilities/Messaging.mjs +2 -2
- package/dist/capabilities/RunHooks.d.mts +1 -1
- package/dist/capabilities/Subagent.d.mts +3 -3
- package/dist/capabilities/Subagent.mjs +3 -3
- package/dist/core/Agent.d.mts +1 -1
- package/dist/core/Worker.d.mts +2 -2
- package/dist/core/Worker.mjs +2 -2
- package/dist/durable/ActivityStore.d.mts +1 -1
- package/dist/durable/Admin.d.mts +1 -1
- package/dist/durable/AgentRegistration.d.mts +1 -1
- package/dist/durable/AgentRegistration.mjs +1 -1
- package/dist/durable/Certification.d.mts +2 -2
- package/dist/durable/CommittedActivity.d.mts +1 -1
- package/dist/durable/Digest.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.mjs +1 -1
- package/dist/durable/DurableFailpoint.d.mts +1 -1
- package/dist/durable/DurableFailpoint.mjs +4 -0
- package/dist/durable/DurableFailpoint.mjs.map +1 -1
- package/dist/durable/DurableFailpointTestControl.d.mts +1 -1
- package/dist/durable/EventSource.d.mts +1 -1
- package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
- package/dist/durable/MessageDelivery.d.mts +20 -3
- package/dist/durable/MessageDelivery.mjs +12 -4
- package/dist/durable/MessageDelivery.mjs.map +1 -1
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +41 -39
- package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
- package/dist/durable/PersistentHistory.d.mts +1 -1
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/Records.d.mts +2 -2
- package/dist/durable/Records.mjs +12 -5
- package/dist/durable/Records.mjs.map +1 -1
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/RunJournal.d.mts +1 -1
- package/dist/durable/Schedule.d.mts +1 -1
- package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
- package/dist/durable/ScheduleTransition.d.mts +1 -1
- package/dist/durable/Scheduling.d.mts +2 -2
- package/dist/durable/SqlMessageDeliveryStore.mjs +7 -1
- package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -1
- package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
- package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
- package/dist/durable/SqlThreadNativeReads.d.mts +5 -1
- package/dist/durable/SqlThreadNativeReads.mjs +6 -0
- package/dist/durable/SqlThreadNativeReads.mjs.map +1 -1
- package/dist/durable/SubmissionLedger.d.mts +2 -2
- package/dist/durable/SubmissionLedger.mjs +34 -4
- package/dist/durable/SubmissionLedger.mjs.map +1 -1
- package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
- package/dist/durable/SubmissionLedgerConformance.mjs +899 -706
- package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -1
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/Subscription.mjs +1 -1
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionInput.mjs +1 -1
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionTools.d.mts +3 -3
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/Subscriptions.d.mts +5 -5
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
- package/dist/durable/ThreadInvariants.d.mts +1 -1
- package/dist/durable/ThreadProjection.d.mts +1 -1
- package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
- package/dist/durable/ThreadStore.d.mts +1 -1
- package/dist/durable/ThreadStore.mjs +5 -0
- package/dist/durable/ThreadStore.mjs.map +1 -1
- package/dist/durable/ThreadStoreConformance.d.mts +1 -1
- package/dist/durable/WorkerHost.d.mts +3 -3
- package/dist/durable/WorkerHost.mjs +1 -1
- package/dist/engine/AgentRuntime.d.mts +1 -1
- package/dist/engine/AgentRuntime.mjs +1 -1
- package/dist/engine/MessagingHost.d.mts +1 -1
- package/dist/engine/MessagingHost.mjs +1 -1
- package/dist/engine/Output.d.mts +1 -1
- package/dist/engine/RunOptions.d.mts +1 -1
- package/dist/engine/SubagentHost.d.mts +2 -2
- package/dist/engine/SubagentHost.mjs +5 -1
- package/dist/engine/SubagentHost.mjs.map +1 -1
- package/dist/index.d.mts +16 -16
- package/dist/index.mjs +5 -5
- package/package.json +1 -1
- package/src/capabilities/Subagent.ts +2 -1
- package/src/capabilities/internal/subagent-background.ts +86 -57
- package/src/capabilities/internal/subagent-reporting.ts +3 -128
- package/src/core/Agent.ts +8 -1
- package/src/core/Worker.ts +58 -2
- package/src/durable/DurableAgentRuntime.ts +2 -0
- package/src/durable/DurableFailpoint.ts +4 -0
- package/src/durable/MessageDelivery.ts +17 -2
- package/src/durable/Records.ts +12 -2
- package/src/durable/SqlMessageDeliveryStore.ts +15 -1
- package/src/durable/SqlThreadNativeReads.ts +14 -0
- package/src/durable/SubmissionLedger.ts +48 -1
- package/src/durable/SubmissionLedgerConformance.ts +260 -42
- package/src/durable/ThreadStore.ts +5 -0
- package/src/durable/internal/agent-registration.ts +13 -48
- package/src/durable/internal/worker-host.ts +490 -341
- package/src/engine/SubagentHost.ts +37 -13
- package/src/engine/internal/agent-runtime.ts +17 -2
- package/dist/AgentRuntime-DLwPoEVH.mjs.map +0 -1
- package/dist/DurableAgentRuntime-BIrgxwRl.mjs.map +0 -1
- package/dist/Subagent-D9eYdGTl.mjs.map +0 -1
- package/dist/Worker-T_3RbaKc.mjs.map +0 -1
- package/dist/agent-registration-B5CI-Ygk.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Subagent-Di8EEjWZ.mjs","names":["FailureDiagnostic.Value","FailureDiagnostic.Failure","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 * as FailureDiagnostic from \"../../core/FailureDiagnostic.ts\";\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 /** Original validation error; detailed diagnostics are never part of the safe message. */\n cause: Schema.optionalKey(FailureDiagnostic.Value),\n stack: Schema.optionalKey(Schema.String),\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 { WorkerReportPreparationFailure, type WorkerRunReport } 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/** Project a canonical child outcome into the bounded standard completion message. */\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 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 { message };\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 * as FailureDiagnostic from \"../../core/FailureDiagnostic.ts\";\nimport { RunId, SettlementId, ThreadId } from \"../../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../../core/internal/utf8.ts\";\nimport { MessageRef, MessageStatus } from \"../../core/Messaging.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 WorkerStop,\n WorkerStopped,\n WorkerSummary,\n} from \"../../core/Worker.ts\";\nimport {\n SubagentHost,\n BackgroundReporting,\n WorkerReportPreparationFailure,\n type WorkerReporting,\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/** Model-facing projection deliberately excludes operator-private diagnostics. */\nconst toolObservation = <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\n/** One exact Receipt, including private canonical failure evidence for programmatic callers. */\nexport const WorkerObservation = <Success extends Schema.Top>(success: Success) => {\n const projected = toolObservation(success);\n\n return Schema.Union([\n projected.members[0],\n projected.members[1],\n Schema.Struct({\n ...projected.members[2].fields,\n diagnostic: Schema.optionalKey(FailureDiagnostic.Failure),\n }),\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\", cause?: unknown) =>\n SubagentProjectionFailure.make({\n delegationId: declaration.delegationId,\n stage,\n ...(cause === undefined ? {} : { cause }),\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((cause) => WorkerError.make({ operation, reason: \"worker-mismatch\", cause })),\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((cause) =>\n WorkerError.make({ operation, reason: \"receipt-mismatch\", cause }),\n ),\n );\n\n const validateDelivery = Effect.fn(\"Subagent.validateWorkerDelivery\")(function* (\n worker: WorkerRef,\n delivery: MessageStatus,\n operation: WorkerError[\"operation\"],\n ) {\n const validated = yield* Schema.decodeEffect(MessageStatus)(delivery).pipe(\n Effect.mapError((cause) => WorkerError.make({ operation, reason: \"corrupt\", cause })),\n );\n\n if (validated.receipt !== null) yield* validateReceipt(worker, validated.receipt, operation);\n\n return validated;\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\", cause: error }),\n ),\n );\n\n const prepare = Effect.fn(\"Subagent.prepareWorkerInput\")(function* (\n parameters: Parameters[\"Type\"],\n caller: WorkerContext,\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((cause) => projectionFailure(\"input\", cause)),\n );\n\n return encodedInput;\n });\n\n const validateKey = (key: IdempotencyKey, operation: \"start\" | \"followUp\") =>\n Schema.decodeEffect(IdempotencyKey)(key).pipe(\n Effect.mapError((cause) =>\n WorkerError.make({ operation, reason: \"idempotency-conflict\", cause }),\n ),\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 encodedParameters = yield* Schema.encodeEffect(declaration.parameters)(parameters).pipe(\n Effect.mapError((cause) => projectionFailure(\"input\", cause)),\n );\n\n const encodedGrant = yield* Schema.encodeEffect(SubagentGrant)(grant).pipe(\n Effect.mapError((cause) => projectionFailure(\"input\", cause)),\n );\n\n const started = yield* service.start({\n delegationId: declaration.delegationId,\n target: declaration.target,\n idempotencyKey: key,\n encodedParameters,\n encodedGrant,\n ...(options.budgetScope === undefined ? {} : { budgetScope: options.budgetScope }),\n prepare: Effect.gen(function* () {\n const encodedInput = yield* prepare(parameters, caller);\n\n const effectiveTarget = yield* service.resolveTargetPolicy({\n target: declaration.target,\n 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 return {\n encodedInput,\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 });\n\n const validated = yield* Schema.decodeEffect(WorkerStarted)(started).pipe(\n Effect.mapError((cause) =>\n WorkerError.make({ operation: \"start\", reason: \"corrupt\", cause }),\n ),\n );\n\n if (validated.delivery.message.ownerThreadId !== caller.source.threadId)\n return yield* WorkerError.make({ operation: \"start\", reason: \"message-mismatch\" });\n\n return {\n worker: yield* validateWorker(validated.worker, \"start\"),\n delivery: validated.delivery,\n };\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\n const encodedParameters = yield* Schema.encodeEffect(declaration.parameters)(parameters).pipe(\n Effect.mapError((cause) => projectionFailure(\"input\", cause)),\n );\n\n const encodedInput = yield* prepare(parameters, caller);\n\n const delivery = yield* validateDelivery(\n validated,\n yield* service.followUp({\n encodedParameters,\n encodedInput,\n worker: validated,\n target: declaration.target,\n idempotencyKey: key,\n }),\n \"followUp\",\n );\n\n if (delivery.message.ownerThreadId !== caller.source.threadId)\n return yield* WorkerError.make({ operation: \"followUp\", reason: \"message-mismatch\" });\n\n return delivery;\n });\n\n const inspectMessage = Effect.fn(\"Subagent.inspectWorkerMessage\")(function* (\n worker: Worker<Name>,\n message: MessageRef,\n ) {\n const service = yield* host;\n const validated = yield* validateWorker(worker, \"inspect\");\n\n const requested = yield* Schema.decodeEffect(MessageRef)(message).pipe(\n Effect.mapError((cause) =>\n WorkerError.make({ operation: \"inspect\", reason: \"message-mismatch\", cause }),\n ),\n );\n\n const observed = yield* service.inspect({\n worker: validated,\n target: declaration.target,\n message: requested,\n });\n\n if (!(\"message\" in observed))\n return yield* WorkerError.make({ operation: \"inspect\", reason: \"corrupt\" });\n const delivery = yield* validateDelivery(validated, observed, \"inspect\");\n\n if (!Schema.toEquivalence(MessageRef)(delivery.message, requested))\n return yield* WorkerError.make({ operation: \"inspect\", reason: \"message-mismatch\" });\n\n return delivery;\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 = yield* service[operation]({\n worker: validated,\n target: declaration.target,\n receipt: requested,\n });\n\n if (!(\"_tag\" in observed)) return yield* WorkerError.make({ operation, reason: \"corrupt\" });\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((cause) => WorkerError.make({ operation, reason: \"corrupt\", cause })),\n ),\n }),\n settlementId: yield* Schema.decodeEffect(SettlementId)(observed.settlementId).pipe(\n Effect.mapError((cause) => WorkerError.make({ operation, reason: \"corrupt\", cause })),\n ),\n };\n\n if (observed.outcome === \"failed\" || observed.outcome === \"aborted\") {\n return {\n ...base,\n outcome: observed.outcome,\n ...(observed.diagnostic === undefined\n ? {}\n : {\n diagnostic: yield* Schema.decodeEffect(FailureDiagnostic.Failure)(\n observed.diagnostic,\n ).pipe(\n Effect.mapError((cause) =>\n WorkerError.make({ operation, reason: \"corrupt\", cause }),\n ),\n ),\n }),\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((cause) => projectionFailure(\"result\", cause)));\n\n const output = yield* Schema.decodeUnknownEffect(declaration.target.output)(\n observed.encodedResult,\n ).pipe(Effect.mapError((cause) => projectionFailure(\"result\", cause)));\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((cause) => projectionFailure(\"result\", cause)),\n );\n\n const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(\n Effect.mapError((cause) => projectionFailure(\"result\", cause)),\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((cause) => projectionFailure(\"result\", cause)));\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, inspectMessage, observe, list, cancel };\n};\n\n/** Retain a first worker input. The same explicit key reuses its durable delivery identity. */\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/** Retain typed follow-up parameters for the same worker Thread; inspect its MessageRef for delivery. */\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 a worker summary, retained MessageRef, or the result of one exact accepted Receipt. */\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 message: MessageRef,\n): Effect.Effect<MessageStatus, WorkerError, SubagentHost>;\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 reference?: Receipt | MessageRef,\n) {\n return reference === undefined\n ? summary(declaration, worker)\n : \"messageId\" in reference\n ? operations(declaration).inspectMessage(worker, reference)\n : operations(declaration).observe(\"inspect\", worker, reference);\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/** Seal a continuing worker, retaining a stable command identity across retries and Runs. */\nexport const stop = <const Name extends string>(\n declaration: WorkerDeclaration<Name> & { readonly target: AnyDefinition },\n worker: Worker<Name>,\n options: { readonly idempotencyKey: IdempotencyKey },\n) =>\n Effect.gen(function* () {\n const service = yield* host;\n\n const command = yield* Schema.decodeEffect(WorkerStop)({ worker, ...options }).pipe(\n Effect.mapError((cause) => WorkerError.make({ operation: \"stop\", reason: \"corrupt\", cause })),\n );\n\n if (\n worker.delegationId !== declaration.delegationId ||\n worker.targetAgentId !== declaration.target.id\n )\n return yield* WorkerError.make({ operation: \"stop\", reason: \"worker-mismatch\" });\n\n return yield* service.stop({ ...command, target: declaration.target }).pipe(\n Effect.flatMap(Schema.decodeEffect(WorkerStopped)),\n Effect.mapError((cause) =>\n Schema.is(WorkerError)(cause)\n ? cause\n : WorkerError.make({ operation: \"stop\", reason: \"corrupt\", cause }),\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 standard completion and progress messages to the parent. */\n readonly reportToParent?: true;\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 InspectParameters = <Name extends string>(declaration: WorkerDeclaration<Name>) =>\n Schema.Struct({\n worker: Worker(declaration),\n message: Schema.optionalKey(MessageRef),\n receipt: Schema.optionalKey(Receipt),\n }).check(\n Schema.makeFilter(\n ({ message, receipt }) => (message === undefined) !== (receipt === undefined),\n { message: \"Provide exactly one retained message reference or accepted receipt\" },\n ),\n );\n\nconst Inspection = <Success extends Schema.Top>(success: Success) =>\n Schema.Union([MessageStatus, toolObservation(success)]);\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 ...WorkerSummary.fields,\n worker: Worker(declaration),\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), delivery: MessageStatus }).check(\n Schema.makeFilter(\n ({ worker, delivery }) =>\n delivery.receipt === null || worker.threadId === delivery.receipt.threadId,\n ),\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 MessageStatus;\n failure: ReturnType<typeof preparationFailure<Failure>>;\n };\n inspect: {\n parameters: ReturnType<typeof InspectParameters<Name>>;\n success: ReturnType<typeof Inspection<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 = selected.reportToParent === true ? automaticReporting(declaration) : undefined;\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: `Retain input for a background ${declaration.name} worker and return its delivery state. Pending confirms retention only; inspect the same message instead of starting another worker.`,\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: `Retain typed follow-up input for an existing ${declaration.name} worker. Pending is retained, not executed: inspect the same message instead of sending the command again.`,\n parameters: FollowUpParameters(declaration, declaration.parameters),\n success: MessageStatus,\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 ${declaration.name} delivery by message reference, or its execution result by accepted receipt. Provide exactly one reference; inspection never resends input.`,\n parameters: InspectParameters(declaration),\n success: Inspection(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 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 message?: MessageRef;\n readonly receipt?: Receipt;\n }) =>\n Effect.gen(function* () {\n const service = yield* host;\n\n if (parameters.message !== undefined)\n return yield* ops.inspectMessage(parameters.worker, parameters.message);\n if (parameters.receipt === undefined)\n return yield* WorkerError.make({ operation: \"inspect\", reason: \"message-mismatch\" });\n\n return yield* ops.observe(\"inspect\", parameters.worker, parameters.receipt).pipe(\n Effect.map((observed) => {\n if (\"diagnostic\" in observed) {\n const { diagnostic: _diagnostic, ...projected } = observed;\n\n return projected;\n }\n\n return observed;\n }),\n Effect.provideService(SubagentHost, service),\n Effect.provide(captured),\n );\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 | SelectionServices<Selected[\"reportToParent\"], Exclude<ProjectServices, Scope.Scope>>;\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 { Cause, Clock, Duration, Effect, Exit, Layer, 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 ModelServices,\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 using the provided model requirement, or pass\n * a native model / explicit child Binding as an override. Without an override,\n * provide the model with Layer.provide; the handler captures it at construction.\n * AutoModel resolves each new child's own Thread ID and projected first task.\n * Share its selection store across parent Runs and child handler Layers.\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 function 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 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?: undefined,\n options?: SubagentRuntimeOptions<\n Failure,\n SubagentChildRunFailure<\n TargetInput,\n TargetOutput,\n TargetInstructions,\n TargetTools,\n never,\n never,\n ModelServices,\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 never,\n never,\n ModelServices,\n PrepareRequirements,\n ProjectRequirements,\n HookRequirements,\n InstructionError,\n InstructionRequirements,\n InputPromptValue,\n UpdatesSchema,\n RunDispositionValue\n >\n>;\n\nexport function 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\nexport function 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 | ModelServices,\n PrepareRequirements,\n ProjectRequirements,\n HookRequirements,\n InstructionError,\n InstructionRequirements,\n InputPromptValue,\n UpdatesSchema,\n RunDispositionValue\n >\n> {\n const childBinding =\n modelOrBinding !== undefined && \"definition\" in modelOrBinding\n ? modelOrBinding\n : {\n definition: delegation.target,\n model: modelOrBinding ?? Layer.effectContext(Effect.context<ModelServices>()),\n };\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 never,\n ModelRequires | ModelServices,\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 never,\n ModelRequires | ModelServices,\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 { 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 stop,\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":";;;;;;;;;;;;;;;;;;AAMA,MAAM,cAAc,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC5D,MAAM,UAAU,OAAO;AAEvB,MAAM,yBAAyB,OAAO,SAAS,KAC7C,OAAO,QACJ,aACC,SAAS,SAAS,QAAQ,KAAK,SAAS,WAAW,QAAQ,GAC7D,EAAE,UAAU,6BAA6B,CAC3C,CACF;AAEA,MAAM,uBAAuB,OAAO,OAAO;;CAEzC,aAAa;;CAEb,gBAAgB;;CAEhB,uBAAuB,OAAO,YAAY,OAAO;;CAEjD,UAAU;;CAEV,cAAc;;CAEd,aAAa;CACb,gBAAgB,OAAO,YAAY,WAAW;CAC9C,iBAAiB,OAAO,YAAY,WAAW;CAC/C,iBAAiB,OAAO,YAAY,OAAO;CAC3C,gBAAgB,OAAO,YAAY,WAAW;AAChD,CAAC;;;;;;;AAkBD,IAAa,iBAAb,cAAoC,OAAO,MACzC,2CACF,CAAC,CAAC,oBAAoB,CAAC,CAAC;;CAEtB,OAAgB,KAAK,OAA4C;EAC/D,OAAO,MAAM,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