effect-agent 0.1.0-beta.144 → 0.1.0-beta.149

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 (83) hide show
  1. package/dist/{Admin-CQMppCcy.d.mts → Admin-B8ISZyYf.d.mts} +37 -22
  2. package/dist/Agent-1DMSO_Fl.mjs.map +1 -1
  3. package/dist/{Agent-BWhD4Dvu.d.mts → Agent-Cjd_ZveM.d.mts} +7 -3
  4. package/dist/{AgentRuntime-xeCUXutN.mjs → AgentRuntime-D8U9gl9Q.mjs} +23 -18
  5. package/dist/AgentRuntime-D8U9gl9Q.mjs.map +1 -0
  6. package/dist/{AgentRuntime-B4kIzmSF.d.mts → AgentRuntime-sXpKcyxu.d.mts} +5 -5
  7. package/dist/{DurableAgentRuntime-D8GI66mP.mjs → DurableAgentRuntime-DLa4IwFi.mjs} +87 -49
  8. package/dist/DurableAgentRuntime-DLa4IwFi.mjs.map +1 -0
  9. package/dist/{EventSource-w9PonN9X.d.mts → EventSource-CkN05NT3.d.mts} +2 -2
  10. package/dist/{Messaging-Dnmk31yq.d.mts → Messaging-ccQURKCf.d.mts} +3 -3
  11. package/dist/{MessagingHost-CajpPDPG.d.mts → MessagingHost-D04wE-7W.d.mts} +2 -2
  12. package/dist/{Output-DhtWbBcw.d.mts → Output-CFD1CPfU.d.mts} +2 -2
  13. package/dist/{PreparedInputAdmission-BfcLy_k4.d.mts → PreparedInputAdmission-fctZOTnn.d.mts} +3 -3
  14. package/dist/{RunOptions-IlEXLG5F.d.mts → RunOptions-Bv9NpkPZ.d.mts} +10 -2
  15. package/dist/{Subagent-Cl8D1mFM.d.mts → Subagent-VHrANXFy.d.mts} +5 -5
  16. package/dist/{Subagent-8RzJkqJ9.mjs → Subagent-hG9lJ7tJ.mjs} +2 -2
  17. package/dist/{Subagent-8RzJkqJ9.mjs.map → Subagent-hG9lJ7tJ.mjs.map} +1 -1
  18. package/dist/{SubagentHost-B6f4PBC2.d.mts → SubagentHost-C-4A7tA2.d.mts} +2 -2
  19. package/dist/{Subscription-ClkC4_T0.d.mts → Subscription-B16A-48F.d.mts} +2 -2
  20. package/dist/{SubscriptionInput-CMjEKL1z.d.mts → SubscriptionInput-DIU7CiXE.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/LifecyclePublication.d.mts +2 -2
  36. package/dist/durable/LifecyclePublication.mjs +32 -12
  37. package/dist/durable/LifecyclePublication.mjs.map +1 -1
  38. package/dist/durable/MessageDelivery.d.mts +3 -3
  39. package/dist/durable/MessageDeliveryStoreConformance.d.mts +1 -1
  40. package/dist/durable/PersistentHistory.d.mts +1 -1
  41. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  42. package/dist/durable/Recovery.d.mts +1 -1
  43. package/dist/durable/RunJournal.d.mts +1 -1
  44. package/dist/durable/Scheduling.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 +25 -5
  60. package/dist/durable/WorkerHost.mjs.map +1 -1
  61. package/dist/engine/AgentRuntime.d.mts +1 -1
  62. package/dist/engine/AgentRuntime.mjs +1 -1
  63. package/dist/engine/MessagingHost.d.mts +1 -1
  64. package/dist/engine/Output.d.mts +1 -1
  65. package/dist/engine/Output.mjs +1 -1
  66. package/dist/engine/RunOptions.d.mts +1 -1
  67. package/dist/engine/RunOptions.mjs.map +1 -1
  68. package/dist/engine/SubagentHost.d.mts +1 -1
  69. package/dist/index.d.mts +13 -13
  70. package/dist/index.mjs +3 -3
  71. package/dist/{output-contract-CANJJGA5.mjs → output-contract-DS-S8mTv.mjs} +46 -10
  72. package/dist/{output-contract-CANJJGA5.mjs.map → output-contract-DS-S8mTv.mjs.map} +1 -1
  73. package/package.json +1 -1
  74. package/src/core/Agent.ts +6 -2
  75. package/src/durable/DurableAgentRuntime.ts +86 -78
  76. package/src/durable/LifecyclePublication.ts +79 -25
  77. package/src/durable/WorkerHost.ts +23 -1
  78. package/src/durable/internal/worker-host.ts +169 -17
  79. package/src/engine/RunOptions.ts +8 -0
  80. package/src/engine/internal/agent-runtime.ts +80 -18
  81. package/src/engine/internal/output-contract.ts +67 -8
  82. package/dist/AgentRuntime-xeCUXutN.mjs.map +0 -1
  83. package/dist/DurableAgentRuntime-D8GI66mP.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-BWhD4Dvu.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-Cjd_ZveM.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-IlEXLG5F.mjs";
16
+ import { G as RunToolAuthorization, O as RunCostEstimator, h as RunApprovalHook, x as RunContextPreparation } from "./RunOptions-Bv9NpkPZ.mjs";
17
17
  import { o as MessagingError, r as InputMessage } from "./Messaging-Dkg87ebg.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";
18
+ import { t as MessagingHost } from "./MessagingHost-D04wE-7W.mjs";
19
+ import "./Messaging-ccQURKCf.mjs";
20
+ import { d as WorkerReportPreparationFailure, f as WorkerReporting, o as SubagentHost } from "./SubagentHost-C-4A7tA2.mjs";
21
+ import { p as RuntimeBinding, r as AgentCompletionProjectionRequirements, s as AgentRuntimeRequirements } from "./AgentRuntime-sXpKcyxu.mjs";
22
22
  import { $ as ToolCallPrepared, A as ProducerId, B as RunStartedRecord, G as SubagentRequested, I as RunCompleted, J as SubmissionSettledRecord, K as SubagentStarted, M as RecordId, O as PersistedJson, Q as ToolApprovalRequested, T as ModelResponseRecorded, U as SubagentJoined, V as SettlementFailureDiagnostic, Z as ToolApprovalDecided, _t as WorkerStopRequested, 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, q as SubmissionSettled, r as AgentUpdateEmitted, s as CanonicalBatch, st as UserInputRecorded, t as AbortRequested, ut as WorkerInputCompleted } 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";
@@ -520,7 +520,7 @@ declare class SettledSubmission extends SettledSubmission_base {}
520
520
  declare const SubmissionStatus: Schema.Union<readonly [typeof PendingSubmission, typeof SettledSubmission]>;
521
521
  type SubmissionStatus = typeof SubmissionStatus.Type;
522
522
  declare namespace LifecyclePublication_d_exports {
523
- export { LifecyclePublication, LifecyclePublicationConfig, LifecyclePublicationError, LifecyclePublicationFact, LifecyclePublicationHandler, LifecyclePublicationSource, LifecyclePublicationStorage, drainLifecyclePublications, lifecyclePublicationLayer };
523
+ export { LifecyclePublication, LifecyclePublicationBatch, LifecyclePublicationConfig, LifecyclePublicationError, LifecyclePublicationFact, LifecyclePublicationHandler, LifecyclePublicationSource, LifecyclePublicationStorage, drainLifecyclePublications, lifecyclePublicationBatchMaxFacts, lifecyclePublicationLayer };
524
524
  }
525
525
  /** Immutable native admission evidence. It is private and grants no application authority. */
526
526
  declare const LifecyclePublicationSource: Schema.Struct<{
@@ -1470,25 +1470,39 @@ declare class LifecyclePublication extends LifecyclePublication_base {}
1470
1470
  declare const LifecyclePublicationError_base: Schema.Class<LifecyclePublicationError, Schema.TaggedStruct<"LifecyclePublicationError", {
1471
1471
  readonly reason: Schema.Literals<readonly ["unavailable", "conflict", "corrupt", "capacity"]>;
1472
1472
  readonly cause: Schema.optionalKey<Schema.Defect>;
1473
- }>, import("effect/Cause").YieldableError>;
1473
+ }>, Cause.YieldableError>;
1474
1474
  declare class LifecyclePublicationError extends LifecyclePublicationError_base {}
1475
- /** Native recovery state, not a second application record or launch queue. */
1475
+ /** Bound both retained facts and the immutable admission evidence resolved before dispatch. */
1476
+ declare const lifecyclePublicationBatchMaxFacts = 8;
1477
+ /** One owner's bounded pending prefix, strictly ordered by its durable ordinals. */
1478
+ declare const LifecyclePublicationBatch: Schema.NonEmptyArray<typeof LifecyclePublication>;
1479
+ type LifecyclePublicationBatch = typeof LifecyclePublicationBatch.Type;
1480
+ /** Native recovery state, independent of Attempts. Hosts serialize drains per storage owner. */
1476
1481
  interface LifecyclePublicationStorage {
1477
- readonly pending: (nowMillis: number, limit: number) => Effect.Effect<ReadonlyArray<LifecyclePublication>, LifecyclePublicationError>;
1478
- readonly acknowledge: (publication: LifecyclePublication) => Effect.Effect<void, LifecyclePublicationError>;
1479
- readonly defer: (publication: LifecyclePublication, untilMillis: number) => Effect.Effect<void, LifecyclePublicationError>;
1482
+ /** Select up to `limit` due owners, with a bounded pending prefix for each selected owner. */
1483
+ readonly pending: (nowMillis: number, limit: number) => Effect.Effect<ReadonlyArray<LifecyclePublicationBatch>, LifecyclePublicationError>;
1484
+ /** Atomically acknowledge the exact batch, retaining its identities and fingerprints. */
1485
+ readonly acknowledge: (publications: LifecyclePublicationBatch) => Effect.Effect<void, LifecyclePublicationError>;
1486
+ /**
1487
+ * Claim a due owner batch and persist its retry before dispatch. Eight automatic attempts;
1488
+ * 1s exponential backoff capped at 60s, after the dispatch timeout. The final attempt parks
1489
+ * the payload before dispatch so process loss cannot renew its budget. False means not due.
1490
+ */
1491
+ readonly claim: (publications: LifecyclePublicationBatch, nowMillis: number, timeoutMillis: number) => Effect.Effect<boolean, LifecyclePublicationError>;
1480
1492
  readonly pendingDeadline: Effect.Effect<Option.Option<number>, LifecyclePublicationError>;
1481
- /** Earliest retained owner obligation, including deferred facts that still gate execution. */
1482
- readonly pendingDeadlineFor: (ownerThreadId: ThreadId) => Effect.Effect<Option.Option<number>, LifecyclePublicationError>;
1493
+ /** Explicit operator retry after repairing a parked owner's destination. */
1494
+ readonly retryParked: (ownerThreadId: ThreadId, nowMillis: number) => Effect.Effect<void, LifecyclePublicationError>;
1483
1495
  }
1484
1496
  declare const LifecyclePublicationHandler_base: Context.ServiceClass<LifecyclePublicationHandler, "@effect-agent/thread/LifecyclePublicationHandler", {
1485
- readonly publish: (publication: LifecyclePublication) => Effect.Effect<void, LifecyclePublicationError, Scope.Scope>;
1497
+ readonly publish: (publications: LifecyclePublicationBatch) => Effect.Effect<void, LifecyclePublicationError, Scope.Scope>;
1486
1498
  }>;
1487
1499
  /**
1488
- * Publish an idempotent domain command, including its authorization, exact receipt and delivery
1489
- * intent. Return only after that command commits. Treat private input/update/result fields as
1490
- * private; the application must select its declared public fields. Revocation/deletion is an
1491
- * acknowledged domain decision, not an indefinitely retryable infrastructure failure.
1500
+ * Publish one owner's ordered batch in one idempotent host transaction, including authorization,
1501
+ * records, receipts and delivery intents. Larger backlogs continue in later batches.
1502
+ * Return only after the entire batch commits. Retries
1503
+ * may include already committed identities plus later facts; deduplicate each fact's `id`.
1504
+ * Private input/update/result fields remain private; select declared public fields explicitly.
1505
+ * Revocation/deletion is an acknowledged domain decision, not an infrastructure retry.
1492
1506
  */
1493
1507
  declare class LifecyclePublicationHandler extends LifecyclePublicationHandler_base {}
1494
1508
  /** Adapter configuration; the opt-in layer captures its explicit Crypto requirement once. */
@@ -1497,7 +1511,8 @@ declare const LifecyclePublicationConfig: Context.Reference<Option.Option<Crypto
1497
1511
  declare const lifecyclePublicationLayer: Layer.Layer<never, never, Crypto.Crypto>;
1498
1512
  /**
1499
1513
  * One finite wave for the host's existing maintenance coordinator. Persist the next deadline
1500
- * before dispatch, so interruption and process loss retain the same fact without another timer.
1514
+ * before dispatch, so interruption and process loss retain the same facts without another timer.
1515
+ * Finish independent owner batches before surfacing failures; interruption stops the wave.
1501
1516
  * Acknowledgements are exact and idempotent. No producer or external Tool is re-executed here.
1502
1517
  */
1503
1518
  declare const drainLifecyclePublications: (storage: LifecyclePublicationStorage, timeoutMillis?: any, limit?: any) => Effect.Effect<number, LifecyclePublicationError, LifecyclePublicationHandler | SubmissionLedger | ThreadStore>;
@@ -4216,5 +4231,5 @@ declare const RetryRefused_base: Schema.Class<RetryRefused, Schema.TaggedStruct<
4216
4231
  */
4217
4232
  declare class RetryRefused extends RetryRefused_base {}
4218
4233
  //#endregion
4219
- export { RepairSubagentStartLink as $, runIdForSubmission as $i, DurableApprovalFailure as $n, ThreadRecoveryCheckpoints as $r, ParentLinkage as $t, AwaitChildSettlement as A, workerOriginRecordId as Aa, RunJournalProjection as Ai, SuspensionReason as An, CheckpointRejected as Ar, ChildReservationConflict as At, MarkUnknown as B, ResolvedBinding as Ba, firstWorkerInputRecordId as Bi, settlementFailureFromRecord as Bn, ThreadExport as Br, InputAppliedMarker as Bt, renderRecoveryExplanation as C, turnIdForRun as Ca, lifecyclePublicationLayer as Ci, SubmissionLookupByKey as Cn, isolateRecovery as Cr, ApprovalDecisionIntent as Ct, ApplyUnknownResolutions as D, turnResultsBatch as Da, SubmissionStatus_d_exports as Di, SubmissionWorkItem as Dn, threadCreatedRecordId as Dr, ChildAttachmentSnapshot as Dt, ApplyJoinAccounting as E, turnResponseBatchId as Ea, SubmissionStatus as Ei, SubmissionState as En, threadCreatedBatchId as Er, BeginChildBudgetReleaseRequest as Et, CompleteMaterialization as F, BindingUnavailable as Fa, approvalDecisionBatchId as Fi, UnknownResolutionIntent as Fn, SaveCheckpointRequest as Fr, Claim as Ft, PropagateChildAbort as G, peerMessageRecordId as Gi, submissionSettlementBatchId as Gn, ThreadNotMaterialized as Gr, MarkInputAppliedRequest as Gt, OpenDelegationCallEvidence as H, compileRegistrations as Ha, modelResponseInterruptedBatchId as Hi, submissionAbortRecordId as Hn, ThreadIdentity as Hr, JoiningClaim as Ht, DeclaredPendingBatchEvidence as I, DurableBindingFailure as Ia, childIdempotencyKeyFor as Ii, WaitingChild as In, SaveRecoveryCheckpointRequest as Ir, ClaimHandoff as It, Recovery_d_exports as J, promptFromCanonicalRecords as Ji, workerTerminalFromRecord as Jn, ThreadOutstandingRequest as Jr, MarkUnknownRequest as Jt, RecoveryDecision as K, projectRunJournal as Ki, submissionSettlementId as Kn, ThreadObservation as Kr, MarkJoinedRequest as Kt, DelegationAdmissionEvidence as L, DurableWorkerBinding as La, childThreadIdFor as Li, WaitingForChildSuspension as Ln, SelectedThreadRead as Lr, ClaimJoiningRequest as Lt, AwaitParentEstablishment as M, AgentRegistration_d_exports as Ma, RunJournal_d_exports as Mi, UnknownResolution as Mn, FencedAppendRequest as Mr, ChildReservationStatus as Mt, AwaitUnknownResolution as N, AgentAttemptContext as Na, TurnCommitInput as Ni, UnknownResolutionCommand as Nn, LoadCheckpointRequest as Nr, ChildSettledNotification as Nt, AwaitApprovalDecision as O, turnResultsBatchId as Oa, JournalBoundary as Oi, SuspendRequest as On, AppendConflict as Or, ChildBudgetReservationRequest as Ot, CompleteChildAdmission as P, AgentRegistration as Pa, agentUpdateRecordId as Pi, UnknownResolutionConflict as Pn, MAX_THREAD_EXPORT_RECORDS as Pr, ChildSettledOutcome as Pt, RepairReadiness as Q, runDurationRecordId as Qi, DurableAgentRuntime_d_exports as Qn, ThreadRecordRequest as Qr, OwnershipToken as Qt, EnsureWaitingForChild as R, ExecutableAgentBinding as Ra, compactionBatchId as Ri, WorkerLedgerState as Rn, ThreadCheckpoint as Rr, ClaimRequest as Rt, recoveryDecisionMeaning as S, turnCanonicalBatch as Sa, drainLifecyclePublications as Si, SubmissionLookupById as Sn, childReservationIdFor as Sr, ApprovalDecisionCommand as St, ApplyInput as T, turnResponseBatch as Ta, SettledSubmission as Ti, SubmissionSnapshot as Tn, recoveryRepairRecordId as Tr, AttachChildToReservationRequest as Tt, OpenToolCallEvidence as U, definitionDigestsEqual as Ua, modelResponseInterruptedRecordId as Ui, submissionInputBatchId as Un, ThreadIdentityRequest as Ur, LedgerCapabilities as Ut, NoAction as V, compileBindingContracts as Va, markUnknownBatchId as Vi, submissionAbortBatchId as Vn, ThreadExportRequest as Vr, JoinSnapshot as Vt, PendingApprovalEvidence as W, modelResponseRecordId as Wi, submissionInputRecordId as Wn, ThreadMaterialization as Wr, LedgerError as Wt, RepairInputMarker as X, runCompletionDigest as Xi, DurableAbortFailure as Xn, ThreadRead as Xr, OwnershipRenewal as Xt, ReleaseOrphanChildReservation as Y, runCompletedRecordId as Yi, ApprovalSuspensionError as Yn, ThreadPeerCountRequest as Yr, OwnershipLost as Yt, RepairJoinMarker as Z, runDurationBatchId as Zi, DurableAgentRuntime as Zn, ThreadReadRequest as Zr, OwnershipSnapshot as Zt, RetryCommand as _, toolCallUnknownRecordId as _a, LifecyclePublicationFact as _i, SubmissionAdmissionFence as _n, RecoveryBlocked as _r, AdmissionPolicyError as _t, IntegrityCheck as a, subagentLineageRecordId as aa, ThreadStoreFailure as ai, ReservedChildBudget as an, DurableObserveOptions as ar, SettleAborted as at, obligationSeverityOf as b, turnApprovalsBatchId as ba, LifecyclePublicationStorage as bi, SubmissionLedger_d_exports as bn, RecoverySweepOptions as br, AdmissionResult as bt, IntegrityReport as c, subagentStartedBatchId as ca, ThreadTailRequest as ci, ResolutionCompletedWithResult as cn, DurableRetryFailure as cr, AbortCommand as ct, ObligationReport as d, toolApprovalRequestRecordId as da, getRunInput as di, RevertJoiningRequest as dn, DurableSubmitAgent as dr, AdmissionAdmitted as dt, runStartedBatchId as ea, ThreadRunInputRequest as ei, RecoverySnapshot as en, DurableApprovalResolver as er, ResumeFromTurnBoundary as et, ObligationSeverity as f, toolCallPreparedRecordId as fa, readOutstanding as fi, Settlement as fn, DurableSubmitFailure as fr, AdmissionConflict as ft, RecoveryExplanation as g, toolCallSettledRecordId as ga, LifecyclePublicationError as gi, SettlementReservationSnapshot as gn, DurableWorkerRequirements as gr, AdmissionNotAdmitted as gt, RecoveryDisposition as h, toolCallResultBatchId as ha, LifecyclePublicationConfig as hi, SettlementReservation as hn, DurableWorkerFailure as hr, AdmissionIndeterminate as ht, ExplainedUnknownCall as i, subagentLineageBatchId as ia, ThreadStoreError as ii, RenewOwnershipRequest as in, DurableObligationFailure as ir, RevertJoining as it, AwaitHostSettlement as j, workerReportRecordId as ja, RunJournalUsage as ji, SuspensionSnapshot as jn, FenceRejected as jr, ChildReservationId as jt, AwaitChildAdmissionResolution as k, workerInputRecordId as ka, RunJournalError as ki, SuspensionOutcome as kn, AppendResult as kr, ChildBudgetReservationSnapshot as kt, ObligationBlockedOn as l, subagentStartedRecordId as la, ThreadWorkerStateRequest as li, ResolutionNeverHappened as ln, DurableRuntimeConfig as lr, AbortIntent as lt, RECOVERY_DECISION_MEANINGS as m, toolCallResolvedRecordId as ma, LifecyclePublication as mi, SettlementFinalization as mn, DurableVerifyFailure as mr, AdmissionGroup as mt, ExplainedEvidence as n, subagentJoinBatchId as na, ThreadStore as ni, ReleaseChildBudgetRequest as nn, DurableAwaitFailure as nr, ResumeSuspended as nt, IntegrityCheckName as o, subagentRequestedBatchId as oa, ThreadStore_d_exports as oi, ReservedSettlement as on, DurableProgressFailure as or, SettleJoinedWithHost as ot, ObligationThresholds as p, toolCallResolutionBatchId as pa, readWorkerState as pi, SettlementConflict as pn, DurableSubmitOptions as pr, AdmissionFence as pt, RecoveryEvidence as q, projectRunJournalStream as qi, submissionSettlementRecordId as qn, ThreadOutstanding as qr, MarkReadyRequest as qt, ExplainedSubmission as r, subagentJoinedRecordId as ra, ThreadStoreDiagnostic as ri, ReleaseOwnershipRequest as rn, DurableExplainFailure as rr, ResumeWaitingParent as rt, IntegrityCheckStatus as s, subagentRequestedRecordId as sa, ThreadTail as si, ResolutionAbortSubmission as sn, DurableResolveFailure as sr, classifyRecovery as st, Admin_d_exports as t, runStartedRecordId as ta, ThreadSelection as ti, RecoverySnapshotRequest as tn, DurableApprovalSuspension as tr, ResumePendingToolBatch as tt, ObligationEntry as u, toolApprovalDecisionRecordId as ua, getRecord as ui, ResolutionSafeToRetry as un, DurableRuntimeConfigOptions as ur, AbortIntentRequest as ut, RetryRefusalReason as v, toolStepSettledBatchId as va, LifecyclePublicationHandler as vi, SubmissionLedger as vn, RecoveryFailure as vr, AdmissionRequest as vt, AppendReservedSettlement as w, turnPreparedBatchId as wa, PendingSubmission as wi, SubmissionScheduling as wn, recoveryRepairBatchId as wr, ApprovalPendingSuspension as wt, predictRecoveryDisposition as x, turnBatchId as xa, LifecyclePublication_d_exports as xi, SubmissionLookup as xn, RecoverySweepResult as xr, ApprovalConflict as xt, RetryRefused as y, toolStepSettledRecordId as ya, LifecyclePublicationSource as yi, SubmissionLedgerFailure as yn, RecoveryReport as yr, AdmissionResolution as yt, FinalizeLedgerFromHistory as z, ReplayVersions as za, compactionRecordId as zi, WorkerStopCommand as zn, ThreadCheckpoints as zr, DEFAULT_OWNERSHIP_LEASE_DURATION as zt };
4220
- //# sourceMappingURL=Admin-CQMppCcy.d.mts.map
4234
+ export { RepairSubagentStartLink as $, runDurationBatchId as $i, DurableApprovalFailure as $n, ThreadRecoveryCheckpoints as $r, ParentLinkage as $t, AwaitChildSettlement as A, turnResultsBatchId as Aa, JournalBoundary as Ai, SuspensionReason as An, CheckpointRejected as Ar, ChildReservationConflict as At, MarkUnknown as B, ExecutableAgentBinding as Ba, compactionBatchId as Bi, settlementFailureFromRecord as Bn, ThreadExport as Br, InputAppliedMarker as Bt, renderRecoveryExplanation as C, turnBatchId as Ca, drainLifecyclePublications as Ci, SubmissionLookupByKey as Cn, isolateRecovery as Cr, ApprovalDecisionIntent as Ct, ApplyUnknownResolutions as D, turnResponseBatch as Da, SettledSubmission as Di, SubmissionWorkItem as Dn, threadCreatedRecordId as Dr, ChildAttachmentSnapshot as Dt, ApplyJoinAccounting as E, turnPreparedBatchId as Ea, PendingSubmission as Ei, SubmissionState as En, threadCreatedBatchId as Er, BeginChildBudgetReleaseRequest as Et, CompleteMaterialization as F, AgentAttemptContext as Fa, TurnCommitInput as Fi, UnknownResolutionIntent as Fn, SaveCheckpointRequest as Fr, Claim as Ft, PropagateChildAbort as G, definitionDigestsEqual as Ga, modelResponseInterruptedRecordId as Gi, submissionSettlementBatchId as Gn, ThreadNotMaterialized as Gr, MarkInputAppliedRequest as Gt, OpenDelegationCallEvidence as H, ResolvedBinding as Ha, firstWorkerInputRecordId as Hi, submissionAbortRecordId as Hn, ThreadIdentity as Hr, JoiningClaim as Ht, DeclaredPendingBatchEvidence as I, AgentRegistration as Ia, agentUpdateRecordId as Ii, WaitingChild as In, SaveRecoveryCheckpointRequest as Ir, ClaimHandoff as It, Recovery_d_exports as J, projectRunJournal as Ji, workerTerminalFromRecord as Jn, ThreadOutstandingRequest as Jr, MarkUnknownRequest as Jt, RecoveryDecision as K, modelResponseRecordId as Ki, submissionSettlementId as Kn, ThreadObservation as Kr, MarkJoinedRequest as Kt, DelegationAdmissionEvidence as L, BindingUnavailable as La, approvalDecisionBatchId as Li, WaitingForChildSuspension as Ln, SelectedThreadRead as Lr, ClaimJoiningRequest as Lt, AwaitParentEstablishment as M, workerOriginRecordId as Ma, RunJournalProjection as Mi, UnknownResolution as Mn, FencedAppendRequest as Mr, ChildReservationStatus as Mt, AwaitUnknownResolution as N, workerReportRecordId as Na, RunJournalUsage as Ni, UnknownResolutionCommand as Nn, LoadCheckpointRequest as Nr, ChildSettledNotification as Nt, AwaitApprovalDecision as O, turnResponseBatchId as Oa, SubmissionStatus as Oi, SuspendRequest as On, AppendConflict as Or, ChildBudgetReservationRequest as Ot, CompleteChildAdmission as P, AgentRegistration_d_exports as Pa, RunJournal_d_exports as Pi, UnknownResolutionConflict as Pn, MAX_THREAD_EXPORT_RECORDS as Pr, ChildSettledOutcome as Pt, RepairReadiness as Q, runCompletionDigest as Qi, DurableAgentRuntime_d_exports as Qn, ThreadRecordRequest as Qr, OwnershipToken as Qt, EnsureWaitingForChild as R, DurableBindingFailure as Ra, childIdempotencyKeyFor as Ri, WorkerLedgerState as Rn, ThreadCheckpoint as Rr, ClaimRequest as Rt, recoveryDecisionMeaning as S, turnApprovalsBatchId as Sa, LifecyclePublication_d_exports as Si, SubmissionLookupById as Sn, childReservationIdFor as Sr, ApprovalDecisionCommand as St, ApplyInput as T, turnIdForRun as Ta, lifecyclePublicationLayer as Ti, SubmissionSnapshot as Tn, recoveryRepairRecordId as Tr, AttachChildToReservationRequest as Tt, OpenToolCallEvidence as U, compileBindingContracts as Ua, markUnknownBatchId as Ui, submissionInputBatchId as Un, ThreadIdentityRequest as Ur, LedgerCapabilities as Ut, NoAction as V, ReplayVersions as Va, compactionRecordId as Vi, submissionAbortBatchId as Vn, ThreadExportRequest as Vr, JoinSnapshot as Vt, PendingApprovalEvidence as W, compileRegistrations as Wa, modelResponseInterruptedBatchId as Wi, submissionInputRecordId as Wn, ThreadMaterialization as Wr, LedgerError as Wt, RepairInputMarker as X, promptFromCanonicalRecords as Xi, DurableAbortFailure as Xn, ThreadRead as Xr, OwnershipRenewal as Xt, ReleaseOrphanChildReservation as Y, projectRunJournalStream as Yi, ApprovalSuspensionError as Yn, ThreadPeerCountRequest as Yr, OwnershipLost as Yt, RepairJoinMarker as Z, runCompletedRecordId as Zi, DurableAgentRuntime as Zn, ThreadReadRequest as Zr, OwnershipSnapshot as Zt, RetryCommand as _, toolCallResultBatchId as _a, LifecyclePublicationError as _i, SubmissionAdmissionFence as _n, RecoveryBlocked as _r, AdmissionPolicyError as _t, IntegrityCheck as a, subagentJoinedRecordId as aa, ThreadStoreFailure as ai, ReservedChildBudget as an, DurableObserveOptions as ar, SettleAborted as at, obligationSeverityOf as b, toolStepSettledBatchId as ba, LifecyclePublicationSource as bi, SubmissionLedger_d_exports as bn, RecoverySweepOptions as br, AdmissionResult as bt, IntegrityReport as c, subagentRequestedBatchId as ca, ThreadTailRequest as ci, ResolutionCompletedWithResult as cn, DurableRetryFailure as cr, AbortCommand as ct, ObligationReport as d, subagentStartedRecordId as da, getRunInput as di, RevertJoiningRequest as dn, DurableSubmitAgent as dr, AdmissionAdmitted as dt, runDurationRecordId as ea, ThreadRunInputRequest as ei, RecoverySnapshot as en, DurableApprovalResolver as er, ResumeFromTurnBoundary as et, ObligationSeverity as f, toolApprovalDecisionRecordId as fa, readOutstanding as fi, Settlement as fn, DurableSubmitFailure as fr, AdmissionConflict as ft, RecoveryExplanation as g, toolCallResolvedRecordId as ga, LifecyclePublicationConfig as gi, SettlementReservationSnapshot as gn, DurableWorkerRequirements as gr, AdmissionNotAdmitted as gt, RecoveryDisposition as h, toolCallResolutionBatchId as ha, LifecyclePublicationBatch as hi, SettlementReservation as hn, DurableWorkerFailure as hr, AdmissionIndeterminate as ht, ExplainedUnknownCall as i, subagentJoinBatchId as ia, ThreadStoreError as ii, RenewOwnershipRequest as in, DurableObligationFailure as ir, RevertJoining as it, AwaitHostSettlement as j, workerInputRecordId as ja, RunJournalError as ji, SuspensionSnapshot as jn, FenceRejected as jr, ChildReservationId as jt, AwaitChildAdmissionResolution as k, turnResultsBatch as ka, SubmissionStatus_d_exports as ki, SuspensionOutcome as kn, AppendResult as kr, ChildBudgetReservationSnapshot as kt, ObligationBlockedOn as l, subagentRequestedRecordId as la, ThreadWorkerStateRequest as li, ResolutionNeverHappened as ln, DurableRuntimeConfig as lr, AbortIntent as lt, RECOVERY_DECISION_MEANINGS as m, toolCallPreparedRecordId as ma, LifecyclePublication as mi, SettlementFinalization as mn, DurableVerifyFailure as mr, AdmissionGroup as mt, ExplainedEvidence as n, runStartedBatchId as na, ThreadStore as ni, ReleaseChildBudgetRequest as nn, DurableAwaitFailure as nr, ResumeSuspended as nt, IntegrityCheckName as o, subagentLineageBatchId as oa, ThreadStore_d_exports as oi, ReservedSettlement as on, DurableProgressFailure as or, SettleJoinedWithHost as ot, ObligationThresholds as p, toolApprovalRequestRecordId as pa, readWorkerState as pi, SettlementConflict as pn, DurableSubmitOptions as pr, AdmissionFence as pt, RecoveryEvidence as q, peerMessageRecordId as qi, submissionSettlementRecordId as qn, ThreadOutstanding as qr, MarkReadyRequest as qt, ExplainedSubmission as r, runStartedRecordId as ra, ThreadStoreDiagnostic as ri, ReleaseOwnershipRequest as rn, DurableExplainFailure as rr, ResumeWaitingParent as rt, IntegrityCheckStatus as s, subagentLineageRecordId as sa, ThreadTail as si, ResolutionAbortSubmission as sn, DurableResolveFailure as sr, classifyRecovery as st, Admin_d_exports as t, runIdForSubmission as ta, ThreadSelection as ti, RecoverySnapshotRequest as tn, DurableApprovalSuspension as tr, ResumePendingToolBatch as tt, ObligationEntry as u, subagentStartedBatchId as ua, getRecord as ui, ResolutionSafeToRetry as un, DurableRuntimeConfigOptions as ur, AbortIntentRequest as ut, RetryRefusalReason as v, toolCallSettledRecordId as va, LifecyclePublicationFact as vi, SubmissionLedger as vn, RecoveryFailure as vr, AdmissionRequest as vt, AppendReservedSettlement as w, turnCanonicalBatch as wa, lifecyclePublicationBatchMaxFacts as wi, SubmissionScheduling as wn, recoveryRepairBatchId as wr, ApprovalPendingSuspension as wt, predictRecoveryDisposition as x, toolStepSettledRecordId as xa, LifecyclePublicationStorage as xi, SubmissionLookup as xn, RecoverySweepResult as xr, ApprovalConflict as xt, RetryRefused as y, toolCallUnknownRecordId as ya, LifecyclePublicationHandler as yi, SubmissionLedgerFailure as yn, RecoveryReport as yr, AdmissionResolution as yt, FinalizeLedgerFromHistory as z, DurableWorkerBinding as za, childThreadIdFor as zi, WorkerStopCommand as zn, ThreadCheckpoints as zr, DEFAULT_OWNERSHIP_LEASE_DURATION as zt };
4235
+ //# sourceMappingURL=Admin-B8ISZyYf.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 /**\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"}
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. OpenAI, xAI and native adapters advertising support\n * preserve chronological system messages, omitting exact repeats only when no distinct system\n * instruction intervenes. The actual selected model determines support on each call. Other\n * adapters group systems first and keep the last exact repeat, including provider options;\n * Anthropic requires an upstream adapter with mid-conversation system-message support.\n * 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;;AAyMjD,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"}
@@ -111,8 +111,12 @@ interface Definition<InputSchema extends Schema.Top, OutputSchema extends Schema
111
111
  /** Canonical schema used to decode the final model output. */
112
112
  readonly output: OutputSchema;
113
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.
114
+ * Evaluated once while preparing each Run. OpenAI, xAI and native adapters advertising support
115
+ * preserve chronological system messages, omitting exact repeats only when no distinct system
116
+ * instruction intervenes. The actual selected model determines support on each call. Other
117
+ * adapters group systems first and keep the last exact repeat, including provider options;
118
+ * Anthropic requires an upstream adapter with mid-conversation system-message support.
119
+ * Stored history is unchanged.
116
120
  */
117
121
  readonly instructions: Instructions;
118
122
  /** Optional projection from decoded input to model-visible native Effect AI prompt content. */
@@ -252,4 +256,4 @@ declare function make<const Name extends string, InputSchema extends Schema.Top,
252
256
  declare const withModel: <DefinitionValue extends AnyDefinition, ModelValue>(definition: DefinitionValue, model: NativeModel<ModelValue>) => Binding<DefinitionValue, ModelValue>;
253
257
  //#endregion
254
258
  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 };
255
- //# sourceMappingURL=Agent-BWhD4Dvu.d.mts.map
259
+ //# sourceMappingURL=Agent-Cjd_ZveM.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 outputSchemaContract, r as prepareModelPrompt, t as isTextOutput } from "./output-contract-CANJJGA5.mjs";
19
+ import { n as outputSchemaContract, r as prepareModelPrompt, t as isTextOutput } from "./output-contract-DS-S8mTv.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";
@@ -1860,13 +1860,12 @@ const formatRunStatus = (view) => {
1860
1860
  /**
1861
1861
  * The run-status message is derived per request and appended only to the
1862
1862
  * OUTGOING prompt: official history and durable commits never carry it, so it
1863
- * can never accumulate or replay. OpenAI receives it as trailing system guidance,
1864
- * leaving the last user/tool result as the implicit cache-write boundary.
1863
+ * can never accumulate or replay. Capable adapters receive trailing system guidance,
1864
+ * leaving the preceding user/tool result available as a cache-write boundary.
1865
1865
  */
1866
- const outgoingModelPrompt = (policy, context, prepared, turn, declaredToolCalls) => Effect.gen(function* () {
1866
+ const outgoingModelPrompt = (policy, context, prepared, turn, declaredToolCalls, systemMessagesInHistory) => Effect.gen(function* () {
1867
1867
  if (policy.runStatus !== "appended") return prepared;
1868
1868
  const now = yield* Clock.currentTimeMillis;
1869
- const provider = yield* Model.ProviderName;
1870
1869
  const status = formatRunStatus({
1871
1870
  turn,
1872
1871
  maxTurns: policy.maxTurns,
@@ -1879,7 +1878,7 @@ const outgoingModelPrompt = (policy, context, prepared, turn, declaredToolCalls)
1879
1878
  elapsedSeconds: Math.max(0, Math.floor((now - context.startedAtMillis) / 1e3)),
1880
1879
  maxDurationSeconds: Math.floor(Duration.toMillis(policy.maxDuration) / 1e3)
1881
1880
  });
1882
- return Prompt.fromMessages([...prepared.content, provider === "openai" ? Prompt.systemMessage({ content: status }) : Prompt.userMessage({ content: [Prompt.textPart({ text: status })] })]);
1881
+ return Prompt.fromMessages([...prepared.content, systemMessagesInHistory ? Prompt.systemMessage({ content: status }) : Prompt.userMessage({ content: [Prompt.textPart({ text: status })] })]);
1883
1882
  });
1884
1883
  const ProviderUsage = Schema.Struct({
1885
1884
  inputTokens: Schema.Struct({
@@ -2161,10 +2160,10 @@ const estimateContextTokens = Effect.fn("AgentRuntime.estimateContextTokens")(fu
2161
2160
  cause
2162
2161
  })));
2163
2162
  });
2164
- const nextContextEstimate = Effect.fn("AgentRuntime.nextContextEstimate")(function* (context, view) {
2163
+ const nextContextEstimate = Effect.fn("AgentRuntime.nextContextEstimate")(function* (context, view, systemMessagesInHistory, staticInstructions) {
2165
2164
  const state = context.compaction;
2166
2165
  if (context.lastInputTokens > 0 && state.lastViewLength >= 0 && state.lastViewLength <= view.length) return context.lastInputTokens + context.lastOutputTokens + (yield* estimateContextTokens(view.slice(state.lastViewLength)));
2167
- return yield* estimateContextTokens(prepareModelPrompt(Prompt.fromMessages(view), void 0).content);
2166
+ return yield* estimateContextTokens(prepareModelPrompt(Prompt.fromMessages(view), void 0, systemMessagesInHistory, staticInstructions).content);
2168
2167
  });
2169
2168
  const snapshotCompactionMessages = Effect.fnUntraced(function* (messages) {
2170
2169
  return yield* Effect.try({
@@ -2844,6 +2843,10 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
2844
2843
  const estimateCallTokens = (messages) => estimateContextTokens(messages, messageTokenEstimator);
2845
2844
  const modelServices = modelContext.modelCall === void 0 ? void 0 : yield* Layer.build(Layer.fresh(modelContext.modelCall.model));
2846
2845
  const withCallModel = (operation) => modelServices === void 0 ? operation : Effect.provide(operation, modelServices);
2846
+ const provider = yield* withCallModel(Model.ProviderName);
2847
+ const callModel = yield* withCallModel(LanguageModel.LanguageModel);
2848
+ const systemMessagesInHistory = callModel.supportsSystemMessagesInHistory === void 0 ? provider === "openai" || provider === "xai" : yield* withCallModel(callModel.supportsSystemMessagesInHistory);
2849
+ const staticInstructions = typeof agent.definition.instructions === "function" ? void 0 : agent.definition.instructions;
2847
2850
  const priorCompactionPrefix = context.preparedCompactionSource?.prefix;
2848
2851
  if (priorCompactionPrefix !== void 0 && priorCompactionPrefix.length > 0) {
2849
2852
  const preparedPrefix = yield* snapshotCompactionMessages(modelContext.prompt.content.slice(0, priorCompactionPrefix.length));
@@ -2902,7 +2905,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
2902
2905
  }));
2903
2906
  const admissionRequired = contextTokenLimit !== void 0 || !context.finalizing && !finalAnswerOnly && policy.tokenBudget !== void 0;
2904
2907
  const outputContractTokens = !admissionRequired || outputContractMessage === void 0 ? 0 : yield* estimateCallTokens([Prompt.makeMessage("system", { content: outputContractMessage })]);
2905
- const canonicalDecoration = !admissionRequired ? Prompt.empty : yield* outgoingModelPrompt(policy, context, Prompt.empty, turn, priorToolCalls).pipe(withCallModel);
2908
+ const canonicalDecoration = !admissionRequired ? Prompt.empty : yield* outgoingModelPrompt(policy, context, Prompt.empty, turn, priorToolCalls, systemMessagesInHistory).pipe(withCallModel);
2906
2909
  const estimateToolSchemaTokens = Effect.suspend(() => {
2907
2910
  const choice = modelToolChoice();
2908
2911
  const tools = typeof choice === "object" && "oneOf" in choice ? catalog.filter((entry) => entry.kind === "native" && choice.oneOf.includes(entry.nativeToolName)).map((entry) => entry.tool) : Object.values(modelToolkit.tools);
@@ -2924,7 +2927,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
2924
2927
  let toolSchemaTokens = yield* estimateToolSchemaTokens;
2925
2928
  const canonicalDecorationPromptTokens = !admissionRequired ? 0 : outputContractTokens + (yield* estimateCallTokens(canonicalDecoration.content));
2926
2929
  const canonicalDecorationTokens = () => toolSchemaTokens + canonicalDecorationPromptTokens;
2927
- const estimateSourceContext = (view) => options.context === void 0 && options.transientContext === void 0 ? nextContextEstimate(context, view) : estimateCallTokens(prepareModelPrompt(Prompt.fromMessages(view), void 0).content);
2930
+ const estimateSourceContext = (view) => options.context === void 0 && options.transientContext === void 0 ? nextContextEstimate(context, view, systemMessagesInHistory, staticInstructions) : estimateCallTokens(prepareModelPrompt(Prompt.fromMessages(view), void 0, systemMessagesInHistory, staticInstructions).content);
2928
2931
  let prepared = buildCompactedView(modelContext.prompt.content, context.compaction);
2929
2932
  let sourceTokens;
2930
2933
  const preparedSourceTokens = Effect.suspend(() => sourceTokens === void 0 ? estimateSourceContext(prepared).pipe(Effect.tap((tokens) => Effect.sync(() => {
@@ -3008,7 +3011,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
3008
3011
  });
3009
3012
  }
3010
3013
  const transientContext = options.transientContext === void 0 ? Prompt.empty : yield* options.transientContext.load(contextRequest).pipe(Effect.flatMap(transientInputToPrompt));
3011
- const derivedPrompt = options.transientContext === void 0 ? canonicalDecoration : yield* outgoingModelPrompt(policy, context, transientContext, turn, priorToolCalls).pipe(withCallModel);
3014
+ const derivedPrompt = options.transientContext === void 0 ? canonicalDecoration : yield* outgoingModelPrompt(policy, context, transientContext, turn, priorToolCalls, systemMessagesInHistory).pipe(withCallModel);
3012
3015
  const derivedPromptContentTokens = !admissionRequired ? 0 : options.transientContext === void 0 ? canonicalDecorationPromptTokens : outputContractTokens + (yield* estimateCallTokens(derivedPrompt.content));
3013
3016
  const derivedPromptTokens = () => toolSchemaTokens + derivedPromptContentTokens;
3014
3017
  if (!context.finalizing && admissionRequired && options.transientContext !== void 0) {
@@ -3080,7 +3083,7 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
3080
3083
  if (trace.usage === void 0) return yield* noteIncompleteUsage(context, turn);
3081
3084
  yield* consumeTurnUsage(0).pipe(Effect.exit);
3082
3085
  });
3083
- const attempt = (basis) => Stream.unwrap(outgoingModelPrompt(policy, context, prepareModelPrompt(Prompt.fromMessages([...basis.content, ...transientContext.content]), outputContract._tag === "rendered" ? outputContract.part : void 0), turn, priorToolCalls).pipe(withCallModel, Effect.flatMap((providerPrompt) => Effect.gen(function* () {
3086
+ const attempt = (basis) => Stream.unwrap(outgoingModelPrompt(policy, context, prepareModelPrompt(Prompt.fromMessages([...basis.content, ...transientContext.content]), outputContract._tag === "rendered" ? outputContract.part : void 0, systemMessagesInHistory, staticInstructions), turn, priorToolCalls, systemMessagesInHistory).pipe(withCallModel, Effect.flatMap((providerPrompt) => Effect.gen(function* () {
3084
3087
  const toolChoice = modelToolChoice();
3085
3088
  let requestToolkit = modelToolkit;
3086
3089
  snapshot = selectionSnapshot;
@@ -3249,10 +3252,11 @@ const makeTurn = (agent, context, prompt, turn, priorToolCalls, options) => Stre
3249
3252
  */
3250
3253
  const settleOrFollowUp = (history) => Effect.gen(function* () {
3251
3254
  yield* advanceHistory(context, history, options);
3252
- const steering = yield* drainInputs(context, options);
3255
+ const turnsBlocked = policy.onExhaustion === "fail" ? turn >= bounds.maxTurns : turn > bounds.maxTurns;
3256
+ const steering = turnsBlocked || context.finalizationUsed ? [] : yield* drainInputs(context, options);
3253
3257
  const queued = steering.length > 0 ? steering : takeFollowUps(context, options.commandDrainPolicy ?? "one");
3254
3258
  if (queued.length > 0) {
3255
- if (policy.onExhaustion === "fail" ? turn >= bounds.maxTurns : turn > bounds.maxTurns) return failRunEventStream(AgentPolicyError.make({
3259
+ if (turnsBlocked) return failRunEventStream(AgentPolicyError.make({
3256
3260
  limit: "turns",
3257
3261
  message: `Agent exceeded its ${bounds.maxTurns} Turn limit`
3258
3262
  }));
@@ -3371,9 +3375,11 @@ const toolBatchContinuation = (agent, context, trace, prompt, turn, toolCalls, o
3371
3375
  if (actionCompletion !== void 0) selectedOutput = yield* projectCompletionFromToolOutput(agent, actionCompletion, call.parameters, successfulResult.encodedResult);
3372
3376
  else if (completion !== void 0) selectedOutput = Option.some(yield* projectCompletionOutput(agent, completion, call.parameters, successfulResult.encodedResult));
3373
3377
  }
3374
- if (Option.isSome(selectedOutput)) {
3378
+ const bounds = effectiveRunBounds(agent.definition.policy, options);
3379
+ const canContinue = turn < bounds.maxTurns && (completion?.required === true ? toolCalls + context.programmaticToolCalls < bounds.maxToolCalls : toolCalls + context.programmaticToolCalls <= bounds.maxToolCalls) && !context.tokenExhausted && !context.finalizationUsed && (yield* Clock.currentTimeMillis) < context.durationDeadlineMillis;
3380
+ const steering = Option.isSome(selectedOutput) && !canContinue ? [] : yield* drainInputs(context, options);
3381
+ if (Option.isSome(selectedOutput) && steering.length === 0) {
3375
3382
  const output = selectedOutput.value;
3376
- const bounds = effectiveRunBounds(agent.definition.policy, options);
3377
3383
  const exhausted = context.tokenExhausted ? "tokens" : turn > bounds.maxTurns ? "turns" : toolCalls + context.programmaticToolCalls > bounds.maxToolCalls ? "tool-calls" : context.exhaustedDimension;
3378
3384
  if (exhausted !== void 0 && context.exhaustedDimension === void 0) context.exhaustedDimension = exhausted;
3379
3385
  const declaration = agent.definition.runDisposition;
@@ -3389,7 +3395,6 @@ const toolBatchContinuation = (agent, context, trace, prompt, turn, toolCalls, o
3389
3395
  ...completionUsage
3390
3396
  })));
3391
3397
  }
3392
- const steering = yield* drainInputs(context, options);
3393
3398
  const nextPrompt = yield* appendInputs(context, history, steering, options);
3394
3399
  return nextTurn(nextPrompt, turn + 1, toolCalls);
3395
3400
  }));
@@ -4737,4 +4742,4 @@ var AgentRuntime_exports = /* @__PURE__ */ __exportAll({
4737
4742
  //#endregion
4738
4743
  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 };
4739
4744
 
4740
- //# sourceMappingURL=AgentRuntime-xeCUXutN.mjs.map
4745
+ //# sourceMappingURL=AgentRuntime-D8U9gl9Q.mjs.map