effect-agent 0.1.0-beta.139 → 0.1.0-beta.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/{Admin-Fx85KT-W.d.mts → Admin-DGZXE5BU.d.mts} +7 -7
  2. package/dist/Agent-1DMSO_Fl.mjs.map +1 -1
  3. package/dist/{Agent-D9cXqfF3.d.mts → Agent-BWhD4Dvu.d.mts} +5 -2
  4. package/dist/{AgentRuntime-DEDvMkAR.d.mts → AgentRuntime-B4kIzmSF.d.mts} +5 -5
  5. package/dist/{AgentRuntime-Cp1hAb-W.mjs → AgentRuntime-RdmnK_aD.mjs} +5 -5
  6. package/dist/AgentRuntime-RdmnK_aD.mjs.map +1 -0
  7. package/dist/{DurableAgentRuntime-Bso5grIH.mjs → DurableAgentRuntime-BmG_UVZG.mjs} +2 -2
  8. package/dist/{DurableAgentRuntime-Bso5grIH.mjs.map → DurableAgentRuntime-BmG_UVZG.mjs.map} +1 -1
  9. package/dist/{EventSource-DLT8oDK8.d.mts → EventSource-Cg3IeJa6.d.mts} +2 -2
  10. package/dist/{Messaging-JYYN3oYS.d.mts → Messaging-Dnmk31yq.d.mts} +3 -3
  11. package/dist/{MessagingHost-CqzpxbGz.d.mts → MessagingHost-CajpPDPG.d.mts} +2 -2
  12. package/dist/{Output-V-6YL1_Z.d.mts → Output-DhtWbBcw.d.mts} +2 -2
  13. package/dist/{PreparedInputAdmission-CKFgG6Em.d.mts → PreparedInputAdmission-CLvaruRe.d.mts} +3 -3
  14. package/dist/{RunOptions-CSBsSj0X.d.mts → RunOptions-IlEXLG5F.d.mts} +2 -2
  15. package/dist/{Subagent-DJeZDrbD.mjs → Subagent-Bnc7I-kb.mjs} +2 -2
  16. package/dist/{Subagent-DJeZDrbD.mjs.map → Subagent-Bnc7I-kb.mjs.map} +1 -1
  17. package/dist/{Subagent-DRFyQxdb.d.mts → Subagent-Cl8D1mFM.d.mts} +5 -5
  18. package/dist/{SubagentHost-DQjHFGqH.d.mts → SubagentHost-B6f4PBC2.d.mts} +2 -2
  19. package/dist/{Subscription-CCmHgOYM.d.mts → Subscription-_VTIVN8o.d.mts} +2 -2
  20. package/dist/{SubscriptionInput-BFJMhu4K.d.mts → SubscriptionInput-BIH1f3Th.d.mts} +2 -2
  21. package/dist/capabilities/Commands.d.mts +1 -1
  22. package/dist/capabilities/Messaging.d.mts +1 -1
  23. package/dist/capabilities/RunHooks.d.mts +1 -1
  24. package/dist/capabilities/Subagent.d.mts +1 -1
  25. package/dist/capabilities/Subagent.mjs +1 -1
  26. package/dist/core/Agent.d.mts +1 -1
  27. package/dist/durable/Admin.d.mts +1 -1
  28. package/dist/durable/AgentRegistration.d.mts +1 -1
  29. package/dist/durable/Certification.d.mts +1 -1
  30. package/dist/durable/CommittedActivity.d.mts +1 -1
  31. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  32. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  33. package/dist/durable/EventSource.d.mts +1 -1
  34. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  35. package/dist/durable/MessageDelivery.d.mts +3 -3
  36. package/dist/durable/MessageDeliveryStoreConformance.d.mts +1 -1
  37. package/dist/durable/PersistentHistory.d.mts +1 -1
  38. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  39. package/dist/durable/Recovery.d.mts +1 -1
  40. package/dist/durable/RunJournal.d.mts +1 -1
  41. package/dist/durable/Scheduling.d.mts +1 -1
  42. package/dist/durable/SqlStorageV2Upgrade.d.mts +1 -1
  43. package/dist/durable/SqlSubscriptionStore.d.mts +1 -1
  44. package/dist/durable/SqlThreadNativeReads.d.mts +1 -1
  45. package/dist/durable/SubmissionLedger.d.mts +1 -1
  46. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  47. package/dist/durable/SubmissionStatus.d.mts +1 -1
  48. package/dist/durable/Subscription.d.mts +1 -1
  49. package/dist/durable/SubscriptionInput.d.mts +1 -1
  50. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  51. package/dist/durable/SubscriptionTools.d.mts +2 -2
  52. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  53. package/dist/durable/Subscriptions.d.mts +5 -5
  54. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  55. package/dist/durable/ThreadInvariants.d.mts +1 -1
  56. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  57. package/dist/durable/ThreadStore.d.mts +1 -1
  58. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  59. package/dist/durable/WorkerHost.d.mts +2 -2
  60. package/dist/engine/AgentRuntime.d.mts +1 -1
  61. package/dist/engine/AgentRuntime.mjs +1 -1
  62. package/dist/engine/MessagingHost.d.mts +1 -1
  63. package/dist/engine/Output.d.mts +1 -1
  64. package/dist/engine/Output.mjs +1 -1
  65. package/dist/engine/RunOptions.d.mts +1 -1
  66. package/dist/engine/SubagentHost.d.mts +1 -1
  67. package/dist/index.d.mts +13 -13
  68. package/dist/index.mjs +3 -3
  69. package/dist/{output-contract-BC7tjlGw.mjs → output-contract-CANJJGA5.mjs} +34 -19
  70. package/dist/{output-contract-BC7tjlGw.mjs.map → output-contract-CANJJGA5.mjs.map} +1 -1
  71. package/package.json +1 -1
  72. package/src/core/Agent.ts +4 -1
  73. package/src/engine/internal/agent-runtime.ts +12 -8
  74. package/src/engine/internal/output-contract.ts +36 -18
  75. package/dist/AgentRuntime-Cp1hAb-W.mjs.map +0 -1
@@ -10,15 +10,15 @@ import { a as FailureDiagnostic_d_exports, r as Diagnostic } from "./FailureDiag
10
10
  import { a as AgentInputError } from "./AgentError-Bn1ytXRD.mjs";
11
11
  import { t as ToolParameterRejection } from "./ToolResult-BKdqWRff.mjs";
12
12
  import { t as AgentPolicy } from "./AgentPolicy-BqDoSXO6.mjs";
13
- import { E as RunDispositionDeclaration, _ as InstructionSource, c as Definition, m as InputPromptSource, n as Any, r as AnyDefinition, t as Agent_d_exports, y as ModelServices } from "./Agent-D9cXqfF3.mjs";
13
+ import { E as RunDispositionDeclaration, _ as InstructionSource, c as Definition, m as InputPromptSource, n as Any, r as AnyDefinition, t as Agent_d_exports, y as ModelServices } from "./Agent-BWhD4Dvu.mjs";
14
14
  import { t as RunPolicyUsage } from "./RunPolicyUsage-ClZxyR46.mjs";
15
15
  import { c as WorkerError, f as WorkerRef, n as AssignmentTerminal } from "./Worker-fwWkBg12.mjs";
16
- import { G as RunToolAuthorization, O as RunCostEstimator, h as RunApprovalHook, x as RunContextPreparation } from "./RunOptions-CSBsSj0X.mjs";
16
+ import { G as RunToolAuthorization, O as RunCostEstimator, h as RunApprovalHook, x as RunContextPreparation } from "./RunOptions-IlEXLG5F.mjs";
17
17
  import { o as MessagingError, r as InputMessage } from "./Messaging-Dkg87ebg.mjs";
18
- import { t as MessagingHost } from "./MessagingHost-CqzpxbGz.mjs";
19
- import "./Messaging-JYYN3oYS.mjs";
20
- import { d as WorkerReportPreparationFailure, f as WorkerReporting, o as SubagentHost } from "./SubagentHost-DQjHFGqH.mjs";
21
- import { p as RuntimeBinding, r as AgentCompletionProjectionRequirements, s as AgentRuntimeRequirements } from "./AgentRuntime-DEDvMkAR.mjs";
18
+ import { t as MessagingHost } from "./MessagingHost-CajpPDPG.mjs";
19
+ import "./Messaging-Dnmk31yq.mjs";
20
+ import { d as WorkerReportPreparationFailure, f as WorkerReporting, o as SubagentHost } from "./SubagentHost-B6f4PBC2.mjs";
21
+ import { p as RuntimeBinding, r as AgentCompletionProjectionRequirements, s as AgentRuntimeRequirements } from "./AgentRuntime-B4kIzmSF.mjs";
22
22
  import { $ as ToolCallPrepared, A as ProducerId, I as RunCompleted, J as SubmissionSettledRecord, M as RecordId, O as PersistedJson, T as ModelResponseRecorded, V as SettlementFailureDiagnostic, a as BatchId, ct as WorkerAdmission, d as CanonicalSequence, dt as WorkerInputRequested, f as CompactionCreated, g as DeploymentId, h as DefinitionDigests, j as RecordEnvelope, l as CanonicalRecordEnvelope, m as DefinitionDigestInput, nt as ToolCallSettled, s as CanonicalBatch } from "./Records-B5GFWCpn.mjs";
23
23
  import { t as DigestError } from "./Digest-U69rDHuO.mjs";
24
24
  import { n as DurableRuntimeFailpoint, r as DurableRuntimeFailpointError } from "./DurableFailpoint-Cnr3wx1L.mjs";
@@ -3234,4 +3234,4 @@ declare const RetryRefused_base: Schema.Class<RetryRefused, Schema.TaggedStruct<
3234
3234
  declare class RetryRefused extends RetryRefused_base {}
3235
3235
  //#endregion
3236
3236
  export { RepairSubagentStartLink as $, subagentStartedRecordId as $i, DurableApprovalFailure as $n, ThreadRecoveryCheckpoints as $r, ParentLinkage as $t, AwaitChildSettlement as A, ResolvedBinding as Aa, firstWorkerInputRecordId as Ai, SuspensionReason as An, CheckpointRejected as Ar, ChildReservationConflict as At, MarkUnknown as B, runCompletionDigest as Bi, settlementFailureFromRecord as Bn, ThreadExport as Br, InputAppliedMarker as Bt, renderRecoveryExplanation as C, AgentAttemptContext as Ca, TurnCommitInput as Ci, SubmissionLookupByKey as Cn, isolateRecovery as Cr, ApprovalDecisionIntent as Ct, ApplyUnknownResolutions as D, DurableWorkerBinding as Da, childThreadIdFor as Di, SubmissionWorkItem as Dn, threadCreatedRecordId as Dr, ChildAttachmentSnapshot as Dt, ApplyJoinAccounting as E, DurableBindingFailure as Ea, childIdempotencyKeyFor as Ei, SubmissionState as En, threadCreatedBatchId as Er, BeginChildBudgetReleaseRequest as Et, CompleteMaterialization as F, peerMessageRecordId as Fi, UnknownResolutionIntent as Fn, SaveCheckpointRequest as Fr, Claim as Ft, PropagateChildAbort as G, runStartedRecordId as Gi, submissionSettlementBatchId as Gn, ThreadNotMaterialized as Gr, MarkInputAppliedRequest as Gt, OpenDelegationCallEvidence as H, runDurationRecordId as Hi, submissionAbortRecordId as Hn, ThreadIdentity as Hr, JoiningClaim as Ht, DeclaredPendingBatchEvidence as I, projectRunJournal as Ii, WaitingChild as In, SaveRecoveryCheckpointRequest as Ir, ClaimHandoff as It, Recovery_d_exports as J, subagentLineageBatchId as Ji, workerTerminalFromRecord as Jn, ThreadOutstandingRequest as Jr, MarkUnknownRequest as Jt, RecoveryDecision as K, subagentJoinBatchId as Ki, submissionSettlementId as Kn, ThreadObservation as Kr, MarkJoinedRequest as Kt, DelegationAdmissionEvidence as L, projectRunJournalStream as Li, WaitingForChildSuspension as Ln, SelectedThreadRead as Lr, ClaimJoiningRequest as Lt, AwaitParentEstablishment as M, compileRegistrations as Ma, modelResponseInterruptedBatchId as Mi, UnknownResolution as Mn, FencedAppendRequest as Mr, ChildReservationStatus as Mt, AwaitUnknownResolution as N, definitionDigestsEqual as Na, modelResponseInterruptedRecordId as Ni, UnknownResolutionCommand as Nn, LoadCheckpointRequest as Nr, ChildSettledNotification as Nt, AwaitApprovalDecision as O, ExecutableAgentBinding as Oa, compactionBatchId as Oi, SuspendRequest as On, AppendConflict as Or, ChildBudgetReservationRequest as Ot, CompleteChildAdmission as P, modelResponseRecordId as Pi, UnknownResolutionConflict as Pn, MAX_THREAD_EXPORT_RECORDS as Pr, ChildSettledOutcome as Pt, RepairReadiness as Q, subagentStartedBatchId as Qi, DurableAgentRuntime_d_exports as Qn, ThreadRecordRequest as Qr, OwnershipToken as Qt, EnsureWaitingForChild as R, promptFromCanonicalRecords as Ri, WorkerLedgerState as Rn, ThreadCheckpoint as Rr, ClaimRequest as Rt, recoveryDecisionMeaning as S, AgentRegistration_d_exports as Sa, RunJournal_d_exports as Si, SubmissionLookupById as Sn, childReservationIdFor as Sr, ApprovalDecisionCommand as St, ApplyInput as T, BindingUnavailable as Ta, approvalDecisionBatchId as Ti, SubmissionSnapshot as Tn, recoveryRepairRecordId as Tr, AttachChildToReservationRequest as Tt, OpenToolCallEvidence as U, runIdForSubmission as Ui, submissionInputBatchId as Un, ThreadIdentityRequest as Ur, LedgerCapabilities as Ut, NoAction as V, runDurationBatchId as Vi, submissionAbortBatchId as Vn, ThreadExportRequest as Vr, JoinSnapshot as Vt, PendingApprovalEvidence as W, runStartedBatchId as Wi, submissionInputRecordId as Wn, ThreadMaterialization as Wr, LedgerError as Wt, RepairInputMarker as X, subagentRequestedBatchId as Xi, DurableAbortFailure as Xn, ThreadRead as Xr, OwnershipRenewal as Xt, ReleaseOrphanChildReservation as Y, subagentLineageRecordId as Yi, ApprovalSuspensionError as Yn, ThreadPeerCountRequest as Yr, OwnershipLost as Yt, RepairJoinMarker as Z, subagentRequestedRecordId as Zi, DurableAgentRuntime as Zn, ThreadReadRequest as Zr, OwnershipSnapshot as Zt, RetryCommand as _, turnResultsBatch as _a, SubmissionStatus_d_exports as _i, SubmissionAdmissionFence as _n, RecoveryBlocked as _r, AdmissionPolicyError as _t, IntegrityCheck as a, toolCallResultBatchId as aa, ThreadStoreFailure as ai, ReservedChildBudget as an, DurableObserveOptions as ar, SettleAborted as at, obligationSeverityOf as b, workerOriginRecordId as ba, RunJournalProjection as bi, SubmissionLedger_d_exports as bn, RecoverySweepOptions as br, AdmissionResult as bt, IntegrityReport as c, toolStepSettledBatchId as ca, ThreadTailRequest as ci, ResolutionCompletedWithResult as cn, DurableRetryFailure as cr, AbortCommand as ct, ObligationReport as d, turnBatchId as da, getRunInput as di, RevertJoiningRequest as dn, DurableSubmitAgent as dr, AdmissionAdmitted as dt, toolApprovalDecisionRecordId as ea, ThreadRunInputRequest as ei, RecoverySnapshot as en, DurableApprovalResolver as er, ResumeFromTurnBoundary as et, ObligationSeverity as f, turnCanonicalBatch as fa, readOutstanding as fi, Settlement as fn, DurableSubmitFailure as fr, AdmissionConflict as ft, RecoveryExplanation as g, turnResponseBatchId as ga, SubmissionStatus as gi, SettlementReservationSnapshot as gn, DurableWorkerRequirements as gr, AdmissionNotAdmitted as gt, RecoveryDisposition as h, turnResponseBatch as ha, SettledSubmission as hi, SettlementReservation as hn, DurableWorkerFailure as hr, AdmissionIndeterminate as ht, ExplainedUnknownCall as i, toolCallResolvedRecordId as ia, ThreadStoreError as ii, RenewOwnershipRequest as in, DurableObligationFailure as ir, RevertJoining as it, AwaitHostSettlement as j, compileBindingContracts as ja, markUnknownBatchId as ji, SuspensionSnapshot as jn, FenceRejected as jr, ChildReservationId as jt, AwaitChildAdmissionResolution as k, ReplayVersions as ka, compactionRecordId as ki, SuspensionOutcome as kn, AppendResult as kr, ChildBudgetReservationSnapshot as kt, ObligationBlockedOn as l, toolStepSettledRecordId as la, ThreadWorkerStateRequest as li, ResolutionNeverHappened as ln, DurableRuntimeConfig as lr, AbortIntent as lt, RECOVERY_DECISION_MEANINGS as m, turnPreparedBatchId as ma, PendingSubmission as mi, SettlementFinalization as mn, DurableVerifyFailure as mr, AdmissionGroup as mt, ExplainedEvidence as n, toolCallPreparedRecordId as na, ThreadStore as ni, ReleaseChildBudgetRequest as nn, DurableAwaitFailure as nr, ResumeSuspended as nt, IntegrityCheckName as o, toolCallSettledRecordId as oa, ThreadStore_d_exports as oi, ReservedSettlement as on, DurableProgressFailure as or, SettleJoinedWithHost as ot, ObligationThresholds as p, turnIdForRun as pa, readWorkerState as pi, SettlementConflict as pn, DurableSubmitOptions as pr, AdmissionFence as pt, RecoveryEvidence as q, subagentJoinedRecordId as qi, submissionSettlementRecordId as qn, ThreadOutstanding as qr, MarkReadyRequest as qt, ExplainedSubmission as r, toolCallResolutionBatchId as ra, ThreadStoreDiagnostic as ri, ReleaseOwnershipRequest as rn, DurableExplainFailure as rr, ResumeWaitingParent as rt, IntegrityCheckStatus as s, toolCallUnknownRecordId as sa, ThreadTail as si, ResolutionAbortSubmission as sn, DurableResolveFailure as sr, classifyRecovery as st, Admin_d_exports as t, toolApprovalRequestRecordId as ta, ThreadSelection as ti, RecoverySnapshotRequest as tn, DurableApprovalSuspension as tr, ResumePendingToolBatch as tt, ObligationEntry as u, turnApprovalsBatchId as ua, getRecord as ui, ResolutionSafeToRetry as un, DurableRuntimeConfigOptions as ur, AbortIntentRequest as ut, RetryRefusalReason as v, turnResultsBatchId as va, JournalBoundary as vi, SubmissionLedger as vn, RecoveryFailure as vr, AdmissionRequest as vt, AppendReservedSettlement as w, AgentRegistration as wa, agentUpdateRecordId as wi, SubmissionScheduling as wn, recoveryRepairBatchId as wr, ApprovalPendingSuspension as wt, predictRecoveryDisposition as x, workerReportRecordId as xa, RunJournalUsage as xi, SubmissionLookup as xn, RecoverySweepResult as xr, ApprovalConflict as xt, RetryRefused as y, workerInputRecordId as ya, RunJournalError as yi, SubmissionLedgerFailure as yn, RecoveryReport as yr, AdmissionResolution as yt, FinalizeLedgerFromHistory as z, runCompletedRecordId as zi, WorkerStopCommand as zn, ThreadCheckpoints as zr, DEFAULT_OWNERSHIP_LEASE_DURATION as zt };
3237
- //# sourceMappingURL=Admin-Fx85KT-W.d.mts.map
3237
+ //# sourceMappingURL=Admin-DGZXE5BU.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Agent-1DMSO_Fl.mjs","names":[],"sources":["../src/core/internal/agent-updates.ts","../src/core/Agent.ts"],"sourcesContent":["import { Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { Emitter, UpdateError } from \"../AgentUpdates.ts\";\n\n/** Definition-owned native Tool. Runtime supplies its handler under the same identity. */\nexport const updateTool = <S extends Schema.Top>(schema: S) =>\n Tool.make(\"emit_update\", {\n description:\n \"Emit a structured intermediate update. Success acknowledges acceptance by this Run; \" +\n \"parent delivery and processing are separate. This does not complete the task.\",\n parameters: Schema.Struct({ value: schema }),\n success: Schema.Struct({ emitted: Schema.Literal(true) }),\n failure: UpdateError,\n failureMode: \"return\",\n }).addDependency(Emitter);\n\nexport type UpdateToolkit<\n T extends Toolkit.Any,\n S extends Schema.Top | undefined,\n> = S extends Schema.Top\n ? Toolkit.Toolkit<T[\"tools\"] & { readonly emit_update: ReturnType<typeof updateTool<S>> }>\n : T;\n\nexport const withUpdateTool = (\n toolkit: Toolkit.Any,\n schema: Schema.Top | undefined,\n): Toolkit.Any => {\n if (schema === undefined) return toolkit;\n if (Object.hasOwn(toolkit.tools, \"emit_update\"))\n throw new TypeError(\"emit_update is reserved for Agent updates\");\n\n return Toolkit.make(...Object.values(toolkit.tools), updateTool(schema));\n};\n","import type { Effect, Layer, Option, Schema } from \"effect\";\nimport * as S from \"effect/Schema\";\nimport {\n type AiError,\n type LanguageModel,\n type Model,\n type Prompt,\n Tool,\n type Toolkit,\n} from \"effect/unstable/ai\";\n\nimport type { AgentInputError, AgentOutputError, AgentRunDispositionError } from \"./AgentError.ts\";\nimport { AgentPolicy, type AgentPolicyInput } from \"./AgentPolicy.ts\";\nimport { AgentId } from \"./Identifiers.ts\";\nimport { type UpdateToolkit, withUpdateTool } from \"./internal/agent-updates.ts\";\nimport type { Configuration } from \"./ToolExposure.ts\";\n\n/** Prompt input produced directly or by an Effect that preserves its failure and requirements. */\nexport type InstructionResult<E = never, R = never> =\n | Prompt.RawInput\n | Effect.Effect<Prompt.RawInput, E, R>;\n\n/** Static prompt input or an input-dependent source evaluated once while preparing a run. */\nexport type InstructionSource<Input, E = never, R = never> =\n | Prompt.RawInput\n | ((input: Input) => InstructionResult<E, R>);\n\n/** Definition-owned projection from decoded Agent input to model-visible prompt content. */\nexport type InputPromptSource<Input, E = never, R = never> = (\n input: Input,\n) => InstructionResult<E, R>;\n\n/** Native services needed to execute and identify model calls. */\nexport type ModelServices = LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName;\n\n/**\n * An optional capability on a provided LanguageModel service. The runtime supplies\n * only model-visible task context and eligible Tool descriptions after validating input.\n * The resolver owns retaining one choice per Thread, including across Runs and\n * recovery; it captures client requirements and returns a closed native Layer\n * that the interpreter acquires for the Run. Context hooks may prepare prompts\n * but cannot replace this model through a per-Turn modelCall.\n * Selection failures remain AiError values and all selector/client services stay in R.\n */\nexport interface ModelResolver extends LanguageModel.LanguageModel {\n readonly resolve: (request: {\n readonly threadId: string;\n readonly state: Schema.JsonObject;\n }) => Effect.Effect<Layer.Layer<ModelServices>, AiError.AiError>;\n}\n\n/** Detect the deferred resolver capability on a trusted, host-provided model service. */\nexport const isModelResolver = (model: LanguageModel.LanguageModel): model is ModelResolver =>\n \"resolve\" in model && typeof model.resolve === \"function\";\n\n/** Accepts native model Layers that provide generation and model identity. */\nexport type NativeModel<ModelValue> =\n ModelValue extends Layer.Layer<infer Provides, never, infer _Requires>\n ? ModelServices extends Provides\n ? ModelValue\n : never\n : never;\n\n/** Definition-owned boundary for selecting and validating an application run disposition. */\nexport interface RunDispositionDeclaration<Output, DispositionSchema extends Schema.Top> {\n /**\n * Opt background workers into one retained assignment. The encoded disposition must be\n * Worker.AssignmentDisposition: completed seals the worker, waiting leaves it steerable.\n * Failures and exhausted Runs seal as failed; aborting an active Run seals as cancelled.\n * The worker origin retains this choice. Omission preserves reusable workers.\n */\n readonly workerLifecycle?: \"assignment\" | undefined;\n /** Canonical Schema used to validate and encode the selected disposition. */\n readonly schema: DispositionSchema;\n /** Pure selection from decoded output. `undefined` declares none, except for assignments. */\n readonly fromOutput: (output: Output) => unknown;\n}\n\n/** Values available to a Definition-owned completion Tool projector after canonical decoding. */\nexport interface CompletionProjectionInput<Parameters = unknown, Result = unknown> {\n readonly parameters: Parameters;\n readonly result: Result;\n}\n\n/**\n * One application Tool whose successful result can complete its owning Agent when it is the\n * only application call. Provider-executed calls may accompany it only with terminal results.\n * Mixed, wholly unexecuted application batches are rejected with failed Tool results so the\n * model can correct them within ordinary Run budgets; completed provider results are retained.\n * Missing provider results and invalid pending resumed batches fail closed. The completion\n * designation never permits side-effect replay.\n */\nexport interface CompletionToolDeclaration<\n Parameters = unknown,\n Result = unknown,\n Output = unknown,\n> {\n readonly tool: string;\n /** Require native Tool use on every model Turn and this Tool for final completion. */\n readonly required?: boolean | undefined;\n readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Output;\n}\n\ntype CompletionToolFor<ToolkitValue extends Toolkit.Any, Output> = {\n readonly [Name in keyof ToolkitValue[\"tools\"] & string]: CompletionToolDeclaration<\n Tool.Parameters<ToolkitValue[\"tools\"][Name]>,\n Tool.Success<ToolkitValue[\"tools\"][Name]>,\n Output\n > & { readonly tool: Name };\n}[keyof ToolkitValue[\"tools\"] & string];\n\n/**\n * An ordinary action Tool whose canonical success may satisfy the whole request.\n * Projectors must be pure and deterministic: recovery re-evaluates them. None preserves\n * ordinary continuation; Some is validated as the Agent output. These Tools must be the sole\n * application call; terminal provider results may accompany them. They never receive the\n * required completion Tool's exhaustion allowance.\n */\nexport interface CompletionFromToolDeclaration<\n Parameters = unknown,\n Result = unknown,\n Output = unknown,\n> {\n readonly tool: string;\n readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Option.Option<Output>;\n}\n\ntype CompletionFromToolFor<ToolkitValue extends Toolkit.Any, Output> = {\n readonly [Name in keyof ToolkitValue[\"tools\"] & string]: CompletionFromToolDeclaration<\n Tool.Parameters<ToolkitValue[\"tools\"][Name]>,\n Tool.Success<ToolkitValue[\"tools\"][Name]>,\n Output\n > & { readonly tool: Name };\n}[keyof ToolkitValue[\"tools\"] & string];\n\n/** Immutable, model-agnostic schemas, behavior, tools, and bounds for an agent. */\nexport interface Definition<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n ToolkitValue extends Toolkit.Any,\n RunDispositionValue = undefined,\n InputPromptValue = undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n> {\n /** Stable agent identity; changing it creates a distinct definition identity. */\n readonly id: AgentId;\n /** Canonical Schema for intermediate updates emitted by this Agent. */\n readonly updates?: UpdatesSchema;\n /** Canonical schema used to decode and encode run input. */\n readonly input: InputSchema;\n /** Canonical schema used to decode the final model output. */\n readonly output: OutputSchema;\n /** Instructions evaluated once while preparing each run. */\n readonly instructions: Instructions;\n /** Optional projection from decoded input to model-visible native Effect AI prompt content. */\n readonly inputPrompt?: InputPromptValue | undefined;\n /** Native Effect AI toolkit whose failures and requirements remain visible. */\n readonly toolkit: ToolkitValue;\n readonly toolExposure?: Configuration | undefined;\n /** Finite execution bounds enforced by the runtime. */\n readonly policy: AgentPolicy;\n /** Explicit policy fields, retained so delegated runs can inherit omitted fields. */\n readonly policyOverrides?: Partial<AgentPolicyInput> | undefined;\n /** Optional successful Tool result that projects directly to the Agent output and settles. */\n readonly completion?: CompletionToolDeclaration | undefined;\n readonly completionFromTools?: ReadonlyArray<CompletionFromToolDeclaration> | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\n/** Options for a model-agnostic agent definition. */\nexport interface DefinitionOptions<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n RunDispositionValue extends\n | RunDispositionDeclaration<OutputSchema[\"Type\"], Schema.Top>\n | undefined = undefined,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined =\n undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n> {\n readonly updates?: UpdatesSchema;\n readonly input: InputSchema;\n readonly output: OutputSchema;\n readonly instructions: Instructions;\n readonly inputPrompt?: InputPromptValue | undefined;\n readonly toolkit: ToolkitValue;\n readonly toolExposure?: Configuration | undefined;\n readonly policy?: Partial<AgentPolicyInput> | undefined;\n readonly completion?: CompletionToolFor<ToolkitValue, OutputSchema[\"Type\"]> | undefined;\n readonly completionFromTools?:\n | ReadonlyArray<CompletionFromToolFor<ToolkitValue, OutputSchema[\"Type\"]>>\n | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\ntype AnyDefinitionShape = Definition<\n Schema.Top,\n Schema.Top,\n unknown,\n Toolkit.Any,\n RunDispositionDeclaration<never, Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n>;\n\n/** Immutable pairing of an agent definition with a native model Layer or thread resolver. */\nexport interface Binding<DefinitionValue extends AnyDefinitionShape, ModelValue> {\n readonly definition: DefinitionValue;\n readonly model: NativeModel<ModelValue>;\n}\n\ntype InstructionEffect<Instructions, Input> = Instructions extends (input: Input) => infer Result\n ? Result\n : Instructions;\n\ntype InputPromptEffect<InputPrompt, Input> = InputPrompt extends (input: Input) => infer Result\n ? Result\n : never;\n\ntype EffectError<Value> =\n Value extends Effect.Effect<infer _Success, infer Error, infer _Services> ? Error : never;\n\ntype EffectServices<Value> =\n Value extends Effect.Effect<infer _Success, infer _Error, infer Services> ? Services : never;\n\ntype ModelRequirements<Value> =\n Value extends Layer.Layer<infer _Provides, infer _Error, infer Services> ? Services : never;\n\n/** Constructors and type projections for definitions and runnable model bindings. */\n\n/** Type-erased definition used at generic framework boundaries. */\nexport type AnyDefinition = AnyDefinitionShape;\n\n/** Read-only interpreter program or binding used at inspection and projection boundaries. */\nexport interface Any {\n readonly definition: AnyDefinition;\n readonly model?: unknown;\n}\n\n/** Native Tool configuration for inspection; it does not predict an invocation's outcome. */\nexport const ToolInspection = S.Struct({\n name: S.String,\n failureMode: S.Literals([\"error\", \"return\"]),\n /** False for provider-executed Tools, whose results do not pass through local handlers. */\n requiresHandler: S.Boolean,\n});\n\nexport type ToolInspection = typeof ToolInspection.Type;\n\n/**\n * Inspect registered native Tools in declaration order without acquiring handlers or a Model.\n * This is the full Definition toolkit, before run-specific visibility or exposure filtering.\n * `failureMode` is Effect AI's configured mode, including its `\"error\"` default. Handler-level\n * recovery, programmatic invocation and Subagent containment can change where failures go;\n * consult execution diagnostics for the actual route. No arguments, results or services are read.\n */\nexport const inspectTools = (agent: AnyDefinition | Any): ReadonlyArray<ToolInspection> => {\n const definition = \"definition\" in agent ? agent.definition : agent;\n\n return Object.values(definition.toolkit.tools).map((tool) =>\n ToolInspection.make({\n name: tool.name,\n failureMode: tool.failureMode,\n requiresHandler: !Tool.isProviderDefined(tool) || tool.requiresHandler,\n }),\n );\n};\n\ntype DefinitionOf<AgentValue extends AnyDefinition | Any> = AgentValue extends {\n readonly definition: infer DefinitionValue extends AnyDefinition;\n}\n ? DefinitionValue\n : AgentValue;\n\ntype RunDispositionSchemaOf<DefinitionValue extends AnyDefinition> = [\n Exclude<DefinitionValue[\"runDisposition\"], undefined>,\n] extends [never]\n ? never\n : Exclude<DefinitionValue[\"runDisposition\"], undefined> extends RunDispositionDeclaration<\n never,\n infer DispositionSchema\n >\n ? DispositionSchema\n : never;\n\n/** Literal Agent ID, retained by Agent.make. */\nexport type Name<A extends AnyDefinition | Any> = DefinitionOf<A>[\"id\"] extends AgentId &\n (infer N extends string)\n ? N\n : string;\n\n/** Declared update Schema, or never for Agents without updates. */\nexport type UpdatesSchema<A extends AnyDefinition | Any> = Exclude<\n DefinitionOf<A>[\"updates\"],\n undefined\n>;\n\n/** Decoded intermediate update value. */\nexport type Update<A extends AnyDefinition | Any> = UpdatesSchema<A>[\"Type\"];\n\n/** Decoded input type of a definition or binding. */\nexport type Input<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"input\"][\"Type\"];\n\n/** Encoded input accepted by the primary execution operations. */\nexport type EncodedInput<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"input\"][\"Encoded\"];\n\n/** Decoded output type of a definition or binding. */\nexport type Output<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"output\"][\"Type\"];\n\n/** Input Schema carried by a definition or binding. */\nexport type InputSchema<AgentValue extends AnyDefinition | Any> = DefinitionOf<AgentValue>[\"input\"];\n\n/** Output Schema carried by a definition or binding. */\nexport type OutputSchema<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"output\"];\n\n/** Application run-disposition Schema carried by a definition or binding, or `never`. */\nexport type RunDispositionSchema<AgentValue extends AnyDefinition | Any> = RunDispositionSchemaOf<\n DefinitionOf<AgentValue>\n>;\n\n/** Decoded application run disposition declared by a definition or binding. */\nexport type RunDisposition<AgentValue extends AnyDefinition | Any> = [\n RunDispositionSchema<AgentValue>,\n] extends [never]\n ? never\n : RunDispositionSchema<AgentValue>[\"Type\"];\n\n/** Validation failure admitted only by definitions that declare a run disposition. */\nexport type RunDispositionFailure<AgentValue extends AnyDefinition | Any> = [\n RunDispositionSchemaOf<DefinitionOf<AgentValue>>,\n] extends [never]\n ? never\n : AgentRunDispositionError;\n\n/** Effect AI tool map carried by a definition or binding. */\nexport type Tools<AgentValue extends AnyDefinition | Any> = Toolkit.Tools<\n DefinitionOf<AgentValue>[\"toolkit\"]\n>;\n\ntype ApplicationTools<A extends AnyDefinition> = [UpdatesSchema<A>] extends [never]\n ? Tools<A>\n : Omit<Tools<A>, \"emit_update\">;\n\ntype ToolMapValues<ToolMap extends Record<string, Tool.Any>> = ToolMap extends unknown\n ? ToolMap[keyof ToolMap]\n : never;\n\n/** All possible tools, including keys present in only one definition or binding branch. */\nexport type ToolUnion<AgentValue extends AnyDefinition | Any> = ToolMapValues<Tools<AgentValue>>;\n\n/** Instruction, tool-handler, and Schema services required before a Model is bound. */\nexport type DefinitionRequirements<DefinitionValue extends AnyDefinition> =\n DefinitionValue extends unknown\n ?\n | EffectServices<InstructionEffect<DefinitionValue[\"instructions\"], Input<DefinitionValue>>>\n | EffectServices<InputPromptEffect<DefinitionValue[\"inputPrompt\"], Input<DefinitionValue>>>\n | Tool.HandlersFor<ApplicationTools<DefinitionValue>>\n | Tool.HandlerServices<ToolMapValues<ApplicationTools<DefinitionValue>>>\n // The interpreter canonically re-encodes decoded Tool parameters before recording them.\n | Tool.ParametersSchema<ToolUnion<DefinitionValue>>[\"EncodingServices\"]\n | Tool.SuccessSchema<ToolUnion<DefinitionValue>>[\"DecodingServices\"]\n | DefinitionValue[\"input\"][\"DecodingServices\"]\n | DefinitionValue[\"input\"][\"EncodingServices\"]\n | DefinitionValue[\"output\"][\"DecodingServices\"]\n | DefinitionValue[\"output\"][\"EncodingServices\"]\n | UpdatesSchema<DefinitionValue>[\"DecodingServices\"]\n | UpdatesSchema<DefinitionValue>[\"EncodingServices\"]\n | RunDispositionSchemaOf<DefinitionValue>[\"DecodingServices\"]\n | RunDispositionSchemaOf<DefinitionValue>[\"EncodingServices\"]\n : never;\n\n/** Definition services plus native model services, or a binding's model Layer requirements. */\nexport type Requirements<AgentValue extends AnyDefinition | Any> =\n | DefinitionRequirements<DefinitionOf<AgentValue>>\n | (AgentValue extends { readonly model: infer ModelValue }\n ? ModelRequirements<ModelValue>\n : ModelServices);\n\n// Distribute after unwrapping bindings too: withModel may itself contain a definition union.\ntype DefinitionFailure<DefinitionValue extends AnyDefinition> = DefinitionValue extends unknown\n ?\n | EffectError<InstructionEffect<DefinitionValue[\"instructions\"], Input<DefinitionValue>>>\n | EffectError<InputPromptEffect<DefinitionValue[\"inputPrompt\"], Input<DefinitionValue>>>\n | Tool.HandlerError<ToolUnion<DefinitionValue>>\n : never;\n\n/** Failures from every possible definition, preserving each branch's instruction input type. */\nexport type Failure<AgentValue extends AnyDefinition | Any> =\n | DefinitionFailure<DefinitionOf<AgentValue>>\n | AiError.AiError\n | AgentInputError\n | AgentOutputError\n | RunDispositionFailure<AgentValue>;\n\n/** Validate an agent ID and return a shallowly frozen, model-agnostic definition. */\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n DispositionSchema extends Schema.Top,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly runDisposition: RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>;\n readonly inputPrompt: InputPromptValue;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n InputPromptValue,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n DispositionSchema extends Schema.Top,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n undefined,\n UpdatesSchema\n > & {\n readonly runDisposition: RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>;\n readonly inputPrompt?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n undefined,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n undefined,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly inputPrompt: InputPromptValue;\n readonly runDisposition?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n undefined,\n InputPromptValue,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n undefined,\n undefined,\n UpdatesSchema\n > & {\n readonly inputPrompt?: undefined;\n readonly runDisposition?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n undefined,\n undefined,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make(\n id: string,\n options: {\n readonly updates?: Schema.Top | undefined;\n readonly input: Schema.Top;\n readonly output: Schema.Top;\n readonly instructions: unknown;\n readonly inputPrompt?: unknown;\n readonly toolkit: Toolkit.Any;\n readonly toolExposure?: Configuration | undefined;\n readonly policy?: Partial<AgentPolicyInput> | undefined;\n readonly completion?: CompletionToolDeclaration | undefined;\n readonly completionFromTools?: ReadonlyArray<CompletionFromToolDeclaration> | undefined;\n readonly runDisposition?: RunDispositionDeclaration<never, Schema.Top> | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n },\n): AnyDefinition {\n const completionNames = new Set<string>();\n\n for (const declaration of options.completionFromTools ?? []) {\n if (declaration.tool === options.completion?.tool || completionNames.has(declaration.tool)) {\n throw new Error(`Tool ${declaration.tool} has more than one completion declaration`);\n }\n if (!Object.hasOwn(options.toolkit.tools, declaration.tool)) {\n throw new Error(`Unknown completion Tool ${declaration.tool}`);\n }\n completionNames.add(declaration.tool);\n }\n\n return Object.freeze({\n ...options,\n toolkit: withUpdateTool(options.toolkit, options.updates),\n policy: AgentPolicy.resolve(options.policy),\n policyOverrides: Object.freeze({ ...options.policy }),\n toolExposure:\n options.toolExposure === undefined\n ? undefined\n : Object.freeze({\n ...options.toolExposure,\n initialToolNames: Object.freeze([...(options.toolExposure.initialToolNames ?? [])]),\n }),\n id: S.decodeSync(AgentId)(id),\n metadata: options.metadata === undefined ? undefined : Object.freeze({ ...options.metadata }),\n completion:\n options.completion === undefined ? undefined : Object.freeze({ ...options.completion }),\n completionFromTools:\n options.completionFromTools === undefined\n ? undefined\n : Object.freeze(\n options.completionFromTools.map((declaration) => Object.freeze({ ...declaration })),\n ),\n runDisposition:\n options.runDisposition === undefined\n ? undefined\n : Object.freeze({ ...options.runDisposition }),\n });\n}\n\n/** Bind a native model or thread resolver without acquiring or hiding its requirements. */\nexport const withModel = <DefinitionValue extends AnyDefinition, ModelValue>(\n definition: DefinitionValue,\n model: NativeModel<ModelValue>,\n): Binding<DefinitionValue, ModelValue> =>\n Object.freeze({\n definition,\n model,\n });\n"],"mappings":";;;;;;;;;AAMA,MAAa,cAAoC,WAC/C,KAAK,KAAK,eAAe;CACvB,aACE;CAEF,YAAY,OAAO,OAAO,EAAE,OAAO,OAAO,CAAC;CAC3C,SAAS,OAAO,OAAO,EAAE,SAAS,OAAO,QAAQ,IAAI,EAAE,CAAC;CACxD,SAAS;CACT,aAAa;AACf,CAAC,CAAC,CAAC,cAAc,OAAO;AAS1B,MAAa,kBACX,SACA,WACgB;CAChB,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,IAAI,OAAO,OAAO,QAAQ,OAAO,aAAa,GAC5C,MAAM,IAAI,UAAU,2CAA2C;CAEjE,OAAO,QAAQ,KAAK,GAAG,OAAO,OAAO,QAAQ,KAAK,GAAG,WAAW,MAAM,CAAC;AACzE;;;;;;;;;;;ACmBA,MAAa,mBAAmB,UAC9B,aAAa,SAAS,OAAO,MAAM,YAAY;;AAkMjD,MAAa,iBAAiB,EAAE,OAAO;CACrC,MAAM,EAAE;CACR,aAAa,EAAE,SAAS,CAAC,SAAS,QAAQ,CAAC;;CAE3C,iBAAiB,EAAE;AACrB,CAAC;;;;;;;;AAWD,MAAa,gBAAgB,UAA8D;CACzF,MAAM,aAAa,gBAAgB,QAAQ,MAAM,aAAa;CAE9D,OAAO,OAAO,OAAO,WAAW,QAAQ,KAAK,CAAC,CAAC,KAAK,SAClD,eAAe,KAAK;EAClB,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,iBAAiB,CAAC,KAAK,kBAAkB,IAAI,KAAK,KAAK;CACzD,CAAC,CACH;AACF;AAqQA,SAAgB,KACd,IACA,SAee;CACf,MAAM,kCAAkB,IAAI,IAAY;CAExC,KAAK,MAAM,eAAe,QAAQ,uBAAuB,CAAC,GAAG;EAC3D,IAAI,YAAY,SAAS,QAAQ,YAAY,QAAQ,gBAAgB,IAAI,YAAY,IAAI,GACvF,MAAM,IAAI,MAAM,QAAQ,YAAY,KAAK,0CAA0C;EAErF,IAAI,CAAC,OAAO,OAAO,QAAQ,QAAQ,OAAO,YAAY,IAAI,GACxD,MAAM,IAAI,MAAM,2BAA2B,YAAY,MAAM;EAE/D,gBAAgB,IAAI,YAAY,IAAI;CACtC;CAEA,OAAO,OAAO,OAAO;EACnB,GAAG;EACH,SAAS,eAAe,QAAQ,SAAS,QAAQ,OAAO;EACxD,QAAQ,YAAY,QAAQ,QAAQ,MAAM;EAC1C,iBAAiB,OAAO,OAAO,EAAE,GAAG,QAAQ,OAAO,CAAC;EACpD,cACE,QAAQ,iBAAiB,KAAA,IACrB,KAAA,IACA,OAAO,OAAO;GACZ,GAAG,QAAQ;GACX,kBAAkB,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,oBAAoB,CAAC,CAAE,CAAC;EACpF,CAAC;EACP,IAAI,EAAE,WAAW,OAAO,CAAC,CAAC,EAAE;EAC5B,UAAU,QAAQ,aAAa,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,EAAE,GAAG,QAAQ,SAAS,CAAC;EAC5F,YACE,QAAQ,eAAe,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,EAAE,GAAG,QAAQ,WAAW,CAAC;EACxF,qBACE,QAAQ,wBAAwB,KAAA,IAC5B,KAAA,IACA,OAAO,OACL,QAAQ,oBAAoB,KAAK,gBAAgB,OAAO,OAAO,EAAE,GAAG,YAAY,CAAC,CAAC,CACpF;EACN,gBACE,QAAQ,mBAAmB,KAAA,IACvB,KAAA,IACA,OAAO,OAAO,EAAE,GAAG,QAAQ,eAAe,CAAC;CACnD,CAAC;AACH;;AAGA,MAAa,aACX,YACA,UAEA,OAAO,OAAO;CACZ;CACA;AACF,CAAC"}
1
+ {"version":3,"file":"Agent-1DMSO_Fl.mjs","names":[],"sources":["../src/core/internal/agent-updates.ts","../src/core/Agent.ts"],"sourcesContent":["import { Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { Emitter, UpdateError } from \"../AgentUpdates.ts\";\n\n/** Definition-owned native Tool. Runtime supplies its handler under the same identity. */\nexport const updateTool = <S extends Schema.Top>(schema: S) =>\n Tool.make(\"emit_update\", {\n description:\n \"Emit a structured intermediate update. Success acknowledges acceptance by this Run; \" +\n \"parent delivery and processing are separate. This does not complete the task.\",\n parameters: Schema.Struct({ value: schema }),\n success: Schema.Struct({ emitted: Schema.Literal(true) }),\n failure: UpdateError,\n failureMode: \"return\",\n }).addDependency(Emitter);\n\nexport type UpdateToolkit<\n T extends Toolkit.Any,\n S extends Schema.Top | undefined,\n> = S extends Schema.Top\n ? Toolkit.Toolkit<T[\"tools\"] & { readonly emit_update: ReturnType<typeof updateTool<S>> }>\n : T;\n\nexport const withUpdateTool = (\n toolkit: Toolkit.Any,\n schema: Schema.Top | undefined,\n): Toolkit.Any => {\n if (schema === undefined) return toolkit;\n if (Object.hasOwn(toolkit.tools, \"emit_update\"))\n throw new TypeError(\"emit_update is reserved for Agent updates\");\n\n return Toolkit.make(...Object.values(toolkit.tools), updateTool(schema));\n};\n","import type { Effect, Layer, Option, Schema } from \"effect\";\nimport * as S from \"effect/Schema\";\nimport {\n type AiError,\n type LanguageModel,\n type Model,\n type Prompt,\n Tool,\n type Toolkit,\n} from \"effect/unstable/ai\";\n\nimport type { AgentInputError, AgentOutputError, AgentRunDispositionError } from \"./AgentError.ts\";\nimport { AgentPolicy, type AgentPolicyInput } from \"./AgentPolicy.ts\";\nimport { AgentId } from \"./Identifiers.ts\";\nimport { type UpdateToolkit, withUpdateTool } from \"./internal/agent-updates.ts\";\nimport type { Configuration } from \"./ToolExposure.ts\";\n\n/** Prompt input produced directly or by an Effect that preserves its failure and requirements. */\nexport type InstructionResult<E = never, R = never> =\n | Prompt.RawInput\n | Effect.Effect<Prompt.RawInput, E, R>;\n\n/** Static prompt input or an input-dependent source evaluated once while preparing a run. */\nexport type InstructionSource<Input, E = never, R = never> =\n | Prompt.RawInput\n | ((input: Input) => InstructionResult<E, R>);\n\n/** Definition-owned projection from decoded Agent input to model-visible prompt content. */\nexport type InputPromptSource<Input, E = never, R = never> = (\n input: Input,\n) => InstructionResult<E, R>;\n\n/** Native services needed to execute and identify model calls. */\nexport type ModelServices = LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName;\n\n/**\n * An optional capability on a provided LanguageModel service. The runtime supplies\n * only model-visible task context and eligible Tool descriptions after validating input.\n * The resolver owns retaining one choice per Thread, including across Runs and\n * recovery; it captures client requirements and returns a closed native Layer\n * that the interpreter acquires for the Run. Context hooks may prepare prompts\n * but cannot replace this model through a per-Turn modelCall.\n * Selection failures remain AiError values and all selector/client services stay in R.\n */\nexport interface ModelResolver extends LanguageModel.LanguageModel {\n readonly resolve: (request: {\n readonly threadId: string;\n readonly state: Schema.JsonObject;\n }) => Effect.Effect<Layer.Layer<ModelServices>, AiError.AiError>;\n}\n\n/** Detect the deferred resolver capability on a trusted, host-provided model service. */\nexport const isModelResolver = (model: LanguageModel.LanguageModel): model is ModelResolver =>\n \"resolve\" in model && typeof model.resolve === \"function\";\n\n/** Accepts native model Layers that provide generation and model identity. */\nexport type NativeModel<ModelValue> =\n ModelValue extends Layer.Layer<infer Provides, never, infer _Requires>\n ? ModelServices extends Provides\n ? ModelValue\n : never\n : never;\n\n/** Definition-owned boundary for selecting and validating an application run disposition. */\nexport interface RunDispositionDeclaration<Output, DispositionSchema extends Schema.Top> {\n /**\n * Opt background workers into one retained assignment. The encoded disposition must be\n * Worker.AssignmentDisposition: completed seals the worker, waiting leaves it steerable.\n * Failures and exhausted Runs seal as failed; aborting an active Run seals as cancelled.\n * The worker origin retains this choice. Omission preserves reusable workers.\n */\n readonly workerLifecycle?: \"assignment\" | undefined;\n /** Canonical Schema used to validate and encode the selected disposition. */\n readonly schema: DispositionSchema;\n /** Pure selection from decoded output. `undefined` declares none, except for assignments. */\n readonly fromOutput: (output: Output) => unknown;\n}\n\n/** Values available to a Definition-owned completion Tool projector after canonical decoding. */\nexport interface CompletionProjectionInput<Parameters = unknown, Result = unknown> {\n readonly parameters: Parameters;\n readonly result: Result;\n}\n\n/**\n * One application Tool whose successful result can complete its owning Agent when it is the\n * only application call. Provider-executed calls may accompany it only with terminal results.\n * Mixed, wholly unexecuted application batches are rejected with failed Tool results so the\n * model can correct them within ordinary Run budgets; completed provider results are retained.\n * Missing provider results and invalid pending resumed batches fail closed. The completion\n * designation never permits side-effect replay.\n */\nexport interface CompletionToolDeclaration<\n Parameters = unknown,\n Result = unknown,\n Output = unknown,\n> {\n readonly tool: string;\n /** Require native Tool use on every model Turn and this Tool for final completion. */\n readonly required?: boolean | undefined;\n readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Output;\n}\n\ntype CompletionToolFor<ToolkitValue extends Toolkit.Any, Output> = {\n readonly [Name in keyof ToolkitValue[\"tools\"] & string]: CompletionToolDeclaration<\n Tool.Parameters<ToolkitValue[\"tools\"][Name]>,\n Tool.Success<ToolkitValue[\"tools\"][Name]>,\n Output\n > & { readonly tool: Name };\n}[keyof ToolkitValue[\"tools\"] & string];\n\n/**\n * An ordinary action Tool whose canonical success may satisfy the whole request.\n * Projectors must be pure and deterministic: recovery re-evaluates them. None preserves\n * ordinary continuation; Some is validated as the Agent output. These Tools must be the sole\n * application call; terminal provider results may accompany them. They never receive the\n * required completion Tool's exhaustion allowance.\n */\nexport interface CompletionFromToolDeclaration<\n Parameters = unknown,\n Result = unknown,\n Output = unknown,\n> {\n readonly tool: string;\n readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Option.Option<Output>;\n}\n\ntype CompletionFromToolFor<ToolkitValue extends Toolkit.Any, Output> = {\n readonly [Name in keyof ToolkitValue[\"tools\"] & string]: CompletionFromToolDeclaration<\n Tool.Parameters<ToolkitValue[\"tools\"][Name]>,\n Tool.Success<ToolkitValue[\"tools\"][Name]>,\n Output\n > & { readonly tool: Name };\n}[keyof ToolkitValue[\"tools\"] & string];\n\n/** Immutable, model-agnostic schemas, behavior, tools, and bounds for an agent. */\nexport interface Definition<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n ToolkitValue extends Toolkit.Any,\n RunDispositionValue = undefined,\n InputPromptValue = undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n> {\n /** Stable agent identity; changing it creates a distinct definition identity. */\n readonly id: AgentId;\n /** Canonical Schema for intermediate updates emitted by this Agent. */\n readonly updates?: UpdatesSchema;\n /** Canonical schema used to decode and encode run input. */\n readonly input: InputSchema;\n /** Canonical schema used to decode the final model output. */\n readonly output: OutputSchema;\n /**\n * Evaluated once while preparing each Run. Outgoing system messages form a leading block;\n * exact repeats (including provider options) keep their last occurrence. Stored history is unchanged.\n */\n readonly instructions: Instructions;\n /** Optional projection from decoded input to model-visible native Effect AI prompt content. */\n readonly inputPrompt?: InputPromptValue | undefined;\n /** Native Effect AI toolkit whose failures and requirements remain visible. */\n readonly toolkit: ToolkitValue;\n readonly toolExposure?: Configuration | undefined;\n /** Finite execution bounds enforced by the runtime. */\n readonly policy: AgentPolicy;\n /** Explicit policy fields, retained so delegated runs can inherit omitted fields. */\n readonly policyOverrides?: Partial<AgentPolicyInput> | undefined;\n /** Optional successful Tool result that projects directly to the Agent output and settles. */\n readonly completion?: CompletionToolDeclaration | undefined;\n readonly completionFromTools?: ReadonlyArray<CompletionFromToolDeclaration> | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\n/** Options for a model-agnostic agent definition. */\nexport interface DefinitionOptions<\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n RunDispositionValue extends\n | RunDispositionDeclaration<OutputSchema[\"Type\"], Schema.Top>\n | undefined = undefined,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined =\n undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n> {\n readonly updates?: UpdatesSchema;\n readonly input: InputSchema;\n readonly output: OutputSchema;\n readonly instructions: Instructions;\n readonly inputPrompt?: InputPromptValue | undefined;\n readonly toolkit: ToolkitValue;\n readonly toolExposure?: Configuration | undefined;\n readonly policy?: Partial<AgentPolicyInput> | undefined;\n readonly completion?: CompletionToolFor<ToolkitValue, OutputSchema[\"Type\"]> | undefined;\n readonly completionFromTools?:\n | ReadonlyArray<CompletionFromToolFor<ToolkitValue, OutputSchema[\"Type\"]>>\n | undefined;\n readonly runDisposition?: RunDispositionValue | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\ntype AnyDefinitionShape = Definition<\n Schema.Top,\n Schema.Top,\n unknown,\n Toolkit.Any,\n RunDispositionDeclaration<never, Schema.Top> | undefined,\n unknown,\n Schema.Top | undefined\n>;\n\n/** Immutable pairing of an agent definition with a native model Layer or thread resolver. */\nexport interface Binding<DefinitionValue extends AnyDefinitionShape, ModelValue> {\n readonly definition: DefinitionValue;\n readonly model: NativeModel<ModelValue>;\n}\n\ntype InstructionEffect<Instructions, Input> = Instructions extends (input: Input) => infer Result\n ? Result\n : Instructions;\n\ntype InputPromptEffect<InputPrompt, Input> = InputPrompt extends (input: Input) => infer Result\n ? Result\n : never;\n\ntype EffectError<Value> =\n Value extends Effect.Effect<infer _Success, infer Error, infer _Services> ? Error : never;\n\ntype EffectServices<Value> =\n Value extends Effect.Effect<infer _Success, infer _Error, infer Services> ? Services : never;\n\ntype ModelRequirements<Value> =\n Value extends Layer.Layer<infer _Provides, infer _Error, infer Services> ? Services : never;\n\n/** Constructors and type projections for definitions and runnable model bindings. */\n\n/** Type-erased definition used at generic framework boundaries. */\nexport type AnyDefinition = AnyDefinitionShape;\n\n/** Read-only interpreter program or binding used at inspection and projection boundaries. */\nexport interface Any {\n readonly definition: AnyDefinition;\n readonly model?: unknown;\n}\n\n/** Native Tool configuration for inspection; it does not predict an invocation's outcome. */\nexport const ToolInspection = S.Struct({\n name: S.String,\n failureMode: S.Literals([\"error\", \"return\"]),\n /** False for provider-executed Tools, whose results do not pass through local handlers. */\n requiresHandler: S.Boolean,\n});\n\nexport type ToolInspection = typeof ToolInspection.Type;\n\n/**\n * Inspect registered native Tools in declaration order without acquiring handlers or a Model.\n * This is the full Definition toolkit, before run-specific visibility or exposure filtering.\n * `failureMode` is Effect AI's configured mode, including its `\"error\"` default. Handler-level\n * recovery, programmatic invocation and Subagent containment can change where failures go;\n * consult execution diagnostics for the actual route. No arguments, results or services are read.\n */\nexport const inspectTools = (agent: AnyDefinition | Any): ReadonlyArray<ToolInspection> => {\n const definition = \"definition\" in agent ? agent.definition : agent;\n\n return Object.values(definition.toolkit.tools).map((tool) =>\n ToolInspection.make({\n name: tool.name,\n failureMode: tool.failureMode,\n requiresHandler: !Tool.isProviderDefined(tool) || tool.requiresHandler,\n }),\n );\n};\n\ntype DefinitionOf<AgentValue extends AnyDefinition | Any> = AgentValue extends {\n readonly definition: infer DefinitionValue extends AnyDefinition;\n}\n ? DefinitionValue\n : AgentValue;\n\ntype RunDispositionSchemaOf<DefinitionValue extends AnyDefinition> = [\n Exclude<DefinitionValue[\"runDisposition\"], undefined>,\n] extends [never]\n ? never\n : Exclude<DefinitionValue[\"runDisposition\"], undefined> extends RunDispositionDeclaration<\n never,\n infer DispositionSchema\n >\n ? DispositionSchema\n : never;\n\n/** Literal Agent ID, retained by Agent.make. */\nexport type Name<A extends AnyDefinition | Any> = DefinitionOf<A>[\"id\"] extends AgentId &\n (infer N extends string)\n ? N\n : string;\n\n/** Declared update Schema, or never for Agents without updates. */\nexport type UpdatesSchema<A extends AnyDefinition | Any> = Exclude<\n DefinitionOf<A>[\"updates\"],\n undefined\n>;\n\n/** Decoded intermediate update value. */\nexport type Update<A extends AnyDefinition | Any> = UpdatesSchema<A>[\"Type\"];\n\n/** Decoded input type of a definition or binding. */\nexport type Input<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"input\"][\"Type\"];\n\n/** Encoded input accepted by the primary execution operations. */\nexport type EncodedInput<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"input\"][\"Encoded\"];\n\n/** Decoded output type of a definition or binding. */\nexport type Output<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"output\"][\"Type\"];\n\n/** Input Schema carried by a definition or binding. */\nexport type InputSchema<AgentValue extends AnyDefinition | Any> = DefinitionOf<AgentValue>[\"input\"];\n\n/** Output Schema carried by a definition or binding. */\nexport type OutputSchema<AgentValue extends AnyDefinition | Any> =\n DefinitionOf<AgentValue>[\"output\"];\n\n/** Application run-disposition Schema carried by a definition or binding, or `never`. */\nexport type RunDispositionSchema<AgentValue extends AnyDefinition | Any> = RunDispositionSchemaOf<\n DefinitionOf<AgentValue>\n>;\n\n/** Decoded application run disposition declared by a definition or binding. */\nexport type RunDisposition<AgentValue extends AnyDefinition | Any> = [\n RunDispositionSchema<AgentValue>,\n] extends [never]\n ? never\n : RunDispositionSchema<AgentValue>[\"Type\"];\n\n/** Validation failure admitted only by definitions that declare a run disposition. */\nexport type RunDispositionFailure<AgentValue extends AnyDefinition | Any> = [\n RunDispositionSchemaOf<DefinitionOf<AgentValue>>,\n] extends [never]\n ? never\n : AgentRunDispositionError;\n\n/** Effect AI tool map carried by a definition or binding. */\nexport type Tools<AgentValue extends AnyDefinition | Any> = Toolkit.Tools<\n DefinitionOf<AgentValue>[\"toolkit\"]\n>;\n\ntype ApplicationTools<A extends AnyDefinition> = [UpdatesSchema<A>] extends [never]\n ? Tools<A>\n : Omit<Tools<A>, \"emit_update\">;\n\ntype ToolMapValues<ToolMap extends Record<string, Tool.Any>> = ToolMap extends unknown\n ? ToolMap[keyof ToolMap]\n : never;\n\n/** All possible tools, including keys present in only one definition or binding branch. */\nexport type ToolUnion<AgentValue extends AnyDefinition | Any> = ToolMapValues<Tools<AgentValue>>;\n\n/** Instruction, tool-handler, and Schema services required before a Model is bound. */\nexport type DefinitionRequirements<DefinitionValue extends AnyDefinition> =\n DefinitionValue extends unknown\n ?\n | EffectServices<InstructionEffect<DefinitionValue[\"instructions\"], Input<DefinitionValue>>>\n | EffectServices<InputPromptEffect<DefinitionValue[\"inputPrompt\"], Input<DefinitionValue>>>\n | Tool.HandlersFor<ApplicationTools<DefinitionValue>>\n | Tool.HandlerServices<ToolMapValues<ApplicationTools<DefinitionValue>>>\n // The interpreter canonically re-encodes decoded Tool parameters before recording them.\n | Tool.ParametersSchema<ToolUnion<DefinitionValue>>[\"EncodingServices\"]\n | Tool.SuccessSchema<ToolUnion<DefinitionValue>>[\"DecodingServices\"]\n | DefinitionValue[\"input\"][\"DecodingServices\"]\n | DefinitionValue[\"input\"][\"EncodingServices\"]\n | DefinitionValue[\"output\"][\"DecodingServices\"]\n | DefinitionValue[\"output\"][\"EncodingServices\"]\n | UpdatesSchema<DefinitionValue>[\"DecodingServices\"]\n | UpdatesSchema<DefinitionValue>[\"EncodingServices\"]\n | RunDispositionSchemaOf<DefinitionValue>[\"DecodingServices\"]\n | RunDispositionSchemaOf<DefinitionValue>[\"EncodingServices\"]\n : never;\n\n/** Definition services plus native model services, or a binding's model Layer requirements. */\nexport type Requirements<AgentValue extends AnyDefinition | Any> =\n | DefinitionRequirements<DefinitionOf<AgentValue>>\n | (AgentValue extends { readonly model: infer ModelValue }\n ? ModelRequirements<ModelValue>\n : ModelServices);\n\n// Distribute after unwrapping bindings too: withModel may itself contain a definition union.\ntype DefinitionFailure<DefinitionValue extends AnyDefinition> = DefinitionValue extends unknown\n ?\n | EffectError<InstructionEffect<DefinitionValue[\"instructions\"], Input<DefinitionValue>>>\n | EffectError<InputPromptEffect<DefinitionValue[\"inputPrompt\"], Input<DefinitionValue>>>\n | Tool.HandlerError<ToolUnion<DefinitionValue>>\n : never;\n\n/** Failures from every possible definition, preserving each branch's instruction input type. */\nexport type Failure<AgentValue extends AnyDefinition | Any> =\n | DefinitionFailure<DefinitionOf<AgentValue>>\n | AiError.AiError\n | AgentInputError\n | AgentOutputError\n | RunDispositionFailure<AgentValue>;\n\n/** Validate an agent ID and return a shallowly frozen, model-agnostic definition. */\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n DispositionSchema extends Schema.Top,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly runDisposition: RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>;\n readonly inputPrompt: InputPromptValue;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n InputPromptValue,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n DispositionSchema extends Schema.Top,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n undefined,\n UpdatesSchema\n > & {\n readonly runDisposition: RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>;\n readonly inputPrompt?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n RunDispositionDeclaration<OutputSchema[\"Type\"], DispositionSchema>,\n undefined,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n undefined,\n InputPromptValue,\n UpdatesSchema\n > & {\n readonly inputPrompt: InputPromptValue;\n readonly runDisposition?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n undefined,\n InputPromptValue,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make<\n const Name extends string,\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions extends InstructionSource<InputSchema[\"Type\"], unknown, unknown>,\n ToolkitValue extends Toolkit.Any,\n UpdatesSchema extends Schema.Top | undefined = undefined,\n>(\n id: Name,\n options: DefinitionOptions<\n InputSchema,\n OutputSchema,\n Instructions,\n ToolkitValue,\n undefined,\n undefined,\n UpdatesSchema\n > & {\n readonly inputPrompt?: undefined;\n readonly runDisposition?: undefined;\n },\n): Definition<\n InputSchema,\n OutputSchema,\n Instructions,\n UpdateToolkit<ToolkitValue, NoInfer<UpdatesSchema>>,\n undefined,\n undefined,\n NoInfer<UpdatesSchema>\n> & { readonly id: AgentId & Name };\n\nexport function make(\n id: string,\n options: {\n readonly updates?: Schema.Top | undefined;\n readonly input: Schema.Top;\n readonly output: Schema.Top;\n readonly instructions: unknown;\n readonly inputPrompt?: unknown;\n readonly toolkit: Toolkit.Any;\n readonly toolExposure?: Configuration | undefined;\n readonly policy?: Partial<AgentPolicyInput> | undefined;\n readonly completion?: CompletionToolDeclaration | undefined;\n readonly completionFromTools?: ReadonlyArray<CompletionFromToolDeclaration> | undefined;\n readonly runDisposition?: RunDispositionDeclaration<never, Schema.Top> | undefined;\n readonly description?: string | undefined;\n readonly metadata?: Readonly<Record<string, string>> | undefined;\n },\n): AnyDefinition {\n const completionNames = new Set<string>();\n\n for (const declaration of options.completionFromTools ?? []) {\n if (declaration.tool === options.completion?.tool || completionNames.has(declaration.tool)) {\n throw new Error(`Tool ${declaration.tool} has more than one completion declaration`);\n }\n if (!Object.hasOwn(options.toolkit.tools, declaration.tool)) {\n throw new Error(`Unknown completion Tool ${declaration.tool}`);\n }\n completionNames.add(declaration.tool);\n }\n\n return Object.freeze({\n ...options,\n toolkit: withUpdateTool(options.toolkit, options.updates),\n policy: AgentPolicy.resolve(options.policy),\n policyOverrides: Object.freeze({ ...options.policy }),\n toolExposure:\n options.toolExposure === undefined\n ? undefined\n : Object.freeze({\n ...options.toolExposure,\n initialToolNames: Object.freeze([...(options.toolExposure.initialToolNames ?? [])]),\n }),\n id: S.decodeSync(AgentId)(id),\n metadata: options.metadata === undefined ? undefined : Object.freeze({ ...options.metadata }),\n completion:\n options.completion === undefined ? undefined : Object.freeze({ ...options.completion }),\n completionFromTools:\n options.completionFromTools === undefined\n ? undefined\n : Object.freeze(\n options.completionFromTools.map((declaration) => Object.freeze({ ...declaration })),\n ),\n runDisposition:\n options.runDisposition === undefined\n ? undefined\n : Object.freeze({ ...options.runDisposition }),\n });\n}\n\n/** Bind a native model or thread resolver without acquiring or hiding its requirements. */\nexport const withModel = <DefinitionValue extends AnyDefinition, ModelValue>(\n definition: DefinitionValue,\n model: NativeModel<ModelValue>,\n): Binding<DefinitionValue, ModelValue> =>\n Object.freeze({\n definition,\n model,\n });\n"],"mappings":";;;;;;;;;AAMA,MAAa,cAAoC,WAC/C,KAAK,KAAK,eAAe;CACvB,aACE;CAEF,YAAY,OAAO,OAAO,EAAE,OAAO,OAAO,CAAC;CAC3C,SAAS,OAAO,OAAO,EAAE,SAAS,OAAO,QAAQ,IAAI,EAAE,CAAC;CACxD,SAAS;CACT,aAAa;AACf,CAAC,CAAC,CAAC,cAAc,OAAO;AAS1B,MAAa,kBACX,SACA,WACgB;CAChB,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,IAAI,OAAO,OAAO,QAAQ,OAAO,aAAa,GAC5C,MAAM,IAAI,UAAU,2CAA2C;CAEjE,OAAO,QAAQ,KAAK,GAAG,OAAO,OAAO,QAAQ,KAAK,GAAG,WAAW,MAAM,CAAC;AACzE;;;;;;;;;;;ACmBA,MAAa,mBAAmB,UAC9B,aAAa,SAAS,OAAO,MAAM,YAAY;;AAqMjD,MAAa,iBAAiB,EAAE,OAAO;CACrC,MAAM,EAAE;CACR,aAAa,EAAE,SAAS,CAAC,SAAS,QAAQ,CAAC;;CAE3C,iBAAiB,EAAE;AACrB,CAAC;;;;;;;;AAWD,MAAa,gBAAgB,UAA8D;CACzF,MAAM,aAAa,gBAAgB,QAAQ,MAAM,aAAa;CAE9D,OAAO,OAAO,OAAO,WAAW,QAAQ,KAAK,CAAC,CAAC,KAAK,SAClD,eAAe,KAAK;EAClB,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,iBAAiB,CAAC,KAAK,kBAAkB,IAAI,KAAK,KAAK;CACzD,CAAC,CACH;AACF;AAqQA,SAAgB,KACd,IACA,SAee;CACf,MAAM,kCAAkB,IAAI,IAAY;CAExC,KAAK,MAAM,eAAe,QAAQ,uBAAuB,CAAC,GAAG;EAC3D,IAAI,YAAY,SAAS,QAAQ,YAAY,QAAQ,gBAAgB,IAAI,YAAY,IAAI,GACvF,MAAM,IAAI,MAAM,QAAQ,YAAY,KAAK,0CAA0C;EAErF,IAAI,CAAC,OAAO,OAAO,QAAQ,QAAQ,OAAO,YAAY,IAAI,GACxD,MAAM,IAAI,MAAM,2BAA2B,YAAY,MAAM;EAE/D,gBAAgB,IAAI,YAAY,IAAI;CACtC;CAEA,OAAO,OAAO,OAAO;EACnB,GAAG;EACH,SAAS,eAAe,QAAQ,SAAS,QAAQ,OAAO;EACxD,QAAQ,YAAY,QAAQ,QAAQ,MAAM;EAC1C,iBAAiB,OAAO,OAAO,EAAE,GAAG,QAAQ,OAAO,CAAC;EACpD,cACE,QAAQ,iBAAiB,KAAA,IACrB,KAAA,IACA,OAAO,OAAO;GACZ,GAAG,QAAQ;GACX,kBAAkB,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,oBAAoB,CAAC,CAAE,CAAC;EACpF,CAAC;EACP,IAAI,EAAE,WAAW,OAAO,CAAC,CAAC,EAAE;EAC5B,UAAU,QAAQ,aAAa,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,EAAE,GAAG,QAAQ,SAAS,CAAC;EAC5F,YACE,QAAQ,eAAe,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,EAAE,GAAG,QAAQ,WAAW,CAAC;EACxF,qBACE,QAAQ,wBAAwB,KAAA,IAC5B,KAAA,IACA,OAAO,OACL,QAAQ,oBAAoB,KAAK,gBAAgB,OAAO,OAAO,EAAE,GAAG,YAAY,CAAC,CAAC,CACpF;EACN,gBACE,QAAQ,mBAAmB,KAAA,IACvB,KAAA,IACA,OAAO,OAAO,EAAE,GAAG,QAAQ,eAAe,CAAC;CACnD,CAAC;AACH;;AAGA,MAAa,aACX,YACA,UAEA,OAAO,OAAO;CACZ;CACA;AACF,CAAC"}
@@ -110,7 +110,10 @@ interface Definition<InputSchema extends Schema.Top, OutputSchema extends Schema
110
110
  readonly input: InputSchema;
111
111
  /** Canonical schema used to decode the final model output. */
112
112
  readonly output: OutputSchema;
113
- /** Instructions evaluated once while preparing each run. */
113
+ /**
114
+ * Evaluated once while preparing each Run. Outgoing system messages form a leading block;
115
+ * exact repeats (including provider options) keep their last occurrence. Stored history is unchanged.
116
+ */
114
117
  readonly instructions: Instructions;
115
118
  /** Optional projection from decoded input to model-visible native Effect AI prompt content. */
116
119
  readonly inputPrompt?: InputPromptValue | undefined;
@@ -249,4 +252,4 @@ declare function make<const Name extends string, InputSchema extends Schema.Top,
249
252
  declare const withModel: <DefinitionValue extends AnyDefinition, ModelValue>(definition: DefinitionValue, model: NativeModel<ModelValue>) => Binding<DefinitionValue, ModelValue>;
250
253
  //#endregion
251
254
  export { ToolUnion as A, OutputSchema as C, RunDispositionFailure as D, RunDispositionDeclaration as E, isModelResolver as F, make as I, withModel as L, Update as M, UpdatesSchema as N, RunDispositionSchema as O, inspectTools as P, Output as S, RunDisposition as T, InstructionSource as _, CompletionFromToolDeclaration as a, Name as b, Definition as c, EncodedInput as d, Failure as f, InstructionResult as g, InputSchema as h, Binding as i, Tools as j, ToolInspection as k, DefinitionOptions as l, InputPromptSource as m, Any as n, CompletionProjectionInput as o, Input as p, AnyDefinition as r, CompletionToolDeclaration as s, Agent_d_exports as t, DefinitionRequirements as u, ModelResolver as v, Requirements as w, NativeModel as x, ModelServices as y };
252
- //# sourceMappingURL=Agent-D9cXqfF3.d.mts.map
255
+ //# sourceMappingURL=Agent-BWhD4Dvu.d.mts.map
@@ -8,14 +8,14 @@ import { n as CurrentToolCatalog } from "./ToolExposure-UCN12eCd.mjs";
8
8
  import { s as ToolBroker } from "./ToolBroker-DWs4tZra.mjs";
9
9
  import { a as AgentInputError, c as AgentPolicyError, d as AgentToolAuthorizationDenied, f as ContextBudgetError, m as ModelProtocolError, n as AgentApprovalPending, p as ContextOverflowError, s as AgentOutputError, t as AgentApprovalDenied, u as AgentToolAuthorizationCheckError } from "./AgentError-Bn1ytXRD.mjs";
10
10
  import { t as AgentPolicy } from "./AgentPolicy-BqDoSXO6.mjs";
11
- import { A as ToolUnion, C as OutputSchema, D as RunDispositionFailure, E as RunDispositionDeclaration, N as UpdatesSchema, O as RunDispositionSchema, S as Output, _ as InstructionSource, a as CompletionFromToolDeclaration, c as Definition, d as EncodedInput, f as Failure, m as InputPromptSource, n as Any, r as AnyDefinition, s as CompletionToolDeclaration, t as Agent_d_exports, w as Requirements } from "./Agent-D9cXqfF3.mjs";
11
+ import { A as ToolUnion, C as OutputSchema, D as RunDispositionFailure, E as RunDispositionDeclaration, N as UpdatesSchema, O as RunDispositionSchema, S as Output, _ as InstructionSource, a as CompletionFromToolDeclaration, c as Definition, d as EncodedInput, f as Failure, m as InputPromptSource, n as Any, r as AnyDefinition, s as CompletionToolDeclaration, t as Agent_d_exports, w as Requirements } from "./Agent-BWhD4Dvu.mjs";
12
12
  import { a as WorkerBudgetScope } from "./Worker-fwWkBg12.mjs";
13
13
  import { a as ContextWindow } from "./ContextWindow-DRQ5Mbm2.mjs";
14
14
  import { n as CompactionError } from "./ContextCompactor-WwSIG_Z2.mjs";
15
15
  import { t as DurableStep } from "./DurableStep-Cry_iol4.mjs";
16
- import { B as RunSubagentChildIdentity, H as RunSubagentEstablishRequest, M as RunOptions, S as RunContextPreparationError, W as RunSubagentJoinRequest, i as ChildEstablishStatus, l as ModelUsageAccounting, t as AgentUpdateAcceptance, x as RunContextPreparation } from "./RunOptions-CSBsSj0X.mjs";
17
- import { t as MessagingHost } from "./MessagingHost-CqzpxbGz.mjs";
18
- import { o as SubagentHost } from "./SubagentHost-DQjHFGqH.mjs";
16
+ import { B as RunSubagentChildIdentity, H as RunSubagentEstablishRequest, M as RunOptions, S as RunContextPreparationError, W as RunSubagentJoinRequest, i as ChildEstablishStatus, l as ModelUsageAccounting, t as AgentUpdateAcceptance, x as RunContextPreparation } from "./RunOptions-IlEXLG5F.mjs";
17
+ import { t as MessagingHost } from "./MessagingHost-CajpPDPG.mjs";
18
+ import { o as SubagentHost } from "./SubagentHost-B6f4PBC2.mjs";
19
19
  import { t as RunEventSink } from "./RunEventSink-D5aVhISG.mjs";
20
20
  import { AiError, LanguageModel, Model, Prompt, Tool, Toolkit } from "effect/unstable/ai";
21
21
  import { Cause, Context, Effect, Layer, Option, Schema, Scope, Stream, Tracer } from "effect";
@@ -343,4 +343,4 @@ declare namespace AgentRuntime_d_exports {
343
343
  }
344
344
  //#endregion
345
345
  export { start as A, decodeFinalOutput as C, renderInputPrompt as D, projectCompletionOutput as E, withTerminalDefectEvent as F, stream as M, streamUnknown as N, run as O, streamWithUsageAccountingUnknown as P, ToolCallWaiting as S, projectCompletionFromToolOutput as T, SubagentDurability as _, AgentResultSchema as a, SubagentDurabilityError as b, AgentSpawner as c, DetachedRun as d, EngineProvidedToolServices as f, SpawnedChildRun as g, SpawnRunOptions as h, AgentResult as i, startUnknown as j, runUnknown as k, AgentSpawnerParent as l, SpawnDelegation as m, AgentChildPending as n, AgentRuntimeFailure as o, RuntimeBinding as p, AgentCompletionProjectionRequirements as r, AgentRuntimeRequirements as s, AgentRuntime_d_exports as t, AgentSpawnerService as u, SubagentDurabilityDurable as v, encodeRunDisposition as w, SubagentDurabilityService as x, SubagentDurabilityEphemeral as y };
346
- //# sourceMappingURL=AgentRuntime-DEDvMkAR.d.mts.map
346
+ //# sourceMappingURL=AgentRuntime-B4kIzmSF.d.mts.map
@@ -16,7 +16,7 @@ import { t as MessagingHost } from "./MessagingHost-DfsbMPvq.mjs";
16
16
  import { SubagentHost } from "./engine/SubagentHost.mjs";
17
17
  import { ThreadHistory, ThreadHistoryError } from "./engine/ThreadHistory.mjs";
18
18
  import { n as RunToolVisibility, t as CurrentToolCatalog } from "./ToolExposure-9uF_Yo0T.mjs";
19
- import { n as isTextOutput, r as outputSchemaContract, t as insertOutputContract } from "./output-contract-BC7tjlGw.mjs";
19
+ import { n as outputSchemaContract, r as prepareModelPrompt, t as isTextOutput } from "./output-contract-CANJJGA5.mjs";
20
20
  import { _ as initialCompactionState, b as boundedCanonicalJsonSnapshot, d as collectCoveredMessages, f as contextWindowId, g as evaluateMessageTokenEstimates, h as estimatePromptTokens, s as buildCompactedView, v as isContextOverflowMessage, x as boundedJsonSnapshot } from "./compaction-C2OTceKw.mjs";
21
21
  import { ContextRolloverRequest, ContextRolloverSelection, ContextRolloverTool, ContextWindow, ContextWindowStatus, ModelCallContext } from "./engine/ContextWindow.mjs";
22
22
  import { DurableStep, DurableStepError, getToolExecutionClass } from "./engine/DurableStep.mjs";
@@ -2162,7 +2162,7 @@ const estimateContextTokens = Effect.fn("AgentRuntime.estimateContextTokens")(fu
2162
2162
  const nextContextEstimate = Effect.fn("AgentRuntime.nextContextEstimate")(function* (context, view) {
2163
2163
  const state = context.compaction;
2164
2164
  if (context.lastInputTokens > 0 && state.lastViewLength >= 0 && state.lastViewLength <= view.length) return context.lastInputTokens + context.lastOutputTokens + (yield* estimateContextTokens(view.slice(state.lastViewLength)));
2165
- return yield* estimateContextTokens(view);
2165
+ return yield* estimateContextTokens(prepareModelPrompt(Prompt.fromMessages(view), void 0).content);
2166
2166
  });
2167
2167
  const snapshotCompactionMessages = Effect.fnUntraced(function* (messages) {
2168
2168
  return yield* Effect.try({
@@ -2922,7 +2922,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
2922
2922
  let toolSchemaTokens = yield* estimateToolSchemaTokens;
2923
2923
  const canonicalDecorationPromptTokens = !admissionRequired ? 0 : outputContractTokens + (yield* estimateCallTokens(canonicalDecoration.content));
2924
2924
  const canonicalDecorationTokens = () => toolSchemaTokens + canonicalDecorationPromptTokens;
2925
- const estimateSourceContext = (view) => options.context === void 0 && options.transientContext === void 0 ? nextContextEstimate(context, view) : estimateCallTokens(view);
2925
+ const estimateSourceContext = (view) => options.context === void 0 && options.transientContext === void 0 ? nextContextEstimate(context, view) : estimateCallTokens(prepareModelPrompt(Prompt.fromMessages(view), void 0).content);
2926
2926
  let prepared = buildCompactedView(modelContext.prompt.content, context.compaction);
2927
2927
  let sourceTokens;
2928
2928
  const preparedSourceTokens = Effect.suspend(() => sourceTokens === void 0 ? estimateSourceContext(prepared).pipe(Effect.tap((tokens) => Effect.sync(() => {
@@ -3092,7 +3092,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
3092
3092
  }));
3093
3093
  }
3094
3094
  context.toolExposure = snapshot;
3095
- const providerPrompt = outputContract._tag !== "rendered" ? outgoing : insertOutputContract(outgoing, outputContract.part);
3095
+ const providerPrompt = prepareModelPrompt(outgoing, outputContract._tag === "rendered" ? outputContract.part : void 0);
3096
3096
  return yield* estimateCallTokens(providerPrompt.content).pipe(Effect.map((tokens) => tokens + toolSchemaTokens), Effect.tap((estimatedTokens) => contextTokenLimit !== void 0 && (options.context !== void 0 || options.transientContext !== void 0) && estimatedTokens > contextTokenLimit ? ContextBudgetError.make({
3097
3097
  message: `Prepared context could not fit the next model prompt inside the ${contextTokenLimit} token context target`,
3098
3098
  estimatedTokens,
@@ -4736,4 +4736,4 @@ var AgentRuntime_exports = /* @__PURE__ */ __exportAll({
4736
4736
  //#endregion
4737
4737
  export { stream as _, SubagentDurability as a, withTerminalDefectEvent as b, decodeFinalOutput as c, projectCompletionOutput as d, renderInputPrompt as f, startUnknown as g, start as h, AgentSpawner as i, encodeRunDisposition as l, runUnknown as m, AgentChildPending as n, SubagentDurabilityError as o, run as p, AgentResultSchema as r, ToolCallWaiting as s, AgentRuntime_exports as t, projectCompletionFromToolOutput as u, streamUnknown as v, streamWithUsageAccountingUnknown as y };
4738
4738
 
4739
- //# sourceMappingURL=AgentRuntime-Cp1hAb-W.mjs.map
4739
+ //# sourceMappingURL=AgentRuntime-RdmnK_aD.mjs.map