effect-agent 0.1.0-beta.93 → 0.1.0-beta.95

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 (146) hide show
  1. package/dist/{Agent-RklVROrm.mjs → Agent-CG_VMrtA.mjs} +2 -2
  2. package/dist/{Agent-RklVROrm.mjs.map → Agent-CG_VMrtA.mjs.map} +1 -1
  3. package/dist/{Agent-CN0EWRsR.d.mts → Agent-CM6JubNX.d.mts} +2 -2
  4. package/dist/{AgentPolicy-CetmQrf3.d.mts → AgentPolicy-BqDoSXO6.d.mts} +2 -2
  5. package/dist/{AgentRuntime-BPjQM1Nv.mjs → AgentRuntime-Cdvqw7l_.mjs} +88 -32
  6. package/dist/AgentRuntime-Cdvqw7l_.mjs.map +1 -0
  7. package/dist/{AgentRuntime-uxR_a4VM.d.mts → AgentRuntime-CufqQ4JM.d.mts} +8 -8
  8. package/dist/{ContextCompactor-Dxu5zhOL.d.mts → ContextCompactor-WwSIG_Z2.d.mts} +2 -2
  9. package/dist/{DurableAgentRuntime-CdrBuKZY.mjs → DurableAgentRuntime-BaGsWDHO.mjs} +9 -5
  10. package/dist/DurableAgentRuntime-BaGsWDHO.mjs.map +1 -0
  11. package/dist/{EventSource-c6GRTCsl.d.mts → EventSource-DVfX1GRH.d.mts} +3 -3
  12. package/dist/{Messaging-CkcIdt4I.d.mts → Messaging-QMYhp297.d.mts} +3 -3
  13. package/dist/{MessagingHost-CRk0kXzT.d.mts → MessagingHost-gAxs5gme.d.mts} +3 -3
  14. package/dist/{Output-D6SkedVx.d.mts → Output-CjocJzsl.d.mts} +2 -2
  15. package/dist/{PreparedInputAdmission-QzFbW2LQ.d.mts → PreparedInputAdmission-DoWaMC2R.d.mts} +4 -4
  16. package/dist/{Records-vFp_ZQ9Y.d.mts → Records-B84j3Jq_.d.mts} +21 -9
  17. package/dist/{Records-C9cezOEf.mjs → Records-CsEsSW2o.mjs} +5 -2
  18. package/dist/Records-CsEsSW2o.mjs.map +1 -0
  19. package/dist/{RunJournal-lwbrh2hZ.mjs → RunJournal-yYpUlTOE.mjs} +3 -2
  20. package/dist/RunJournal-yYpUlTOE.mjs.map +1 -0
  21. package/dist/{RunOptions-g1aigcKI.d.mts → RunOptions-CE-G3niT.d.mts} +14 -8
  22. package/dist/{Schedule-BkZvKyMw.d.mts → Schedule-DCYBfhgT.d.mts} +2 -2
  23. package/dist/{Scheduling-D0QqOoeT.mjs → Scheduling-CUuYc3-D.mjs} +3 -3
  24. package/dist/{Scheduling-D0QqOoeT.mjs.map → Scheduling-CUuYc3-D.mjs.map} +1 -1
  25. package/dist/{Subagent-CnTzCy8k.mjs → Subagent-Cbfzylz1.mjs} +3 -3
  26. package/dist/{Subagent-CnTzCy8k.mjs.map → Subagent-Cbfzylz1.mjs.map} +1 -1
  27. package/dist/{Subagent-DyfzHNdv.d.mts → Subagent-DscbtbNY.d.mts} +6 -6
  28. package/dist/{SubagentHost-CJUBQlcc.d.mts → SubagentHost-DaFMZnVR.d.mts} +4 -4
  29. package/dist/{Subscription-CKQ0KDHN.d.mts → Subscription-C8IHdmFk.d.mts} +4 -4
  30. package/dist/{SubscriptionInput-Cth8F_7b.d.mts → SubscriptionInput-DhM3jUW2.d.mts} +3 -3
  31. package/dist/{ToolResult-DmmgoChv.d.mts → ToolResult-BKdqWRff.d.mts} +20 -3
  32. package/dist/{Worker-CaPYykpe.d.mts → Worker--j87JI__.d.mts} +2 -2
  33. package/dist/capabilities/Approval.mjs +1 -1
  34. package/dist/capabilities/Commands.d.mts +1 -1
  35. package/dist/capabilities/Messaging.d.mts +2 -2
  36. package/dist/capabilities/ModelContext.mjs +1 -1
  37. package/dist/capabilities/RunHooks.d.mts +1 -1
  38. package/dist/capabilities/Subagent.d.mts +2 -2
  39. package/dist/capabilities/Subagent.mjs +1 -1
  40. package/dist/capabilities/ToolDiscovery.d.mts +19 -4
  41. package/dist/capabilities/ToolDiscovery.mjs +33 -14
  42. package/dist/capabilities/ToolDiscovery.mjs.map +1 -1
  43. package/dist/core/Agent.d.mts +1 -1
  44. package/dist/core/Agent.mjs +1 -1
  45. package/dist/core/AgentPolicy.d.mts +1 -1
  46. package/dist/core/Thread.mjs +1 -1
  47. package/dist/core/ToolResult.d.mts +2 -2
  48. package/dist/core/ToolResult.mjs +17 -1
  49. package/dist/core/ToolResult.mjs.map +1 -1
  50. package/dist/core/Worker.d.mts +1 -1
  51. package/dist/core/Worker.mjs +1 -1
  52. package/dist/durable/ActivityStore.d.mts +1 -1
  53. package/dist/durable/ActivityStore.mjs +1 -1
  54. package/dist/durable/Admin.d.mts +1 -1
  55. package/dist/durable/Admin.mjs +1 -1
  56. package/dist/durable/AgentRegistration.d.mts +1 -1
  57. package/dist/durable/Certification.d.mts +1 -1
  58. package/dist/durable/CommittedActivity.d.mts +1 -1
  59. package/dist/durable/CommittedActivity.mjs +1 -1
  60. package/dist/durable/Digest.d.mts +1 -1
  61. package/dist/durable/Digest.mjs +1 -1
  62. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  63. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  64. package/dist/durable/EventSource.d.mts +1 -1
  65. package/dist/durable/EventSource.mjs +1 -1
  66. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  67. package/dist/durable/GitHubWorkflowSource.mjs +1 -1
  68. package/dist/durable/MessageDelivery.d.mts +23 -23
  69. package/dist/durable/MessageDelivery.mjs +1 -1
  70. package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
  71. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  72. package/dist/durable/PersistentHistory.d.mts +1 -1
  73. package/dist/durable/PersistentHistory.mjs +2 -2
  74. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  75. package/dist/durable/Records.d.mts +1 -1
  76. package/dist/durable/Records.mjs +1 -1
  77. package/dist/durable/Recovery.d.mts +1 -1
  78. package/dist/durable/Recovery.mjs +1 -1
  79. package/dist/durable/RunJournal.d.mts +1 -1
  80. package/dist/durable/RunJournal.mjs +1 -1
  81. package/dist/durable/Schedule.d.mts +1 -1
  82. package/dist/durable/Schedule.mjs +1 -1
  83. package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
  84. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  85. package/dist/durable/ScheduleTransition.d.mts +1 -1
  86. package/dist/durable/ScheduleTransition.mjs +1 -1
  87. package/dist/durable/Scheduling.d.mts +2 -2
  88. package/dist/durable/Scheduling.mjs +1 -1
  89. package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
  90. package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
  91. package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
  92. package/dist/durable/SqlSubscriptionStore.mjs +1 -1
  93. package/dist/durable/SubmissionLedger.d.mts +1 -1
  94. package/dist/durable/SubmissionLedger.mjs +1 -1
  95. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  96. package/dist/durable/SubmissionLedgerConformance.mjs +2 -2
  97. package/dist/durable/SubmissionStatus.d.mts +1 -1
  98. package/dist/durable/Subscription.d.mts +1 -1
  99. package/dist/durable/Subscription.mjs +1 -1
  100. package/dist/durable/SubscriptionInput.d.mts +1 -1
  101. package/dist/durable/SubscriptionInput.mjs +1 -1
  102. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  103. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  104. package/dist/durable/SubscriptionTools.d.mts +3 -3
  105. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  106. package/dist/durable/SubscriptionTransition.mjs +1 -1
  107. package/dist/durable/Subscriptions.d.mts +5 -5
  108. package/dist/durable/Subscriptions.mjs +2 -2
  109. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  110. package/dist/durable/ThreadContextHistory.mjs +1 -1
  111. package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
  112. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  113. package/dist/durable/ThreadInvariants.d.mts +1 -1
  114. package/dist/durable/ThreadInvariants.mjs +1 -1
  115. package/dist/durable/ThreadProjection.d.mts +1 -1
  116. package/dist/durable/ThreadProjection.mjs +1 -1
  117. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  118. package/dist/durable/ThreadStore.d.mts +1 -1
  119. package/dist/durable/ThreadStore.mjs +1 -1
  120. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  121. package/dist/durable/ThreadStoreConformance.mjs +1 -1
  122. package/dist/durable/ToolReconciler.mjs +1 -1
  123. package/dist/durable/WorkerHost.d.mts +4 -4
  124. package/dist/engine/AgentRuntime.d.mts +1 -1
  125. package/dist/engine/AgentRuntime.mjs +1 -1
  126. package/dist/engine/Compaction.d.mts +1 -1
  127. package/dist/engine/ContextCompactor.d.mts +1 -1
  128. package/dist/engine/MessagingHost.d.mts +1 -1
  129. package/dist/engine/Output.d.mts +1 -1
  130. package/dist/engine/RunOptions.d.mts +1 -1
  131. package/dist/engine/RunOptions.mjs.map +1 -1
  132. package/dist/engine/SubagentHost.d.mts +1 -1
  133. package/dist/index.d.mts +18 -18
  134. package/dist/index.mjs +8 -8
  135. package/package.json +1 -1
  136. package/src/capabilities/ToolDiscovery.ts +48 -18
  137. package/src/core/ToolResult.ts +20 -0
  138. package/src/durable/DurableAgentRuntime.ts +7 -0
  139. package/src/durable/Records.ts +3 -0
  140. package/src/durable/RunJournal.ts +5 -0
  141. package/src/engine/RunOptions.ts +9 -3
  142. package/src/engine/internal/agent-runtime.ts +254 -67
  143. package/dist/AgentRuntime-BPjQM1Nv.mjs.map +0 -1
  144. package/dist/DurableAgentRuntime-CdrBuKZY.mjs.map +0 -1
  145. package/dist/Records-C9cezOEf.mjs.map +0 -1
  146. package/dist/RunJournal-lwbrh2hZ.mjs.map +0 -1
@@ -4,13 +4,14 @@ import { i as UpdateError, r as Update } from "./AgentUpdates-DMJ-_xow.mjs";
4
4
  import { c as Selection, l as Snapshot } from "./ToolExposure-r2eOWk4F.mjs";
5
5
  import { r as ModelCallUsage, s as RunTotals, t as ChildRunUsage } from "./Usage-Dx0aknfk.mjs";
6
6
  import { a as AgentInputError } from "./AgentError-CggcAQ7V.mjs";
7
- import { t as AgentPolicy } from "./AgentPolicy-CetmQrf3.mjs";
8
- import { r as AnyDefinition } from "./Agent-CN0EWRsR.mjs";
7
+ import { t as ToolParameterRejection } from "./ToolResult-BKdqWRff.mjs";
8
+ import { t as AgentPolicy } from "./AgentPolicy-BqDoSXO6.mjs";
9
+ import { r as AnyDefinition } from "./Agent-CM6JubNX.mjs";
9
10
  import { o as MemoryRecallError } from "./MemoryReference-B8Q3UJoJ.mjs";
10
11
  import { t as RunPolicyUsage } from "./RunPolicyUsage-ClZxyR46.mjs";
11
- import { n as WorkerBudgetScope, t as FrameworkMessage } from "./Worker-CaPYykpe.mjs";
12
+ import { n as WorkerBudgetScope, t as FrameworkMessage } from "./Worker--j87JI__.mjs";
12
13
  import { c as ModelCallContext, r as ContextRolloverSelection } from "./ContextWindow-DRQ5Mbm2.mjs";
13
- import { c as ContextMessageTokenEstimator, n as CompactionError } from "./ContextCompactor-Dxu5zhOL.mjs";
14
+ import { c as ContextMessageTokenEstimator, n as CompactionError } from "./ContextCompactor-WwSIG_Z2.mjs";
14
15
  import { l as ToolExecutionClassValue, o as RunStepHook } from "./DurableStep-Cry_iol4.mjs";
15
16
  import { LanguageModel, Model, Prompt, Response } from "effect/unstable/ai";
16
17
  import { Cause, Context, DateTime, Effect, Layer, Schema } from "effect";
@@ -383,6 +384,8 @@ declare class RunToolAuthorization extends RunToolAuthorization_base {
383
384
  * application Tool Calls; no-tool Turns keep their late single-batch commit.
384
385
  */
385
386
  interface RunTurnResponseCommit {
387
+ /** Rejected fresh arguments; persist atomically with the response and restore on resume. */
388
+ readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;
386
389
  readonly toolExposure?: Snapshot | undefined;
387
390
  readonly turn: number;
388
391
  readonly turnId: TurnId;
@@ -666,15 +669,18 @@ type RunResumeUsage = typeof RunResumeUsageSchema.Type;
666
669
  * Resume one canonically declared Tool batch without re-invoking the model.
667
670
  *
668
671
  * When present, the engine's first Turn skips the model request entirely: the
669
- * declared calls are re-validated through their Tool parameter Schemas (a
670
- * decode failure executes nothing), approval preflight runs against recorded
671
- * decisions, host Tool authorization is re-evaluated, `prepareToolCalls` replays the full
672
+ * executable calls are re-validated through their Tool parameter Schemas (a
673
+ * decode failure executes nothing). Canonically rejected calls retain their native failure;
674
+ * the rejection must match their exact arguments and any settled result. Approval preflight
675
+ * for executable calls runs against recorded decisions, host Tool authorization is re-evaluated, `prepareToolCalls` replays the full
672
676
  * prepared batch idempotently,
673
677
  * calls listed in `settled` are injected as final results without starting
674
678
  * their handlers, and only the remaining open calls execute. The Run then
675
679
  * proceeds through the normal continuation.
676
680
  */
677
681
  interface RunTurnResume {
682
+ /** Canonical rejection evidence, matched to the exact call; never permits handler execution. */
683
+ readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;
678
684
  readonly toolExposure?: Snapshot | undefined;
679
685
  readonly turn: number;
680
686
  readonly turnId: TurnId;
@@ -912,4 +918,4 @@ type RunOptionsError<Options> = Options extends RunOptions<infer Error, infer _R
912
918
  type RunOptionsRequirements<Options> = Options extends RunOptions<infer _Error, infer Requirements> ? Requirements : never;
913
919
  //#endregion
914
920
  export { RunTurnResponseCommit as $, RunInputCommand as A, RunSubagentChildIdentity as B, RunContextPreparationPassthrough as C, RunCostEstimateValue as D, RunCostEstimateRequest as E, RunOptions_d_exports as F, RunToolAuthorization as G, RunSubagentEstablishRequest as H, RunResumeUsage as I, RunToolAuthorizationRequest as J, RunToolAuthorizationDecision as K, RunResumeUsageSchema as L, RunOptions as M, RunOptionsError as N, RunCostEstimator as O, RunOptionsRequirements as P, RunTransientContextHook as Q, RunSchedulingHook as R, RunContextPreparationError as S, RunCostEstimate as T, RunSubagentHook as U, RunSubagentDigests as V, RunSubagentJoinRequest as W, RunToolFailureObserver as X, RunToolCallDescriptor as Y, RunToolScheduling as Z, RunBudgetHook as _, ChildEstablishWaiting as a, RunUsageDelta as at, RunContextHook as b, ModelToolFailure as c, ProgrammaticPreflightFailure as d, RunTurnResume as et, ProgrammaticToolFailure as f, RunApprovalRequest as g, RunApprovalHook as h, ChildEstablishStatus as i, RunTurnUsage as it, RunInputHook as j, RunDurabilityHook as k, ModelUsageAccounting as l, RunApprovalDecision as m, ChildEstablishDenied as n, RunTurnResumeSettledCall as nt, CommandDrainPolicy as o, ToolFailureObservation as ot, ResolvedModelCall as p, RunToolAuthorizationHook as q, ChildEstablishSettled as r, RunTurnResumeSettledCallSchema as rt, CurrentToolFailureObserver as s, toolFailureObserverLayer as st, AgentUpdateAcceptance as t, RunTurnResumeCall as tt, PreparedRunContext as u, RunBufferLimits as v, RunContextRequest as w, RunContextPreparation as x, RunCompactionCommit as y, RunSchedulingOverride as z };
915
- //# sourceMappingURL=RunOptions-g1aigcKI.d.mts.map
921
+ //# sourceMappingURL=RunOptions-CE-G3niT.d.mts.map
@@ -1,5 +1,5 @@
1
1
  import { a as Receipt } from "./Receipt-BAHyigAF.mjs";
2
- import { _ as Digest, h as DefinitionDigests } from "./Records-vFp_ZQ9Y.mjs";
2
+ import { _ as Digest, h as DefinitionDigests } from "./Records-B84j3Jq_.mjs";
3
3
  import { Context, Effect, Schema } from "effect";
4
4
  declare namespace Schedule_d_exports {
5
5
  export { ScheduleAuthorizationDecision, ScheduleAuthorizationError, ScheduleAuthorizer, ScheduleCapacityError, ScheduleChange, ScheduleConfiguration, ScheduleConflict, ScheduleDestination, ScheduleDueCursor, ScheduleFailpoint, ScheduleFailpointError, ScheduleId, ScheduleInstant, ScheduleKey, ScheduleManagementAuthorization, ScheduleManagementOperation, ScheduleNotFound, ScheduleOccurrenceAuthorization, ScheduleOwner, SchedulePage, SchedulePageRequest, SchedulePending, ScheduleRecord, ScheduleRefusal, ScheduleRetry, ScheduleRetryReason, ScheduleScope, ScheduleSkippedRange, ScheduleSnapshot, ScheduleSnapshotPage, ScheduleStorageError, ScheduleStore, ScheduleStoreFailure, ScheduleTiming, ScheduleTimingRequest, ScheduleValidationError, ScheduleWake, ScheduledEnvelope, ScheduledInputAdmission, ScheduledInputFailure, ScheduledInputRefused, ScheduledInputRetryable, SchedulingLimits, defaultSchedulingLimits };
@@ -839,4 +839,4 @@ declare const ScheduleFailpoint: Context.Reference<{
839
839
  }>;
840
840
  //#endregion
841
841
  export { ScheduleSnapshotPage as A, ScheduledInputAdmission as B, ScheduleRecord as C, ScheduleScope as D, ScheduleRetryReason as E, ScheduleTimingRequest as F, defaultSchedulingLimits as G, ScheduledInputRefused as H, ScheduleValidationError as I, ScheduleWake as L, ScheduleStore as M, ScheduleStoreFailure as N, ScheduleSkippedRange as O, ScheduleTiming as P, Schedule_d_exports as R, SchedulePending as S, ScheduleRetry as T, ScheduledInputRetryable as U, ScheduledInputFailure as V, SchedulingLimits as W, ScheduleNotFound as _, ScheduleChange as a, SchedulePage as b, ScheduleDestination as c, ScheduleFailpointError as d, ScheduleId as f, ScheduleManagementOperation as g, ScheduleManagementAuthorization as h, ScheduleCapacityError as i, ScheduleStorageError as j, ScheduleSnapshot as k, ScheduleDueCursor as l, ScheduleKey as m, ScheduleAuthorizationError as n, ScheduleConfiguration as o, ScheduleInstant as p, ScheduleAuthorizer as r, ScheduleConflict as s, ScheduleAuthorizationDecision as t, ScheduleFailpoint as u, ScheduleOccurrenceAuthorization as v, ScheduleRefusal as w, SchedulePageRequest as x, ScheduleOwner as y, ScheduledEnvelope as z };
842
- //# sourceMappingURL=Schedule-BkZvKyMw.d.mts.map
842
+ //# sourceMappingURL=Schedule-DCYBfhgT.d.mts.map
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { n as utf8ByteLength } from "./utf8-DchGZRBd.mjs";
3
2
  import { ThreadId } from "./core/Identifiers.mjs";
3
+ import { n as utf8ByteLength } from "./utf8-DchGZRBd.mjs";
4
4
  import { IdempotencyKey } from "./core/Receipt.mjs";
5
- import { T as PersistedJson, p as DefinitionDigests } from "./Records-C9cezOEf.mjs";
5
+ import { T as PersistedJson, p as DefinitionDigests } from "./Records-CsEsSW2o.mjs";
6
6
  import { digestJson } from "./durable/Digest.mjs";
7
7
  import { ScheduleAuthorizer, ScheduleConflict, ScheduleDestination, ScheduleFailpoint, ScheduleInstant, ScheduleNotFound, ScheduleStorageError, ScheduleStore, ScheduleTimingRequest, ScheduleValidationError, ScheduleWake, ScheduledInputAdmission, SchedulingLimits, defaultSchedulingLimits } from "./durable/Schedule.mjs";
8
8
  import { admitPreparedInput } from "./durable/PreparedInputAdmission.mjs";
@@ -688,4 +688,4 @@ var ScheduleDriver = class ScheduleDriver extends Context.Service()("@effect-age
688
688
  //#endregion
689
689
  export { Scheduling_exports as i, ScheduleWakeNoop as n, Scheduling as r, ScheduleDriver as t };
690
690
 
691
- //# sourceMappingURL=Scheduling-D0QqOoeT.mjs.map
691
+ //# sourceMappingURL=Scheduling-CUuYc3-D.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduling-D0QqOoeT.mjs","names":["ScheduleTimingRequestSchema","ScheduleDestinationSchema"],"sources":["../src/durable/internal/schedule-time.ts","../src/durable/Scheduling.ts"],"sourcesContent":["import { Cron, DateTime, Option, Result, Schema } from \"effect\";\n\nimport {\n ScheduleValidationError,\n ScheduleInstant,\n type ScheduleSkippedRange,\n type ScheduleTiming,\n type ScheduleTimingRequest,\n} from \"../Schedule.ts\";\n\nconst invalid = (message: string) => Result.fail(ScheduleValidationError.make({ message }));\n\nconst checkedInstant = (millis: number, label: string) =>\n Schema.decodeResult(ScheduleInstant)(millis).pipe(\n Result.mapError(() =>\n ScheduleValidationError.make({\n message: `${label} is outside the supported ScheduleInstant range`,\n }),\n ),\n );\n\nconst values = (set: ReadonlySet<number>, size: number): ReadonlyArray<number> =>\n set.size === 0 ? Array.from({ length: size }, (_, index) => index) : [...set];\n\n/**\n * Cron frequency proof without calendar enumeration. It checks the minimum circular spacing of\n * the allowed hour/minute pairs. Day restrictions may make a rule sparser, so this deliberately\n * rejects some safe rules when a configured minimum exceeds one minute.\n */\nconst validateCronFrequency = (\n cron: Cron.Cron,\n minimumMillis: number,\n): Result.Result<void, ScheduleValidationError> => {\n if (cron.seconds.size !== 1) {\n return invalid(\"Cron must select exactly one seconds value\");\n }\n if (minimumMillis <= 60_000) return Result.succeed(undefined);\n if (\n Option.isSome(cron.tz) &&\n DateTime.isTimeZoneNamed(cron.tz.value) &&\n cron.tz.value.id !== \"UTC\"\n ) {\n return invalid(\"Cron minimums above one minute require UTC or a fixed-offset time zone\");\n }\n\n const minuteOfDay = values(cron.hours, 24).flatMap((hour) =>\n values(cron.minutes, 60).map((minute) => hour * 60 + minute),\n );\n\n minuteOfDay.sort((left, right) => left - right);\n let minimumGap = 24 * 60;\n\n for (let index = 0; index < minuteOfDay.length; index += 1) {\n const current = minuteOfDay[index];\n const next = minuteOfDay[(index + 1) % minuteOfDay.length];\n\n if (current === undefined || next === undefined) continue;\n const gap = next > current ? next - current : 24 * 60 - current + next;\n\n minimumGap = Math.min(minimumGap, gap);\n }\n\n return minimumGap * 60_000 >= minimumMillis\n ? Result.succeed(undefined)\n : invalid(`Cron may fire more often than the configured ${minimumMillis}ms minimum`);\n};\n\nexport const parseScheduleCron = (\n expression: string,\n timeZone: string,\n minimumMillis: number,\n): Result.Result<Cron.Cron, ScheduleValidationError> => {\n const parsed = Cron.parse(expression, timeZone);\n\n if (Result.isFailure(parsed)) return invalid(parsed.failure.message);\n const frequency = validateCronFrequency(parsed.success, minimumMillis);\n\n return Result.isFailure(frequency)\n ? Result.fail(frequency.failure)\n : Result.succeed(parsed.success);\n};\n\nexport const normalizeScheduleTiming = (\n request: ScheduleTimingRequest,\n nowMillis: number,\n minimumMillis: number,\n): Result.Result<ScheduleTiming, ScheduleValidationError> => {\n switch (request._tag) {\n case \"At\":\n return Result.succeed(request);\n case \"After\": {\n const at = checkedInstant(nowMillis + request.delayMillis, \"Relative deadline\");\n\n return Result.map(at, (atMillis) => ({ _tag: \"At\" as const, atMillis }));\n }\n case \"Interval\": {\n if (request.everyMillis < minimumMillis) {\n return invalid(`Interval must be at least ${minimumMillis}ms`);\n }\n\n const anchor = checkedInstant(\n request.anchorMillis ?? nowMillis + request.everyMillis,\n \"Interval anchor\",\n );\n\n return Result.map(anchor, (anchorMillis) => ({\n _tag: \"Interval\" as const,\n everyMillis: request.everyMillis,\n anchorMillis,\n }));\n }\n case \"Cron\": {\n const timeZone = request.timeZone ?? \"UTC\";\n const cron = parseScheduleCron(request.expression, timeZone, minimumMillis);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.succeed({ _tag: \"Cron\", expression: request.expression, timeZone });\n }\n }\n};\n\nconst parsedStoredCron = (timing: Extract<ScheduleTiming, { _tag: \"Cron\" }>) => {\n const parsed = Cron.parse(timing.expression, timing.timeZone);\n\n return Result.isFailure(parsed)\n ? invalid(`Stored cron is invalid: ${parsed.failure.message}`)\n : Result.succeed(parsed.success);\n};\n\n/** Strictly selects the first occurrence after an instant. */\nexport const scheduleNextAfter = (\n timing: ScheduleTiming,\n afterMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n switch (timing._tag) {\n case \"At\":\n return Result.succeed(timing.atMillis > afterMillis ? timing.atMillis : null);\n case \"Interval\": {\n if (afterMillis < timing.anchorMillis) return Result.succeed(timing.anchorMillis);\n const steps = Math.floor((afterMillis - timing.anchorMillis) / timing.everyMillis) + 1;\n const next = timing.anchorMillis + steps * timing.everyMillis;\n\n return checkedInstant(next, \"Next interval occurrence\");\n }\n case \"Cron\": {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.try({\n try: () => {\n let next = Cron.next(cron.success, afterMillis).getTime();\n\n // Inside a fall fold Effect may select the first, already elapsed local instant.\n while (next <= afterMillis) {\n const following = Cron.next(cron.success, next).getTime();\n\n if (following <= next) throw new Error(\"Cron did not advance\");\n next = following;\n }\n\n return next;\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported next firing\" }),\n }).pipe(Result.flatMap((next) => checkedInstant(next, \"Next cron occurrence\")));\n }\n }\n};\n\n/** Initial cursor. Past one-shots remain due; recurring rules start strictly after registration. */\nexport const scheduleInitialCursor = (\n timing: ScheduleTiming,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> =>\n timing._tag === \"At\" ? Result.succeed(timing.atMillis) : scheduleNextAfter(timing, nowMillis);\n\nexport interface DueScheduleOccurrence {\n readonly intendedAtMillis: number;\n readonly nextAtMillis: number | null;\n readonly skippedRange: ScheduleSkippedRange | null;\n}\n\n/** Coalesces recurring occurrences using the same forward sequence as registration. */\nexport const scheduleDueOccurrence = (\n timing: ScheduleTiming,\n cursorMillis: number,\n nowMillis: number,\n): Result.Result<DueScheduleOccurrence | null, ScheduleValidationError> => {\n if (cursorMillis > nowMillis) return Result.succeed(null);\n if (timing._tag === \"At\") {\n return Result.succeed({\n intendedAtMillis: cursorMillis,\n nextAtMillis: null,\n skippedRange: null,\n });\n }\n\n let intendedAtMillis: number;\n\n if (timing._tag === \"Interval\") {\n const steps = Math.floor((nowMillis - timing.anchorMillis) / timing.everyMillis);\n\n intendedAtMillis = Math.max(cursorMillis, timing.anchorMillis + steps * timing.everyMillis);\n } else {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n const due = Result.try({\n try: () => {\n let intended = cursorMillis;\n // Reverse traversal is safe only without offset transitions. Named-zone reverse\n // traversal has different gap/fold semantics from the forward occurrence sequence.\n const zone = Option.getOrUndefined(cron.success.tz);\n\n if (zone !== undefined && (DateTime.isTimeZoneOffset(zone) || zone.id === \"UTC\")) {\n intended = Math.max(cursorMillis, Cron.prev(cron.success, nowMillis + 1_000).getTime());\n } else {\n // Seek by calendar date in UTC, where reverse traversal has no DST ambiguity.\n // Include two prior civil days to cover even IANA date-line shifts. There are no\n // matching dates between this seed day and that boundary, so forward traversal\n // visits only the seed day and the recent days, regardless of downtime length.\n const calendar = Cron.make({\n ...cron.success,\n seconds: [0],\n minutes: [0],\n hours: [0],\n tz: DateTime.zoneMakeNamedUnsafe(\"UTC\"),\n });\n\n const localDay = DateTime.makeUnsafe(\n DateTime.toDate(DateTime.makeZonedUnsafe(nowMillis, { timeZone: zone })),\n ).pipe(DateTime.startOf(\"day\"), DateTime.subtract({ days: 2 }));\n\n const seedDay = Cron.prev(calendar, DateTime.toEpochMillis(localDay) + 1_000);\n\n const seed =\n DateTime.makeZonedUnsafe(seedDay, {\n timeZone: zone,\n adjustForTimeZone: true,\n }).pipe(DateTime.toEpochMillis) - 1_000;\n\n if (seed > cursorMillis) {\n const first = Cron.next(cron.success, seed).getTime();\n\n if (first <= nowMillis) intended = Math.max(intended, first);\n }\n }\n let next = Cron.next(cron.success, intended).getTime();\n\n while (next <= nowMillis) {\n if (next <= intended) throw new Error(\"Cron did not advance\");\n intended = next;\n next = Cron.next(cron.success, intended).getTime();\n }\n\n return { intended, next };\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported due firing\" }),\n });\n\n if (Result.isFailure(due)) return Result.fail(due.failure);\n const next = checkedInstant(due.success.next, \"Next cron occurrence\");\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis: due.success.intended,\n nextAtMillis: next.success,\n skippedRange:\n due.success.intended === cursorMillis\n ? null\n : {\n fromMillis: cursorMillis,\n toMillis: due.success.intended,\n },\n });\n }\n\n const next = scheduleNextAfter(timing, nowMillis);\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis,\n nextAtMillis: next.success,\n skippedRange:\n intendedAtMillis === cursorMillis\n ? null\n : { fromMillis: cursorMillis, toMillis: intendedAtMillis },\n });\n};\n\nexport const scheduleResumeCursor = (\n timing: ScheduleTiming,\n existingCursor: number | null,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n if (timing._tag === \"At\") return Result.succeed(existingCursor);\n\n return scheduleNextAfter(timing, nowMillis);\n};\n","import {\n Cause,\n Context,\n Crypto,\n DateTime,\n Effect,\n Layer,\n Option,\n Result,\n Schema,\n Semaphore,\n} from \"effect\";\n\nimport { type AgentId, ThreadId } from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { digestJson } from \"./Digest.ts\";\nimport type { DurableSubmitAgent } from \"./DurableAgentRuntime.ts\";\nimport {\n normalizeScheduleTiming,\n scheduleDueOccurrence,\n scheduleInitialCursor,\n scheduleNextAfter,\n scheduleResumeCursor,\n} from \"./internal/schedule-time.ts\";\nimport { admitPreparedInput } from \"./PreparedInputAdmission.ts\";\nimport { DefinitionDigests, type Digest, PersistedJson } from \"./Records.ts\";\nimport {\n defaultSchedulingLimits,\n type ScheduleAuthorizationError,\n ScheduleAuthorizer,\n ScheduleConflict,\n type ScheduleConfiguration,\n ScheduleDestination as ScheduleDestinationSchema,\n type ScheduleDestination,\n ScheduleFailpoint,\n type ScheduleId,\n type ScheduleDueCursor,\n ScheduleInstant,\n type ScheduleKey,\n SchedulingLimits,\n ScheduleNotFound,\n type ScheduleOwner,\n type ScheduleRecord,\n type ScheduleRefusal,\n type ScheduleRetryReason,\n type ScheduleScope,\n type ScheduleSnapshot,\n type ScheduleSnapshotPage,\n ScheduleStorageError,\n ScheduleStore,\n type ScheduleStoreFailure,\n ScheduleTimingRequest as ScheduleTimingRequestSchema,\n type ScheduleTimingRequest,\n ScheduleValidationError,\n ScheduledInputAdmission,\n ScheduleWake,\n} from \"./Schedule.ts\";\nimport { type AdmissionFence, IdempotencyKey, type Principal } from \"./SubmissionLedger.ts\";\n\nexport interface ScheduleCreateOptions {\n readonly scope: ScheduleScope;\n readonly scheduleId: ScheduleId;\n readonly timing: ScheduleTimingRequest;\n readonly destination: ScheduleDestination;\n readonly deliveryPrincipal: Principal;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionFence;\n readonly definitions: DefinitionDigests;\n}\n\nexport interface ScheduleUpdateOptions extends ScheduleCreateOptions {\n readonly expectedRevision: number;\n}\n\nexport interface ScheduleListOptions {\n readonly after?: ScheduleId | undefined;\n readonly limit?: number | undefined;\n}\n\nexport type ScheduleManagementFailure =\n | ScheduleValidationError\n | ScheduleAuthorizationError\n | ScheduleStoreFailure;\n\nexport type ScheduleProcessFailure =\n | ScheduleValidationError\n | ScheduleStoreFailure\n | ScheduleStorageError;\n\nconst equivalentDefinitions = Schema.toEquivalence(DefinitionDigests);\nconst equivalentInput = Schema.toEquivalence(PersistedJson);\n\nconst keyOf = (scope: ScheduleScope, scheduleId: ScheduleId): ScheduleKey => ({\n owner: scope.owner,\n scheduleId,\n});\n\nconst notFound = (key: ScheduleKey) => ScheduleNotFound.make({ key });\n\nconst asSnapshot = (record: ScheduleRecord, observedAtMillis: number): ScheduleSnapshot => {\n const intendedAtMillis = record.pending?.envelope.intendedAtMillis ?? record.nextAtMillis;\n\n return {\n owner: record.owner,\n scheduleId: record.scheduleId,\n createdAtMillis: record.createdAtMillis,\n updatedAtMillis: record.updatedAtMillis,\n configurationRevision: record.configurationRevision,\n configuration: {\n timing: record.configuration.timing,\n destination: record.configuration.destination,\n deliveryPrincipal: record.configuration.deliveryPrincipal,\n ...(record.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: record.configuration.admissionGroup }),\n ...(record.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: record.configuration.admissionFence }),\n agentId: record.configuration.agentId,\n },\n state: record.state,\n nextAtMillis: record.nextAtMillis,\n pending:\n record.pending === null\n ? null\n : {\n intendedAtMillis: record.pending.envelope.intendedAtMillis,\n preparedAtMillis: record.pending.envelope.preparedAtMillis,\n configurationRevision: record.pending.envelope.configurationRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: record.pending.retry,\n },\n lastReceipt: record.lastReceipt,\n lastRefusal: record.lastRefusal,\n lastSkippedRange: record.lastSkippedRange,\n observedAtMillis,\n pendingAgeMillis:\n record.pending === null\n ? null\n : Math.max(0, observedAtMillis - record.pending.envelope.preparedAtMillis),\n latenessMillis:\n intendedAtMillis === null ? 0 : Math.max(0, observedAtMillis - intendedAtMillis),\n };\n};\n\nconst inputByteLength = (input: PersistedJson): number => utf8ByteLength(JSON.stringify(input));\n\nconst currentMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));\n\nconst validateRequestedFields = Effect.fn(\"Scheduling.validateRequestedFields\")(function* (\n options: ScheduleCreateOptions,\n) {\n yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n yield* Schema.encodeEffect(ScheduleDestinationSchema)(options.destination).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid definition digests\" })),\n );\n});\n\nconst resolveInput = Effect.fn(\"Scheduling.resolveInput\")(function* <\n InputSchema extends Schema.Top,\n>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n maximumBytes: number,\n): Effect.fn.Return<\n { readonly payload: PersistedJson; readonly digest: Digest },\n ScheduleValidationError,\n InputSchema[\"EncodingServices\"] | Crypto.Crypto\n> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to encode Agent input\" }),\n ),\n );\n\n const payload = yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n\n if (inputByteLength(payload) > maximumBytes) {\n return yield* ScheduleValidationError.make({\n message: `Encoded Agent input exceeds the configured ${maximumBytes} byte limit`,\n });\n }\n\n const digest = yield* digestJson(payload).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest encoded Agent input\" }),\n ),\n );\n\n return { payload, digest };\n});\n\nconst makeManagement = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const nowMillis = yield* currentMillis;\n\n yield* Schema.decodeEffect(ScheduleInstant)(nowMillis + limits.recoveryPollMillis).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Scheduling recovery deadline exceeds the supported instant range\",\n }),\n ),\n );\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const wake = yield* ScheduleWake;\n const crypto = yield* Crypto.Crypto;\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const fingerprint = Effect.fn(\"Scheduling.fingerprint\")(function* (\n agentId: AgentId,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n ) {\n const timing = yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n\n const destination = yield* Schema.encodeEffect(ScheduleDestinationSchema)(\n options.destination,\n ).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n\n const definitions = yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Invalid definition digests\" }),\n ),\n );\n\n return yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n registeringPrincipal: options.scope.principal,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined\n ? {}\n : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined\n ? {}\n : { admissionFence: options.admissionFence }),\n agentId,\n definitions,\n destination,\n timing,\n inputDigest,\n }),\n ).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest Schedule registration\" }),\n ),\n );\n });\n\n const configuration = (\n agentId: AgentId,\n payload: PersistedJson,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n timing: ScheduleConfiguration[\"timing\"],\n ): ScheduleConfiguration => ({\n timing,\n destination: options.destination,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined ? {} : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined ? {} : { admissionFence: options.admissionFence }),\n agentId,\n definitions: options.definitions,\n input: payload,\n inputDigest,\n });\n\n const create = Effect.fn(\"Scheduling.create\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const creationFingerprint = yield* fingerprint(\n agent.definition.id,\n resolvedInput.digest,\n options,\n );\n\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n const existing = yield* store.get(key);\n\n if (existing !== null) {\n if (existing.creationFingerprint !== creationFingerprint) {\n return yield* ScheduleConflict.make({ reason: \"creation\", key });\n }\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: existing.configuration,\n });\n\n return asSnapshot(existing, nowMillis);\n }\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(options.timing, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis = yield* Effect.fromResult(scheduleInitialCursor(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const record: ScheduleRecord = {\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n creationFingerprint,\n createdBy: options.scope.principal,\n createdAtMillis: nowMillis,\n updatedAtMillis: nowMillis,\n configurationRevision: 1,\n version: 1,\n configuration: nextConfiguration,\n state: \"active\",\n nextAtMillis,\n pending: null,\n lastReceipt: null,\n lastRefusal: null,\n lastSkippedRange: null,\n };\n\n const inserted = yield* store.insert(record, limits.maxSchedulesPerOwner);\n\n yield* wake.notify;\n\n return asSnapshot(inserted, nowMillis);\n });\n\n const update = Effect.fn(\"Scheduling.update\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n yield* validateRequestedFields(options);\n const existing = yield* store.get(key);\n\n if (existing === null) return yield* notFound(key);\n if (existing.configurationRevision !== options.expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const timingRequest =\n options.timing._tag === \"Interval\" &&\n options.timing.anchorMillis === undefined &&\n existing.configuration.timing._tag === \"Interval\" &&\n existing.configuration.timing.everyMillis === options.timing.everyMillis\n ? { ...options.timing, anchorMillis: existing.configuration.timing.anchorMillis }\n : options.timing;\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(timingRequest, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis =\n timing._tag === \"At\"\n ? timing.atMillis\n : yield* Effect.fromResult(scheduleNextAfter(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const changed = yield* store.change(\n key,\n {\n _tag: \"Update\",\n expectedRevision: options.expectedRevision,\n configuration: nextConfiguration,\n nextAtMillis,\n nowMillis,\n },\n limits.maxSchedulesPerOwner,\n );\n\n yield* wake.notify;\n\n return asSnapshot(changed, nowMillis);\n });\n\n const get = Effect.fn(\"Scheduling.get\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) {\n yield* authorizer.manage({ operation: \"get\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n return asSnapshot(record, yield* currentMillis);\n });\n\n const list = Effect.fn(\"Scheduling.list\")(function* (\n scope: ScheduleScope,\n options: ScheduleListOptions = {},\n ) {\n yield* authorizer.manage({ operation: \"list\", scope });\n const limit = options.limit ?? 50;\n\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n return yield* ScheduleValidationError.make({\n message: \"Schedule page limit must be an integer from 1 through 100\",\n });\n }\n\n const page = yield* store.list({\n owner: scope.owner,\n ...(options.after === undefined ? {} : { after: options.after }),\n limit,\n });\n\n const nowMillis = yield* currentMillis;\n\n return { items: page.items.map((record) => asSnapshot(record, nowMillis)), next: page.next };\n });\n\n const control = Effect.fn(\"Scheduling.control\")(function* (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ): Effect.fn.Return<ScheduleSnapshot, ScheduleManagementFailure> {\n yield* authorizer.manage({ operation, scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n\n const attempt = (): Effect.Effect<ScheduleRecord, ScheduleManagementFailure> =>\n Effect.suspend(() =>\n Effect.gen(function* () {\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n if (operation === \"resume\" && record.state === \"active\") return record;\n const nowMillis = yield* currentMillis;\n\n const nextAtMillis =\n operation === \"resume\"\n ? yield* Effect.fromResult(\n scheduleResumeCursor(\n record.configuration.timing,\n record.nextAtMillis,\n nowMillis,\n ),\n )\n : operation === \"cancel\"\n ? null\n : record.nextAtMillis;\n\n const skippedRange =\n operation === \"resume\" &&\n record.configuration.timing._tag !== \"At\" &&\n record.nextAtMillis !== null &&\n nextAtMillis !== null &&\n nextAtMillis > record.nextAtMillis\n ? { fromMillis: record.nextAtMillis, toMillis: nextAtMillis }\n : null;\n\n return yield* store\n .change(\n key,\n {\n _tag: \"Control\",\n expectedRevision,\n expectedVersion: record.version,\n action: operation,\n nextAtMillis,\n nowMillis,\n skippedRange,\n },\n limits.maxSchedulesPerOwner,\n )\n .pipe(\n Effect.catchTag(\"ScheduleConflict\", (error) =>\n error.reason === \"revision\" ? attempt() : Effect.fail(error),\n ),\n );\n }),\n );\n\n const changed = yield* attempt();\n\n yield* wake.notify;\n\n return asSnapshot(changed, yield* currentMillis);\n });\n\n const recover = Effect.fn(\"Scheduling.recover\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) {\n yield* authorizer.manage({ operation: \"recover\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision)\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n const time = yield* currentMillis;\n\n if (record.pending === null) return asSnapshot(record, time);\n\n const recovered = yield* store.change(key, {\n _tag: \"Recover\",\n expectedGeneration,\n expectedRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n nowMillis: time,\n });\n\n yield* wake.notify;\n\n return asSnapshot(recovered, time);\n });\n\n return Scheduling.of({\n recover,\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n });\n\nconst makeDriver = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const admission = yield* ScheduledInputAdmission;\n const failpoint = yield* ScheduleFailpoint;\n const crypto = yield* Crypto.Crypto;\n const admissionSemaphore = yield* Semaphore.make(limits.admissionConcurrency);\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const retry = Effect.fn(\"Scheduling.retry\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n reason: ScheduleRetryReason,\n nowMillis: number,\n ) {\n if (record.pending === null) return record;\n const current = record.pending.retry;\n\n const delay = Math.min(\n limits.retryBaseMillis * 2 ** Math.min(current.attempts, 52),\n limits.retryMaxMillis,\n );\n\n return yield* store.change(key, {\n _tag: \"Retry\",\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: {\n generation: current.generation,\n attempts: current.attempts + 1,\n automaticAttempts: current.automaticAttempts + 1,\n parked: current.automaticAttempts + 1 >= (limits.maxAutomaticAttempts ?? 8),\n nextAttemptAtMillis: Math.min(nowMillis + delay, 8_640_000_000_000_000),\n lastAttemptAtMillis: nowMillis,\n lastFailure: reason,\n },\n nowMillis,\n });\n });\n\n const verifyPending = Effect.fn(\"Scheduling.verifyPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n ) {\n const pending = record.pending;\n\n if (pending === null) return;\n const envelope = pending.envelope;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: envelope.owner,\n scheduleId: envelope.scheduleId,\n configurationRevision: envelope.configurationRevision,\n intendedAtMillis: envelope.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"process\")));\n\n const usesCurrentConfiguration =\n envelope.configurationRevision === record.configurationRevision;\n\n const expectedThreadId = usesCurrentConfiguration\n ? record.configuration.destination._tag === \"ExistingThread\"\n ? record.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${envelope.occurrenceId}`)\n : null;\n\n const expectedAdmissionKey = Schema.decodeSync(IdempotencyKey)(\n `schedule-occurrence:${envelope.occurrenceId}`,\n );\n\n const digest = yield* withCrypto(digestJson(envelope.input)).pipe(\n Effect.mapError(() => corrupt(\"process\")),\n );\n\n if (\n envelope.schemaVersion !== 1 ||\n envelope.owner.tenantId !== key.owner.tenantId ||\n envelope.owner.ownerId !== key.owner.ownerId ||\n envelope.scheduleId !== key.scheduleId ||\n envelope.configurationRevision > record.configurationRevision ||\n envelope.occurrenceId !== occurrenceId ||\n (usesCurrentConfiguration &&\n (envelope.deliveryPrincipal !== record.configuration.deliveryPrincipal ||\n envelope.agentId !== record.configuration.agentId ||\n !equivalentDefinitions(envelope.definitions, record.configuration.definitions) ||\n !equivalentInput(envelope.input, record.configuration.input) ||\n envelope.inputDigest !== record.configuration.inputDigest)) ||\n envelope.inputDigest !== digest ||\n (expectedThreadId !== null && envelope.threadId !== expectedThreadId) ||\n envelope.admissionKey !== expectedAdmissionKey\n ) {\n return yield* corrupt(\"process\");\n }\n });\n\n const deliverPending = Effect.fn(\"Scheduling.deliverPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n nowMillis: number,\n ) {\n if (\n record.pending === null ||\n record.pending.retry.parked === true ||\n record.pending.retry.nextAttemptAtMillis > nowMillis\n ) {\n return record;\n }\n yield* verifyPending(key, record);\n const envelope = record.pending.envelope;\n\n const outcome = yield* admissionSemaphore.withPermit(\n admitPreparedInput(admission.submit(envelope), limits.admissionTimeoutMillis).pipe(\n Effect.tap((outcome) =>\n outcome._tag === \"Receipt\" ? failpoint.hit(\"schedule:admission:after\") : Effect.void,\n ),\n ),\n );\n\n const completedAtMillis = yield* currentMillis;\n\n if (outcome._tag === \"Receipt\") {\n if (outcome.receipt.threadId !== envelope.threadId) {\n return yield* corrupt(\"admission\");\n }\n\n return yield* store\n .change(key, {\n _tag: \"Complete\",\n occurrenceId: envelope.occurrenceId,\n receipt: outcome.receipt,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n if (outcome._tag === \"Refused\") {\n const refusal: ScheduleRefusal = {\n atMillis: completedAtMillis,\n intendedAtMillis: envelope.intendedAtMillis,\n occurrenceId: envelope.occurrenceId,\n phase: \"admission\",\n code: outcome.error.code,\n };\n\n return yield* store\n .change(key, {\n _tag: \"Refuse\",\n occurrenceId: envelope.occurrenceId,\n refusal,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n\n return yield* retry(key, record, outcome.reason, completedAtMillis);\n });\n\n const processRecord = Effect.fn(\"Scheduling.processRecord\")(function* (\n key: ScheduleKey,\n initial: ScheduleRecord,\n nowMillis: number,\n ): Effect.fn.Return<ScheduleRecord, ScheduleProcessFailure> {\n if (initial.pending !== null) return yield* deliverPending(key, initial, nowMillis);\n if (\n initial.state !== \"active\" ||\n initial.nextAtMillis === null ||\n initial.nextAtMillis > nowMillis\n ) {\n return initial;\n }\n\n const currentInputDigest = yield* withCrypto(digestJson(initial.configuration.input)).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"prepare\", reason: \"unavailable\" }),\n ),\n );\n\n if (currentInputDigest !== initial.configuration.inputDigest) {\n return yield* corrupt(\"prepare\");\n }\n\n const due = yield* Effect.fromResult(\n scheduleDueOccurrence(initial.configuration.timing, initial.nextAtMillis, nowMillis),\n );\n\n if (due === null) return initial;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"prepare\")));\n\n const occurrence = {\n key,\n configurationRevision: initial.configurationRevision,\n configuration: initial.configuration,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n };\n\n const authorization = yield* authorizer.prepare(occurrence).pipe(Effect.result);\n\n if (Result.isFailure(authorization)) {\n if (authorization.failure._tag === \"ScheduleStorageError\") {\n return yield* authorization.failure;\n }\n\n return yield* store.change(key, {\n _tag: \"DenyPreparation\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n refusal: {\n atMillis: nowMillis,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n phase: \"preparation\",\n code: authorization.failure.code,\n },\n nowMillis,\n });\n }\n\n const threadId =\n initial.configuration.destination._tag === \"ExistingThread\"\n ? initial.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${occurrenceId}`);\n\n const admissionKey = Schema.decodeSync(IdempotencyKey)(`schedule-occurrence:${occurrenceId}`);\n\n const prepared = yield* store.change(key, {\n _tag: \"Prepare\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n envelope: {\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n preparedAtMillis: nowMillis,\n occurrenceId,\n threadId,\n deliveryPrincipal: initial.configuration.deliveryPrincipal,\n ...(initial.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: initial.configuration.admissionGroup }),\n ...(initial.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: initial.configuration.admissionFence }),\n agentId: initial.configuration.agentId,\n definitions: initial.configuration.definitions,\n input: initial.configuration.input,\n inputDigest: initial.configuration.inputDigest,\n admissionKey,\n authorization: authorization.success,\n },\n nextAtMillis: due.nextAtMillis,\n skippedRange: due.skippedRange,\n nowMillis,\n });\n\n return yield* deliverPending(key, prepared, nowMillis);\n });\n\n const process = Effect.fn(\"Scheduling.process\")(function* (key: ScheduleKey) {\n const nowMillis = yield* currentMillis;\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n const processed = yield* processRecord(key, record, nowMillis).pipe(\n Effect.catchTag(\"ScheduleConflict\", () =>\n store\n .get(key)\n .pipe(\n Effect.flatMap((current) =>\n current === null\n ? Effect.fail(notFound(key))\n : processRecord(key, current, nowMillis),\n ),\n ),\n ),\n );\n\n return processed;\n });\n\n const runDue = Effect.fn(\"ScheduleDriver.runDue\")(function* (owner?: ScheduleOwner) {\n const nowMillis = yield* currentMillis;\n let after: ScheduleDueCursor | undefined;\n let processed = 0;\n let failed = 0;\n\n while (true) {\n const due = yield* store.due(nowMillis, limits.dueBatchSize, owner, after);\n\n if (due.length === 0) break;\n yield* Effect.forEach(\n due,\n (key) =>\n process(key).pipe(\n Effect.matchCauseEffect({\n onSuccess: () =>\n Effect.sync(() => {\n processed += 1;\n }),\n onFailure: (cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.gen(function* () {\n failed += 1;\n yield* Effect.logWarning(\"Schedule processing failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n );\n }),\n }),\n ),\n { concurrency: limits.admissionConcurrency },\n );\n after = due.at(-1);\n if (due.length < limits.dueBatchSize) break;\n }\n\n return { processed, failed };\n });\n\n return ScheduleDriver.of({ process, runDue });\n });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst validateLimits = (limits: SchedulingLimits) =>\n Schema.decodeEffect(SchedulingLimits)(limits).pipe(\n Effect.mapError((error) =>\n ScheduleValidationError.make({ message: `Invalid Scheduling limits: ${error.message}` }),\n ),\n Effect.filterOrFail(\n (validated) => validated.retryBaseMillis <= validated.retryMaxMillis,\n () =>\n ScheduleValidationError.make({\n message: \"Scheduling retryBaseMillis must not exceed retryMaxMillis\",\n }),\n ),\n );\n\nexport class Scheduling extends Context.Service<\n Scheduling,\n {\n readonly create: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly update: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly get: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly list: (\n scope: ScheduleScope,\n options?: ScheduleListOptions,\n ) => Effect.Effect<ScheduleSnapshotPage, ScheduleManagementFailure>;\n readonly pause: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly resume: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly recover: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly cancel: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n }\n>()(\"@effect-agent/thread/Scheduling\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n Scheduling,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduleWake | Crypto.Crypto\n > {\n return Layer.effect(Scheduling, validateLimits(limits).pipe(Effect.flatMap(makeManagement)));\n }\n}\n\nexport const ScheduleWakeNoop: Layer.Layer<ScheduleWake> = Layer.succeed(ScheduleWake, {\n notify: Effect.void,\n await: Effect.never,\n});\n\n/** Privileged host capability. Never provide this service to management callers or model tools. */\nexport class ScheduleDriver extends Context.Service<\n ScheduleDriver,\n {\n readonly process: (key: ScheduleKey) => Effect.Effect<ScheduleRecord, ScheduleProcessFailure>;\n readonly runDue: (\n owner?: ScheduleOwner,\n ) => Effect.Effect<\n { readonly processed: number; readonly failed: number },\n ScheduleStorageError\n >;\n }\n>()(\"@effect-agent/thread/ScheduleDriver\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n ScheduleDriver,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduledInputAdmission | Crypto.Crypto\n > {\n return Layer.effect(ScheduleDriver, validateLimits(limits).pipe(Effect.flatMap(makeDriver)));\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,WAAW,YAAoB,OAAO,KAAK,wBAAwB,KAAK,EAAE,QAAQ,CAAC,CAAC;AAE1F,MAAM,kBAAkB,QAAgB,UACtC,OAAO,aAAa,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC,KAC3C,OAAO,eACL,wBAAwB,KAAK,EAC3B,SAAS,GAAG,MAAM,iDACpB,CAAC,CACH,CACF;AAEF,MAAM,UAAU,KAA0B,SACxC,IAAI,SAAS,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAAG,UAAU,KAAK,IAAI,CAAC,GAAG,GAAG;;;;;;AAO9E,MAAM,yBACJ,MACA,kBACiD;CACjD,IAAI,KAAK,QAAQ,SA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ACzF,GACA,OAAO,cACJ,cAAc,UAAU,mBAAmB,UAAU,sBAEpD,wBAAwB,KAAK,EAC3B,SAAS,4DACX,CAAC,CACL,CACF;AAEF,IAAa,aAAb,MAAa,mBAAmB,QAAQ,QAmDtC,CAAC,CAAC,iCAAiC,CAAC,CAAC;CACrC,OAAO,MACL,SAA2B,yBAK3B;EACA,OAAO,MAAM,OAAO,YAAY,eAAe,MAAM,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC,CAAC;CAC7F;AACF;AAEA,MAAa,mBAA8C,MAAM,QAAQ,cAAc;CACrF,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CAAC;;AAGD,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAW1C,CAAC,CAAC,qCAAqC,CAAC,CAAC;CACzC,OAAO,MACL,SAA2B,yBAK3B;EACA,OAAO,MAAM,OAAO,gBAAgB,eAAe,MAAM,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC,CAAC;CAC7F;AACF"}
1
+ {"version":3,"file":"Scheduling-CUuYc3-D.mjs","names":["ScheduleTimingRequestSchema","ScheduleDestinationSchema"],"sources":["../src/durable/internal/schedule-time.ts","../src/durable/Scheduling.ts"],"sourcesContent":["import { Cron, DateTime, Option, Result, Schema } from \"effect\";\n\nimport {\n ScheduleValidationError,\n ScheduleInstant,\n type ScheduleSkippedRange,\n type ScheduleTiming,\n type ScheduleTimingRequest,\n} from \"../Schedule.ts\";\n\nconst invalid = (message: string) => Result.fail(ScheduleValidationError.make({ message }));\n\nconst checkedInstant = (millis: number, label: string) =>\n Schema.decodeResult(ScheduleInstant)(millis).pipe(\n Result.mapError(() =>\n ScheduleValidationError.make({\n message: `${label} is outside the supported ScheduleInstant range`,\n }),\n ),\n );\n\nconst values = (set: ReadonlySet<number>, size: number): ReadonlyArray<number> =>\n set.size === 0 ? Array.from({ length: size }, (_, index) => index) : [...set];\n\n/**\n * Cron frequency proof without calendar enumeration. It checks the minimum circular spacing of\n * the allowed hour/minute pairs. Day restrictions may make a rule sparser, so this deliberately\n * rejects some safe rules when a configured minimum exceeds one minute.\n */\nconst validateCronFrequency = (\n cron: Cron.Cron,\n minimumMillis: number,\n): Result.Result<void, ScheduleValidationError> => {\n if (cron.seconds.size !== 1) {\n return invalid(\"Cron must select exactly one seconds value\");\n }\n if (minimumMillis <= 60_000) return Result.succeed(undefined);\n if (\n Option.isSome(cron.tz) &&\n DateTime.isTimeZoneNamed(cron.tz.value) &&\n cron.tz.value.id !== \"UTC\"\n ) {\n return invalid(\"Cron minimums above one minute require UTC or a fixed-offset time zone\");\n }\n\n const minuteOfDay = values(cron.hours, 24).flatMap((hour) =>\n values(cron.minutes, 60).map((minute) => hour * 60 + minute),\n );\n\n minuteOfDay.sort((left, right) => left - right);\n let minimumGap = 24 * 60;\n\n for (let index = 0; index < minuteOfDay.length; index += 1) {\n const current = minuteOfDay[index];\n const next = minuteOfDay[(index + 1) % minuteOfDay.length];\n\n if (current === undefined || next === undefined) continue;\n const gap = next > current ? next - current : 24 * 60 - current + next;\n\n minimumGap = Math.min(minimumGap, gap);\n }\n\n return minimumGap * 60_000 >= minimumMillis\n ? Result.succeed(undefined)\n : invalid(`Cron may fire more often than the configured ${minimumMillis}ms minimum`);\n};\n\nexport const parseScheduleCron = (\n expression: string,\n timeZone: string,\n minimumMillis: number,\n): Result.Result<Cron.Cron, ScheduleValidationError> => {\n const parsed = Cron.parse(expression, timeZone);\n\n if (Result.isFailure(parsed)) return invalid(parsed.failure.message);\n const frequency = validateCronFrequency(parsed.success, minimumMillis);\n\n return Result.isFailure(frequency)\n ? Result.fail(frequency.failure)\n : Result.succeed(parsed.success);\n};\n\nexport const normalizeScheduleTiming = (\n request: ScheduleTimingRequest,\n nowMillis: number,\n minimumMillis: number,\n): Result.Result<ScheduleTiming, ScheduleValidationError> => {\n switch (request._tag) {\n case \"At\":\n return Result.succeed(request);\n case \"After\": {\n const at = checkedInstant(nowMillis + request.delayMillis, \"Relative deadline\");\n\n return Result.map(at, (atMillis) => ({ _tag: \"At\" as const, atMillis }));\n }\n case \"Interval\": {\n if (request.everyMillis < minimumMillis) {\n return invalid(`Interval must be at least ${minimumMillis}ms`);\n }\n\n const anchor = checkedInstant(\n request.anchorMillis ?? nowMillis + request.everyMillis,\n \"Interval anchor\",\n );\n\n return Result.map(anchor, (anchorMillis) => ({\n _tag: \"Interval\" as const,\n everyMillis: request.everyMillis,\n anchorMillis,\n }));\n }\n case \"Cron\": {\n const timeZone = request.timeZone ?? \"UTC\";\n const cron = parseScheduleCron(request.expression, timeZone, minimumMillis);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.succeed({ _tag: \"Cron\", expression: request.expression, timeZone });\n }\n }\n};\n\nconst parsedStoredCron = (timing: Extract<ScheduleTiming, { _tag: \"Cron\" }>) => {\n const parsed = Cron.parse(timing.expression, timing.timeZone);\n\n return Result.isFailure(parsed)\n ? invalid(`Stored cron is invalid: ${parsed.failure.message}`)\n : Result.succeed(parsed.success);\n};\n\n/** Strictly selects the first occurrence after an instant. */\nexport const scheduleNextAfter = (\n timing: ScheduleTiming,\n afterMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n switch (timing._tag) {\n case \"At\":\n return Result.succeed(timing.atMillis > afterMillis ? timing.atMillis : null);\n case \"Interval\": {\n if (afterMillis < timing.anchorMillis) return Result.succeed(timing.anchorMillis);\n const steps = Math.floor((afterMillis - timing.anchorMillis) / timing.everyMillis) + 1;\n const next = timing.anchorMillis + steps * timing.everyMillis;\n\n return checkedInstant(next, \"Next interval occurrence\");\n }\n case \"Cron\": {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.try({\n try: () => {\n let next = Cron.next(cron.success, afterMillis).getTime();\n\n // Inside a fall fold Effect may select the first, already elapsed local instant.\n while (next <= afterMillis) {\n const following = Cron.next(cron.success, next).getTime();\n\n if (following <= next) throw new Error(\"Cron did not advance\");\n next = following;\n }\n\n return next;\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported next firing\" }),\n }).pipe(Result.flatMap((next) => checkedInstant(next, \"Next cron occurrence\")));\n }\n }\n};\n\n/** Initial cursor. Past one-shots remain due; recurring rules start strictly after registration. */\nexport const scheduleInitialCursor = (\n timing: ScheduleTiming,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> =>\n timing._tag === \"At\" ? Result.succeed(timing.atMillis) : scheduleNextAfter(timing, nowMillis);\n\nexport interface DueScheduleOccurrence {\n readonly intendedAtMillis: number;\n readonly nextAtMillis: number | null;\n readonly skippedRange: ScheduleSkippedRange | null;\n}\n\n/** Coalesces recurring occurrences using the same forward sequence as registration. */\nexport const scheduleDueOccurrence = (\n timing: ScheduleTiming,\n cursorMillis: number,\n nowMillis: number,\n): Result.Result<DueScheduleOccurrence | null, ScheduleValidationError> => {\n if (cursorMillis > nowMillis) return Result.succeed(null);\n if (timing._tag === \"At\") {\n return Result.succeed({\n intendedAtMillis: cursorMillis,\n nextAtMillis: null,\n skippedRange: null,\n });\n }\n\n let intendedAtMillis: number;\n\n if (timing._tag === \"Interval\") {\n const steps = Math.floor((nowMillis - timing.anchorMillis) / timing.everyMillis);\n\n intendedAtMillis = Math.max(cursorMillis, timing.anchorMillis + steps * timing.everyMillis);\n } else {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n const due = Result.try({\n try: () => {\n let intended = cursorMillis;\n // Reverse traversal is safe only without offset transitions. Named-zone reverse\n // traversal has different gap/fold semantics from the forward occurrence sequence.\n const zone = Option.getOrUndefined(cron.success.tz);\n\n if (zone !== undefined && (DateTime.isTimeZoneOffset(zone) || zone.id === \"UTC\")) {\n intended = Math.max(cursorMillis, Cron.prev(cron.success, nowMillis + 1_000).getTime());\n } else {\n // Seek by calendar date in UTC, where reverse traversal has no DST ambiguity.\n // Include two prior civil days to cover even IANA date-line shifts. There are no\n // matching dates between this seed day and that boundary, so forward traversal\n // visits only the seed day and the recent days, regardless of downtime length.\n const calendar = Cron.make({\n ...cron.success,\n seconds: [0],\n minutes: [0],\n hours: [0],\n tz: DateTime.zoneMakeNamedUnsafe(\"UTC\"),\n });\n\n const localDay = DateTime.makeUnsafe(\n DateTime.toDate(DateTime.makeZonedUnsafe(nowMillis, { timeZone: zone })),\n ).pipe(DateTime.startOf(\"day\"), DateTime.subtract({ days: 2 }));\n\n const seedDay = Cron.prev(calendar, DateTime.toEpochMillis(localDay) + 1_000);\n\n const seed =\n DateTime.makeZonedUnsafe(seedDay, {\n timeZone: zone,\n adjustForTimeZone: true,\n }).pipe(DateTime.toEpochMillis) - 1_000;\n\n if (seed > cursorMillis) {\n const first = Cron.next(cron.success, seed).getTime();\n\n if (first <= nowMillis) intended = Math.max(intended, first);\n }\n }\n let next = Cron.next(cron.success, intended).getTime();\n\n while (next <= nowMillis) {\n if (next <= intended) throw new Error(\"Cron did not advance\");\n intended = next;\n next = Cron.next(cron.success, intended).getTime();\n }\n\n return { intended, next };\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported due firing\" }),\n });\n\n if (Result.isFailure(due)) return Result.fail(due.failure);\n const next = checkedInstant(due.success.next, \"Next cron occurrence\");\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis: due.success.intended,\n nextAtMillis: next.success,\n skippedRange:\n due.success.intended === cursorMillis\n ? null\n : {\n fromMillis: cursorMillis,\n toMillis: due.success.intended,\n },\n });\n }\n\n const next = scheduleNextAfter(timing, nowMillis);\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis,\n nextAtMillis: next.success,\n skippedRange:\n intendedAtMillis === cursorMillis\n ? null\n : { fromMillis: cursorMillis, toMillis: intendedAtMillis },\n });\n};\n\nexport const scheduleResumeCursor = (\n timing: ScheduleTiming,\n existingCursor: number | null,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n if (timing._tag === \"At\") return Result.succeed(existingCursor);\n\n return scheduleNextAfter(timing, nowMillis);\n};\n","import {\n Cause,\n Context,\n Crypto,\n DateTime,\n Effect,\n Layer,\n Option,\n Result,\n Schema,\n Semaphore,\n} from \"effect\";\n\nimport { type AgentId, ThreadId } from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { digestJson } from \"./Digest.ts\";\nimport type { DurableSubmitAgent } from \"./DurableAgentRuntime.ts\";\nimport {\n normalizeScheduleTiming,\n scheduleDueOccurrence,\n scheduleInitialCursor,\n scheduleNextAfter,\n scheduleResumeCursor,\n} from \"./internal/schedule-time.ts\";\nimport { admitPreparedInput } from \"./PreparedInputAdmission.ts\";\nimport { DefinitionDigests, type Digest, PersistedJson } from \"./Records.ts\";\nimport {\n defaultSchedulingLimits,\n type ScheduleAuthorizationError,\n ScheduleAuthorizer,\n ScheduleConflict,\n type ScheduleConfiguration,\n ScheduleDestination as ScheduleDestinationSchema,\n type ScheduleDestination,\n ScheduleFailpoint,\n type ScheduleId,\n type ScheduleDueCursor,\n ScheduleInstant,\n type ScheduleKey,\n SchedulingLimits,\n ScheduleNotFound,\n type ScheduleOwner,\n type ScheduleRecord,\n type ScheduleRefusal,\n type ScheduleRetryReason,\n type ScheduleScope,\n type ScheduleSnapshot,\n type ScheduleSnapshotPage,\n ScheduleStorageError,\n ScheduleStore,\n type ScheduleStoreFailure,\n ScheduleTimingRequest as ScheduleTimingRequestSchema,\n type ScheduleTimingRequest,\n ScheduleValidationError,\n ScheduledInputAdmission,\n ScheduleWake,\n} from \"./Schedule.ts\";\nimport { type AdmissionFence, IdempotencyKey, type Principal } from \"./SubmissionLedger.ts\";\n\nexport interface ScheduleCreateOptions {\n readonly scope: ScheduleScope;\n readonly scheduleId: ScheduleId;\n readonly timing: ScheduleTimingRequest;\n readonly destination: ScheduleDestination;\n readonly deliveryPrincipal: Principal;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionFence;\n readonly definitions: DefinitionDigests;\n}\n\nexport interface ScheduleUpdateOptions extends ScheduleCreateOptions {\n readonly expectedRevision: number;\n}\n\nexport interface ScheduleListOptions {\n readonly after?: ScheduleId | undefined;\n readonly limit?: number | undefined;\n}\n\nexport type ScheduleManagementFailure =\n | ScheduleValidationError\n | ScheduleAuthorizationError\n | ScheduleStoreFailure;\n\nexport type ScheduleProcessFailure =\n | ScheduleValidationError\n | ScheduleStoreFailure\n | ScheduleStorageError;\n\nconst equivalentDefinitions = Schema.toEquivalence(DefinitionDigests);\nconst equivalentInput = Schema.toEquivalence(PersistedJson);\n\nconst keyOf = (scope: ScheduleScope, scheduleId: ScheduleId): ScheduleKey => ({\n owner: scope.owner,\n scheduleId,\n});\n\nconst notFound = (key: ScheduleKey) => ScheduleNotFound.make({ key });\n\nconst asSnapshot = (record: ScheduleRecord, observedAtMillis: number): ScheduleSnapshot => {\n const intendedAtMillis = record.pending?.envelope.intendedAtMillis ?? record.nextAtMillis;\n\n return {\n owner: record.owner,\n scheduleId: record.scheduleId,\n createdAtMillis: record.createdAtMillis,\n updatedAtMillis: record.updatedAtMillis,\n configurationRevision: record.configurationRevision,\n configuration: {\n timing: record.configuration.timing,\n destination: record.configuration.destination,\n deliveryPrincipal: record.configuration.deliveryPrincipal,\n ...(record.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: record.configuration.admissionGroup }),\n ...(record.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: record.configuration.admissionFence }),\n agentId: record.configuration.agentId,\n },\n state: record.state,\n nextAtMillis: record.nextAtMillis,\n pending:\n record.pending === null\n ? null\n : {\n intendedAtMillis: record.pending.envelope.intendedAtMillis,\n preparedAtMillis: record.pending.envelope.preparedAtMillis,\n configurationRevision: record.pending.envelope.configurationRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: record.pending.retry,\n },\n lastReceipt: record.lastReceipt,\n lastRefusal: record.lastRefusal,\n lastSkippedRange: record.lastSkippedRange,\n observedAtMillis,\n pendingAgeMillis:\n record.pending === null\n ? null\n : Math.max(0, observedAtMillis - record.pending.envelope.preparedAtMillis),\n latenessMillis:\n intendedAtMillis === null ? 0 : Math.max(0, observedAtMillis - intendedAtMillis),\n };\n};\n\nconst inputByteLength = (input: PersistedJson): number => utf8ByteLength(JSON.stringify(input));\n\nconst currentMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));\n\nconst validateRequestedFields = Effect.fn(\"Scheduling.validateRequestedFields\")(function* (\n options: ScheduleCreateOptions,\n) {\n yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n yield* Schema.encodeEffect(ScheduleDestinationSchema)(options.destination).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid definition digests\" })),\n );\n});\n\nconst resolveInput = Effect.fn(\"Scheduling.resolveInput\")(function* <\n InputSchema extends Schema.Top,\n>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n maximumBytes: number,\n): Effect.fn.Return<\n { readonly payload: PersistedJson; readonly digest: Digest },\n ScheduleValidationError,\n InputSchema[\"EncodingServices\"] | Crypto.Crypto\n> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to encode Agent input\" }),\n ),\n );\n\n const payload = yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n\n if (inputByteLength(payload) > maximumBytes) {\n return yield* ScheduleValidationError.make({\n message: `Encoded Agent input exceeds the configured ${maximumBytes} byte limit`,\n });\n }\n\n const digest = yield* digestJson(payload).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest encoded Agent input\" }),\n ),\n );\n\n return { payload, digest };\n});\n\nconst makeManagement = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const nowMillis = yield* currentMillis;\n\n yield* Schema.decodeEffect(ScheduleInstant)(nowMillis + limits.recoveryPollMillis).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Scheduling recovery deadline exceeds the supported instant range\",\n }),\n ),\n );\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const wake = yield* ScheduleWake;\n const crypto = yield* Crypto.Crypto;\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const fingerprint = Effect.fn(\"Scheduling.fingerprint\")(function* (\n agentId: AgentId,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n ) {\n const timing = yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n\n const destination = yield* Schema.encodeEffect(ScheduleDestinationSchema)(\n options.destination,\n ).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n\n const definitions = yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Invalid definition digests\" }),\n ),\n );\n\n return yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n registeringPrincipal: options.scope.principal,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined\n ? {}\n : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined\n ? {}\n : { admissionFence: options.admissionFence }),\n agentId,\n definitions,\n destination,\n timing,\n inputDigest,\n }),\n ).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest Schedule registration\" }),\n ),\n );\n });\n\n const configuration = (\n agentId: AgentId,\n payload: PersistedJson,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n timing: ScheduleConfiguration[\"timing\"],\n ): ScheduleConfiguration => ({\n timing,\n destination: options.destination,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined ? {} : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined ? {} : { admissionFence: options.admissionFence }),\n agentId,\n definitions: options.definitions,\n input: payload,\n inputDigest,\n });\n\n const create = Effect.fn(\"Scheduling.create\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const creationFingerprint = yield* fingerprint(\n agent.definition.id,\n resolvedInput.digest,\n options,\n );\n\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n const existing = yield* store.get(key);\n\n if (existing !== null) {\n if (existing.creationFingerprint !== creationFingerprint) {\n return yield* ScheduleConflict.make({ reason: \"creation\", key });\n }\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: existing.configuration,\n });\n\n return asSnapshot(existing, nowMillis);\n }\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(options.timing, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis = yield* Effect.fromResult(scheduleInitialCursor(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const record: ScheduleRecord = {\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n creationFingerprint,\n createdBy: options.scope.principal,\n createdAtMillis: nowMillis,\n updatedAtMillis: nowMillis,\n configurationRevision: 1,\n version: 1,\n configuration: nextConfiguration,\n state: \"active\",\n nextAtMillis,\n pending: null,\n lastReceipt: null,\n lastRefusal: null,\n lastSkippedRange: null,\n };\n\n const inserted = yield* store.insert(record, limits.maxSchedulesPerOwner);\n\n yield* wake.notify;\n\n return asSnapshot(inserted, nowMillis);\n });\n\n const update = Effect.fn(\"Scheduling.update\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n yield* validateRequestedFields(options);\n const existing = yield* store.get(key);\n\n if (existing === null) return yield* notFound(key);\n if (existing.configurationRevision !== options.expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const timingRequest =\n options.timing._tag === \"Interval\" &&\n options.timing.anchorMillis === undefined &&\n existing.configuration.timing._tag === \"Interval\" &&\n existing.configuration.timing.everyMillis === options.timing.everyMillis\n ? { ...options.timing, anchorMillis: existing.configuration.timing.anchorMillis }\n : options.timing;\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(timingRequest, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis =\n timing._tag === \"At\"\n ? timing.atMillis\n : yield* Effect.fromResult(scheduleNextAfter(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const changed = yield* store.change(\n key,\n {\n _tag: \"Update\",\n expectedRevision: options.expectedRevision,\n configuration: nextConfiguration,\n nextAtMillis,\n nowMillis,\n },\n limits.maxSchedulesPerOwner,\n );\n\n yield* wake.notify;\n\n return asSnapshot(changed, nowMillis);\n });\n\n const get = Effect.fn(\"Scheduling.get\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) {\n yield* authorizer.manage({ operation: \"get\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n return asSnapshot(record, yield* currentMillis);\n });\n\n const list = Effect.fn(\"Scheduling.list\")(function* (\n scope: ScheduleScope,\n options: ScheduleListOptions = {},\n ) {\n yield* authorizer.manage({ operation: \"list\", scope });\n const limit = options.limit ?? 50;\n\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n return yield* ScheduleValidationError.make({\n message: \"Schedule page limit must be an integer from 1 through 100\",\n });\n }\n\n const page = yield* store.list({\n owner: scope.owner,\n ...(options.after === undefined ? {} : { after: options.after }),\n limit,\n });\n\n const nowMillis = yield* currentMillis;\n\n return { items: page.items.map((record) => asSnapshot(record, nowMillis)), next: page.next };\n });\n\n const control = Effect.fn(\"Scheduling.control\")(function* (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ): Effect.fn.Return<ScheduleSnapshot, ScheduleManagementFailure> {\n yield* authorizer.manage({ operation, scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n\n const attempt = (): Effect.Effect<ScheduleRecord, ScheduleManagementFailure> =>\n Effect.suspend(() =>\n Effect.gen(function* () {\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n if (operation === \"resume\" && record.state === \"active\") return record;\n const nowMillis = yield* currentMillis;\n\n const nextAtMillis =\n operation === \"resume\"\n ? yield* Effect.fromResult(\n scheduleResumeCursor(\n record.configuration.timing,\n record.nextAtMillis,\n nowMillis,\n ),\n )\n : operation === \"cancel\"\n ? null\n : record.nextAtMillis;\n\n const skippedRange =\n operation === \"resume\" &&\n record.configuration.timing._tag !== \"At\" &&\n record.nextAtMillis !== null &&\n nextAtMillis !== null &&\n nextAtMillis > record.nextAtMillis\n ? { fromMillis: record.nextAtMillis, toMillis: nextAtMillis }\n : null;\n\n return yield* store\n .change(\n key,\n {\n _tag: \"Control\",\n expectedRevision,\n expectedVersion: record.version,\n action: operation,\n nextAtMillis,\n nowMillis,\n skippedRange,\n },\n limits.maxSchedulesPerOwner,\n )\n .pipe(\n Effect.catchTag(\"ScheduleConflict\", (error) =>\n error.reason === \"revision\" ? attempt() : Effect.fail(error),\n ),\n );\n }),\n );\n\n const changed = yield* attempt();\n\n yield* wake.notify;\n\n return asSnapshot(changed, yield* currentMillis);\n });\n\n const recover = Effect.fn(\"Scheduling.recover\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) {\n yield* authorizer.manage({ operation: \"recover\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision)\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n const time = yield* currentMillis;\n\n if (record.pending === null) return asSnapshot(record, time);\n\n const recovered = yield* store.change(key, {\n _tag: \"Recover\",\n expectedGeneration,\n expectedRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n nowMillis: time,\n });\n\n yield* wake.notify;\n\n return asSnapshot(recovered, time);\n });\n\n return Scheduling.of({\n recover,\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n });\n\nconst makeDriver = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const admission = yield* ScheduledInputAdmission;\n const failpoint = yield* ScheduleFailpoint;\n const crypto = yield* Crypto.Crypto;\n const admissionSemaphore = yield* Semaphore.make(limits.admissionConcurrency);\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const retry = Effect.fn(\"Scheduling.retry\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n reason: ScheduleRetryReason,\n nowMillis: number,\n ) {\n if (record.pending === null) return record;\n const current = record.pending.retry;\n\n const delay = Math.min(\n limits.retryBaseMillis * 2 ** Math.min(current.attempts, 52),\n limits.retryMaxMillis,\n );\n\n return yield* store.change(key, {\n _tag: \"Retry\",\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: {\n generation: current.generation,\n attempts: current.attempts + 1,\n automaticAttempts: current.automaticAttempts + 1,\n parked: current.automaticAttempts + 1 >= (limits.maxAutomaticAttempts ?? 8),\n nextAttemptAtMillis: Math.min(nowMillis + delay, 8_640_000_000_000_000),\n lastAttemptAtMillis: nowMillis,\n lastFailure: reason,\n },\n nowMillis,\n });\n });\n\n const verifyPending = Effect.fn(\"Scheduling.verifyPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n ) {\n const pending = record.pending;\n\n if (pending === null) return;\n const envelope = pending.envelope;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: envelope.owner,\n scheduleId: envelope.scheduleId,\n configurationRevision: envelope.configurationRevision,\n intendedAtMillis: envelope.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"process\")));\n\n const usesCurrentConfiguration =\n envelope.configurationRevision === record.configurationRevision;\n\n const expectedThreadId = usesCurrentConfiguration\n ? record.configuration.destination._tag === \"ExistingThread\"\n ? record.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${envelope.occurrenceId}`)\n : null;\n\n const expectedAdmissionKey = Schema.decodeSync(IdempotencyKey)(\n `schedule-occurrence:${envelope.occurrenceId}`,\n );\n\n const digest = yield* withCrypto(digestJson(envelope.input)).pipe(\n Effect.mapError(() => corrupt(\"process\")),\n );\n\n if (\n envelope.schemaVersion !== 1 ||\n envelope.owner.tenantId !== key.owner.tenantId ||\n envelope.owner.ownerId !== key.owner.ownerId ||\n envelope.scheduleId !== key.scheduleId ||\n envelope.configurationRevision > record.configurationRevision ||\n envelope.occurrenceId !== occurrenceId ||\n (usesCurrentConfiguration &&\n (envelope.deliveryPrincipal !== record.configuration.deliveryPrincipal ||\n envelope.agentId !== record.configuration.agentId ||\n !equivalentDefinitions(envelope.definitions, record.configuration.definitions) ||\n !equivalentInput(envelope.input, record.configuration.input) ||\n envelope.inputDigest !== record.configuration.inputDigest)) ||\n envelope.inputDigest !== digest ||\n (expectedThreadId !== null && envelope.threadId !== expectedThreadId) ||\n envelope.admissionKey !== expectedAdmissionKey\n ) {\n return yield* corrupt(\"process\");\n }\n });\n\n const deliverPending = Effect.fn(\"Scheduling.deliverPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n nowMillis: number,\n ) {\n if (\n record.pending === null ||\n record.pending.retry.parked === true ||\n record.pending.retry.nextAttemptAtMillis > nowMillis\n ) {\n return record;\n }\n yield* verifyPending(key, record);\n const envelope = record.pending.envelope;\n\n const outcome = yield* admissionSemaphore.withPermit(\n admitPreparedInput(admission.submit(envelope), limits.admissionTimeoutMillis).pipe(\n Effect.tap((outcome) =>\n outcome._tag === \"Receipt\" ? failpoint.hit(\"schedule:admission:after\") : Effect.void,\n ),\n ),\n );\n\n const completedAtMillis = yield* currentMillis;\n\n if (outcome._tag === \"Receipt\") {\n if (outcome.receipt.threadId !== envelope.threadId) {\n return yield* corrupt(\"admission\");\n }\n\n return yield* store\n .change(key, {\n _tag: \"Complete\",\n occurrenceId: envelope.occurrenceId,\n receipt: outcome.receipt,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n if (outcome._tag === \"Refused\") {\n const refusal: ScheduleRefusal = {\n atMillis: completedAtMillis,\n intendedAtMillis: envelope.intendedAtMillis,\n occurrenceId: envelope.occurrenceId,\n phase: \"admission\",\n code: outcome.error.code,\n };\n\n return yield* store\n .change(key, {\n _tag: \"Refuse\",\n occurrenceId: envelope.occurrenceId,\n refusal,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n\n return yield* retry(key, record, outcome.reason, completedAtMillis);\n });\n\n const processRecord = Effect.fn(\"Scheduling.processRecord\")(function* (\n key: ScheduleKey,\n initial: ScheduleRecord,\n nowMillis: number,\n ): Effect.fn.Return<ScheduleRecord, ScheduleProcessFailure> {\n if (initial.pending !== null) return yield* deliverPending(key, initial, nowMillis);\n if (\n initial.state !== \"active\" ||\n initial.nextAtMillis === null ||\n initial.nextAtMillis > nowMillis\n ) {\n return initial;\n }\n\n const currentInputDigest = yield* withCrypto(digestJson(initial.configuration.input)).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"prepare\", reason: \"unavailable\" }),\n ),\n );\n\n if (currentInputDigest !== initial.configuration.inputDigest) {\n return yield* corrupt(\"prepare\");\n }\n\n const due = yield* Effect.fromResult(\n scheduleDueOccurrence(initial.configuration.timing, initial.nextAtMillis, nowMillis),\n );\n\n if (due === null) return initial;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"prepare\")));\n\n const occurrence = {\n key,\n configurationRevision: initial.configurationRevision,\n configuration: initial.configuration,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n };\n\n const authorization = yield* authorizer.prepare(occurrence).pipe(Effect.result);\n\n if (Result.isFailure(authorization)) {\n if (authorization.failure._tag === \"ScheduleStorageError\") {\n return yield* authorization.failure;\n }\n\n return yield* store.change(key, {\n _tag: \"DenyPreparation\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n refusal: {\n atMillis: nowMillis,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n phase: \"preparation\",\n code: authorization.failure.code,\n },\n nowMillis,\n });\n }\n\n const threadId =\n initial.configuration.destination._tag === \"ExistingThread\"\n ? initial.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${occurrenceId}`);\n\n const admissionKey = Schema.decodeSync(IdempotencyKey)(`schedule-occurrence:${occurrenceId}`);\n\n const prepared = yield* store.change(key, {\n _tag: \"Prepare\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n envelope: {\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n preparedAtMillis: nowMillis,\n occurrenceId,\n threadId,\n deliveryPrincipal: initial.configuration.deliveryPrincipal,\n ...(initial.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: initial.configuration.admissionGroup }),\n ...(initial.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: initial.configuration.admissionFence }),\n agentId: initial.configuration.agentId,\n definitions: initial.configuration.definitions,\n input: initial.configuration.input,\n inputDigest: initial.configuration.inputDigest,\n admissionKey,\n authorization: authorization.success,\n },\n nextAtMillis: due.nextAtMillis,\n skippedRange: due.skippedRange,\n nowMillis,\n });\n\n return yield* deliverPending(key, prepared, nowMillis);\n });\n\n const process = Effect.fn(\"Scheduling.process\")(function* (key: ScheduleKey) {\n const nowMillis = yield* currentMillis;\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n const processed = yield* processRecord(key, record, nowMillis).pipe(\n Effect.catchTag(\"ScheduleConflict\", () =>\n store\n .get(key)\n .pipe(\n Effect.flatMap((current) =>\n current === null\n ? Effect.fail(notFound(key))\n : processRecord(key, current, nowMillis),\n ),\n ),\n ),\n );\n\n return processed;\n });\n\n const runDue = Effect.fn(\"ScheduleDriver.runDue\")(function* (owner?: ScheduleOwner) {\n const nowMillis = yield* currentMillis;\n let after: ScheduleDueCursor | undefined;\n let processed = 0;\n let failed = 0;\n\n while (true) {\n const due = yield* store.due(nowMillis, limits.dueBatchSize, owner, after);\n\n if (due.length === 0) break;\n yield* Effect.forEach(\n due,\n (key) =>\n process(key).pipe(\n Effect.matchCauseEffect({\n onSuccess: () =>\n Effect.sync(() => {\n processed += 1;\n }),\n onFailure: (cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.gen(function* () {\n failed += 1;\n yield* Effect.logWarning(\"Schedule processing failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n );\n }),\n }),\n ),\n { concurrency: limits.admissionConcurrency },\n );\n after = due.at(-1);\n if (due.length < limits.dueBatchSize) break;\n }\n\n return { processed, failed };\n });\n\n return ScheduleDriver.of({ process, runDue });\n });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst validateLimits = (limits: SchedulingLimits) =>\n Schema.decodeEffect(SchedulingLimits)(limits).pipe(\n Effect.mapError((error) =>\n ScheduleValidationError.make({ message: `Invalid Scheduling limits: ${error.message}` }),\n ),\n Effect.filterOrFail(\n (validated) => validated.retryBaseMillis <= validated.retryMaxMillis,\n () =>\n ScheduleValidationError.make({\n message: \"Scheduling retryBaseMillis must not exceed retryMaxMillis\",\n }),\n ),\n );\n\nexport class Scheduling extends Context.Service<\n Scheduling,\n {\n readonly create: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly update: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly get: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly list: (\n scope: ScheduleScope,\n options?: ScheduleListOptions,\n ) => Effect.Effect<ScheduleSnapshotPage, ScheduleManagementFailure>;\n readonly pause: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly resume: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly recover: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly cancel: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n }\n>()(\"@effect-agent/thread/Scheduling\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n Scheduling,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduleWake | Crypto.Crypto\n > {\n return Layer.effect(Scheduling, validateLimits(limits).pipe(Effect.flatMap(makeManagement)));\n }\n}\n\nexport const ScheduleWakeNoop: Layer.Layer<ScheduleWake> = Layer.succeed(ScheduleWake, {\n notify: Effect.void,\n await: Effect.never,\n});\n\n/** Privileged host capability. Never provide this service to management callers or model tools. */\nexport class ScheduleDriver extends Context.Service<\n ScheduleDriver,\n {\n readonly process: (key: ScheduleKey) => Effect.Effect<ScheduleRecord, ScheduleProcessFailure>;\n readonly runDue: (\n owner?: ScheduleOwner,\n ) => Effect.Effect<\n { readonly processed: number; readonly failed: number },\n ScheduleStorageError\n >;\n }\n>()(\"@effect-agent/thread/ScheduleDriver\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n ScheduleDriver,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduledInputAdmission | Crypto.Crypto\n > {\n return Layer.effect(ScheduleDriver, validateLimits(limits).pipe(Effect.flatMap(makeDriver)));\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,WAAW,YAAoB,OAAO,KAAK,wBAAwB,KAAK,EAAE,QAAQ,CAAC,CAAC;AAE1F,MAAM,kBAAkB,QAAgB,UACtC,OAAO,aAAa,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC,KAC3C,OAAO,eACL,wBAAwB,KAAK,EAC3B,SAAS,GAAG,MAAM,iDACpB,CAAC,CACH,CACF;AAEF,MAAM,UAAU,KAA0B,SACxC,IAAI,SAAS,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAAG,UAAU,KAAK,IAAI,CAAC,GAAG,GAAG;;;;;;AAO9E,MAAM,yBACJ,MACA,kBACiD;CACjD,IAAI,KAAK,QAAQ,SAAS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F,GACA,OAAO,cACJ,cAAc,UAAU,mBAAmB,UAAU,sBAEpD,wBAAwB,KAAK,EAC3B,SAAS,4DACX,CAAC,CACL,CACF;AAEF,IAAa,aAAb,MAAa,mBAAmB,QAAQ,QAmDtC,CAAC,CAAC,iCAAiC,CAAC,CAAC;CACrC,OAAO,MACL,SAA2B,yBAK3B;EACA,OAAO,MAAM,OAAO,YAAY,eAAe,MAAM,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC,CAAC;CAC7F;AACF;AAEA,MAAa,mBAA8C,MAAM,QAAQ,cAAc;CACrF,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CAAC;;AAGD,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAW1C,CAAC,CAAC,qCAAqC,CAAC,CAAC;CACzC,OAAO,MACL,SAA2B,yBAK3B;EACA,OAAO,MAAM,OAAO,gBAAgB,eAAe,MAAM,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC,CAAC;CAC7F;AACF"}
@@ -1,14 +1,14 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { AgentId, DelegationId, RunId, SettlementId, ThreadId, ToolCallId } from "./core/Identifiers.mjs";
2
3
  import { n as utf8ByteLength } from "./utf8-DchGZRBd.mjs";
3
4
  import { AgentPolicy } from "./core/AgentPolicy.mjs";
4
- import { AgentId, DelegationId, RunId, SettlementId, ThreadId, ToolCallId } from "./core/Identifiers.mjs";
5
5
  import { IdempotencyKey, JoinedToHost, Receipt } from "./core/Receipt.mjs";
6
6
  import { IdGenerator as IdGenerator$1 } from "./core/IdGenerator.mjs";
7
7
  import { BackgroundSpawnTool, DelegationTool, SubagentBudgetReservation, SubagentDelegationCaps, SubagentExecutionFailure, SubagentExecutionFailureClassification, SubagentGrant, SubagentReservationAmounts, WorkerOperationTool, narrowSubagentGrant } from "./core/SubagentContract.mjs";
8
8
  import { RunUsageReport, unknownRunTotals } from "./core/Usage.mjs";
9
9
  import { WorkerCompletion, WorkerContext, WorkerError, WorkerPage, WorkerRef, WorkerReport, WorkerStarted, WorkerSummary } from "./core/Worker.mjs";
10
10
  import { BackgroundReporting, SubagentHost, WorkerReportPreparationFailure } from "./engine/SubagentHost.mjs";
11
- import { a as SubagentDurability, i as AgentSpawner, o as SubagentDurabilityError, s as ToolCallWaiting } from "./AgentRuntime-BPjQM1Nv.mjs";
11
+ import { a as SubagentDurability, i as AgentSpawner, o as SubagentDurabilityError, s as ToolCallWaiting } from "./AgentRuntime-Cdvqw7l_.mjs";
12
12
  import { RunEventSink } from "./engine/RunEventSink.mjs";
13
13
  import { SubagentBudgetExhausted, SubagentObservedUsage, SubagentReservationRequest, SubagentReservations, makeBudgetReservationId } from "./capabilities/SubagentReservations.mjs";
14
14
  import { t as utf8Bytes } from "./utf8-BYfhEkcj.mjs";
@@ -1466,4 +1466,4 @@ function background(targetOrDeclaration, selected) {
1466
1466
  //#endregion
1467
1467
  export { delegationCapsFromPolicy as C, delegationAllocationFromPolicy as S, reporting as _, define as a, SubagentPrestartDenied as b, Worker as c, cancel as d, followUp as f, start as g, observe as h, background as i, WorkerObservation as l, list as m, SubagentResult as n, layer as o, inspect as p, Subagent_exports as r, make as s, SubagentDurableAccounting as t, awaitWorker as u, reportingToWorker as v, SubagentProjectionFailure as x, SubagentPolicy as y };
1468
1468
 
1469
- //# sourceMappingURL=Subagent-CnTzCy8k.mjs.map
1469
+ //# sourceMappingURL=Subagent-Cbfzylz1.mjs.map