@yielded/agent 0.1.0-beta.181 → 0.1.0-beta.183
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Admin-NvXFPDIM.d.mts → Admin-BgCHCGSl.d.mts} +8 -8
- package/dist/{AgentRuntime-Dx5u_FJD.d.mts → AgentRuntime-DhRchFzv.d.mts} +7 -4
- package/dist/{AgentRuntime-BAExRlgu.mjs → AgentRuntime-ILtyHuQG.mjs} +61 -45
- package/dist/AgentRuntime-ILtyHuQG.mjs.map +1 -0
- package/dist/{Digest-DjUgS5PG.d.mts → Digest-1iVcDLVm.d.mts} +2 -2
- package/dist/{Digest-ft4ku9pj.mjs → Digest-CzLJcsWv.mjs} +2 -2
- package/dist/{Digest-ft4ku9pj.mjs.map → Digest-CzLJcsWv.mjs.map} +1 -1
- package/dist/{DurableAgentRuntime-HH2muFrT.mjs → DurableAgentRuntime-Cj263rW9.mjs} +27 -57
- package/dist/DurableAgentRuntime-Cj263rW9.mjs.map +1 -0
- package/dist/{EventSource-DNyaWmyQ.d.mts → EventSource-CaA6RAtC.d.mts} +3 -3
- package/dist/InMemory.d.mts +1 -1
- package/dist/{MessageDelivery-CLzWJImC.d.mts → MessageDelivery-rlLpakO8.d.mts} +43 -43
- package/dist/{PreparedInputAdmission-BQ9UCLFS.d.mts → PreparedInputAdmission-DjbWz2lW.d.mts} +4 -4
- package/dist/{RecordFormat-BNiLpe43.d.mts → RecordFormat-CjMl0uu8.d.mts} +2 -2
- package/dist/{Records-BTnGRdcf.d.mts → Records-BP67Yz6n.d.mts} +20 -8
- package/dist/{Records-CZRedCE7.mjs → Records-bbGVHprv.mjs} +14 -10
- package/dist/Records-bbGVHprv.mjs.map +1 -0
- package/dist/{RunContinuation-CL0wBsQE.d.mts → RunContinuation-CIJRN_vC.d.mts} +5 -4
- package/dist/{RunContinuation-BF95Ncv2.mjs → RunContinuation-DJ6kkbQG.mjs} +22 -58
- package/dist/RunContinuation-DJ6kkbQG.mjs.map +1 -0
- package/dist/{RunEvent-C5jVQZ6K.d.mts → RunEvent-Bh1p4zAO.d.mts} +2 -2
- package/dist/{RunJournal-oJLo-pjS.mjs → RunJournal-DQr2dUgg.mjs} +4 -7
- package/dist/RunJournal-DQr2dUgg.mjs.map +1 -0
- package/dist/{RunOptions-BANtohGk.d.mts → RunOptions-aBHR-Eqm.d.mts} +6 -3
- package/dist/{RunStorage-DlfvMfHM.mjs → RunStorage-DblN-cmM.mjs} +2 -2
- package/dist/{RunStorage-DlfvMfHM.mjs.map → RunStorage-DblN-cmM.mjs.map} +1 -1
- package/dist/{Schedule-CDgTz0vj.d.mts → Schedule-CVLtl5rP.d.mts} +2 -2
- package/dist/{Scheduling-BebkRVc2.mjs → Scheduling-B6l0lWdr.mjs} +3 -3
- package/dist/{Scheduling-BebkRVc2.mjs.map → Scheduling-B6l0lWdr.mjs.map} +1 -1
- package/dist/{Subagent-D68fe7mr.mjs → Subagent-Bm842K7J.mjs} +43 -17
- package/dist/Subagent-Bm842K7J.mjs.map +1 -0
- package/dist/{Subagent-5ulnV6An.d.mts → Subagent-CWWmA1UQ.d.mts} +17 -5
- package/dist/{Subscription-D2yn6Eo3.d.mts → Subscription-BRsNy0TA.d.mts} +4 -4
- package/dist/{SubscriptionInput-Cog4x7Rd.d.mts → SubscriptionInput-ClCaW_kX.d.mts} +3 -3
- package/dist/{ThreadHistory-KPPBJLJb.d.mts → ThreadHistory-ajQhqZDY.d.mts} +2 -2
- package/dist/{ThreadImport-BoTfjjrz.mjs → ThreadImport-CkPAxXU5.mjs} +7 -7
- package/dist/{ThreadImport-BoTfjjrz.mjs.map → ThreadImport-CkPAxXU5.mjs.map} +1 -1
- package/dist/{ThreadImport-em89zmM-.d.mts → ThreadImport-DtRNoHIr.d.mts} +5 -5
- package/dist/{ThreadStore-D2rqtt7k.mjs → ThreadStore-C_ofHc7h.mjs} +4 -4
- package/dist/{ThreadStore-D2rqtt7k.mjs.map → ThreadStore-C_ofHc7h.mjs.map} +1 -1
- package/dist/{ThreadTransfer-BFolkpEp.mjs → ThreadTransfer-C_TRuo_9.mjs} +4 -4
- package/dist/{ThreadTransfer-BFolkpEp.mjs.map → ThreadTransfer-C_TRuo_9.mjs.map} +1 -1
- package/dist/{WorkerAdmission-DrxDrLII.mjs → WorkerAdmission-9Ka3edXj.mjs} +5 -5
- package/dist/{WorkerAdmission-DrxDrLII.mjs.map → WorkerAdmission-9Ka3edXj.mjs.map} +1 -1
- package/dist/{agent-registration-BovXT8jc.mjs → agent-registration-7kp1dHT0.mjs} +4 -4
- package/dist/{agent-registration-BovXT8jc.mjs.map → agent-registration-7kp1dHT0.mjs.map} +1 -1
- package/dist/capabilities/Commands.d.mts +1 -1
- package/dist/capabilities/Redaction.d.mts +1 -1
- package/dist/capabilities/RunHooks.d.mts +1 -1
- package/dist/capabilities/Subagent.d.mts +1 -1
- package/dist/capabilities/Subagent.mjs +1 -1
- package/dist/capabilities/SubagentReservations.d.mts +4 -1
- package/dist/capabilities/SubagentReservations.mjs +4 -1
- package/dist/capabilities/SubagentReservations.mjs.map +1 -1
- package/dist/core/RunEvent.d.mts +1 -1
- package/dist/core/RunEvent.mjs +1 -1
- package/dist/core/RunEvent.mjs.map +1 -1
- package/dist/durable/ActivityStore.d.mts +1 -1
- package/dist/durable/ActivityStore.mjs +1 -1
- package/dist/durable/Admin.d.mts +1 -1
- package/dist/durable/Admin.mjs +1 -1
- package/dist/durable/AgentRegistration.d.mts +1 -1
- package/dist/durable/AgentRegistration.mjs +1 -1
- package/dist/durable/Certification.d.mts +1 -1
- package/dist/durable/CommittedActivity.d.mts +3 -3
- package/dist/durable/CommittedActivity.mjs +3 -3
- package/dist/durable/Digest.d.mts +1 -1
- package/dist/durable/Digest.mjs +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.mjs +2 -2
- package/dist/durable/EventSource.d.mts +1 -1
- package/dist/durable/EventSource.mjs +1 -1
- package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
- package/dist/durable/LifecyclePublication.d.mts +1 -1
- package/dist/durable/LifecyclePublication.mjs +2 -2
- package/dist/durable/MessageDelivery.d.mts +1 -1
- package/dist/durable/MessageDelivery.mjs +2 -2
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +42 -42
- package/dist/durable/MessageDeliveryStoreConformance.mjs +2 -2
- package/dist/durable/PersistentHistory.d.mts +2 -2
- package/dist/durable/PersistentHistory.mjs +4 -4
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/RecordFormat.d.mts +1 -1
- package/dist/durable/RecordFormat.mjs +1 -1
- package/dist/durable/Records.d.mts +1 -1
- package/dist/durable/Records.mjs +1 -1
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/Recovery.mjs +1 -1
- package/dist/durable/RunContinuation.d.mts +3 -3
- package/dist/durable/RunContinuation.mjs +3 -3
- package/dist/durable/RunJournal.d.mts +1 -1
- package/dist/durable/RunJournal.mjs +1 -1
- package/dist/durable/RunStorage.d.mts +1 -1
- package/dist/durable/RunStorage.mjs +1 -1
- package/dist/durable/Schedule.d.mts +1 -1
- package/dist/durable/Schedule.mjs +1 -1
- package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
- package/dist/durable/ScheduleStoreConformance.mjs +1 -1
- package/dist/durable/ScheduleTransition.d.mts +1 -1
- package/dist/durable/ScheduleTransition.mjs +1 -1
- package/dist/durable/Scheduling.d.mts +3 -3
- package/dist/durable/Scheduling.mjs +1 -1
- package/dist/durable/SettlementPublisher.d.mts +1 -1
- package/dist/durable/SettlementPublisher.mjs +3 -3
- package/dist/durable/SubmissionLedger.d.mts +1 -1
- package/dist/durable/SubmissionLedger.mjs +2 -2
- package/dist/durable/SubmissionLedgerConformance.d.mts +2 -2
- package/dist/durable/SubmissionLedgerConformance.mjs +5 -5
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/Subscription.mjs +1 -1
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionInput.mjs +2 -2
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
- package/dist/durable/SubscriptionTools.d.mts +4 -4
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/SubscriptionTransition.mjs +1 -1
- package/dist/durable/Subscriptions.d.mts +6 -6
- package/dist/durable/Subscriptions.mjs +2 -2
- package/dist/durable/ThreadArchiveRange.d.mts +1 -1
- package/dist/durable/ThreadArchiveRange.mjs +1 -1
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadContextHistory.mjs +2 -2
- package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
- package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
- package/dist/durable/ThreadImport.d.mts +1 -1
- package/dist/durable/ThreadImport.mjs +1 -1
- package/dist/durable/ThreadInvariants.d.mts +3 -3
- package/dist/durable/ThreadInvariants.mjs +4 -4
- package/dist/durable/ThreadProjection.d.mts +1 -1
- package/dist/durable/ThreadProjection.mjs +1 -1
- package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
- package/dist/durable/ThreadReader.d.mts +1 -1
- package/dist/durable/ThreadReader.mjs +1 -1
- package/dist/durable/ThreadStore.d.mts +2 -2
- package/dist/durable/ThreadStore.mjs +2 -2
- package/dist/durable/ThreadStoreConformance.d.mts +2 -2
- package/dist/durable/ThreadStoreConformance.mjs +4 -4
- package/dist/durable/ThreadTransfer.d.mts +2 -2
- package/dist/durable/ThreadTransfer.mjs +1 -1
- package/dist/durable/ThreadWork.d.mts +1 -1
- package/dist/durable/ThreadWork.mjs +5 -5
- package/dist/durable/ToolReconciler.mjs +1 -1
- package/dist/durable/WorkerAdmission.d.mts +2 -2
- package/dist/durable/WorkerAdmission.mjs +1 -1
- package/dist/durable/WorkerHost.d.mts +2 -2
- package/dist/engine/AgentRuntime.d.mts +1 -1
- package/dist/engine/AgentRuntime.mjs +1 -1
- package/dist/engine/RunOptions.d.mts +1 -1
- package/dist/engine/RunOptions.mjs.map +1 -1
- package/dist/engine/ThreadHistory.d.mts +1 -1
- package/dist/index.d.mts +17 -17
- package/dist/index.mjs +12 -12
- package/dist/{run-context-reader-kpO9xhP2.d.mts → run-context-reader-DEU4REfD.d.mts} +3 -3
- package/package.json +1 -1
- package/src/capabilities/Subagent.ts +83 -28
- package/src/capabilities/SubagentReservations.ts +4 -1
- package/src/capabilities/internal/subagent-contract.ts +23 -3
- package/src/core/RunEvent.ts +1 -1
- package/src/durable/DurableAgentRuntime.ts +64 -14
- package/src/durable/Records.ts +21 -15
- package/src/durable/RunContinuation.ts +64 -125
- package/src/durable/RunJournal.ts +4 -12
- package/src/durable/internal/history-prompt.ts +10 -4
- package/src/durable/internal/initial-context.ts +1 -1
- package/src/durable/internal/prompt-history-cache.ts +8 -63
- package/src/engine/RunOptions.ts +4 -1
- package/src/engine/internal/agent-runtime.ts +422 -387
- package/dist/AgentRuntime-BAExRlgu.mjs.map +0 -1
- package/dist/DurableAgentRuntime-HH2muFrT.mjs.map +0 -1
- package/dist/Records-CZRedCE7.mjs.map +0 -1
- package/dist/RunContinuation-BF95Ncv2.mjs.map +0 -1
- package/dist/RunJournal-oJLo-pjS.mjs.map +0 -1
- package/dist/Subagent-D68fe7mr.mjs.map +0 -1
- package/dist/json-BlJVQZxN.mjs +0 -15
- package/dist/json-BlJVQZxN.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Scheduling-BebkRVc2.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) return invalid(\"Cron has no supported next firing\");\n next = following;\n }\n\n return checkedInstant(next, \"Next cron occurrence\");\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported next firing\" }),\n }).pipe(Result.flatMap((result) => result));\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) return invalid(\"Cron has no supported due firing\");\n intended = next;\n next = Cron.next(cron.success, intended).getTime();\n }\n\n return Result.succeed({ intended, next });\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported due firing\" }),\n }).pipe(Result.flatMap((result) => result));\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.fnUntraced(function* (options: ScheduleCreateOptions) {\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.fnUntraced(function* <InputSchema extends Schema.Top>(\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 = Effect.fnUntraced(function* (limits: SchedulingLimits) {\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.fnUntraced(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(Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })));\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 ? {} : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined ? {} : { 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.fnUntraced(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.fnUntraced(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.fnUntraced(function* (scope: ScheduleScope, scheduleId: ScheduleId) {\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.fnUntraced(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.fnUntraced(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(record.configuration.timing, record.nextAtMillis, nowMillis),\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 = Effect.fnUntraced(function* (limits: SchedulingLimits) {\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.fnUntraced(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.fnUntraced(function* (key: ScheduleKey, record: ScheduleRecord) {\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.fnUntraced(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.fnUntraced(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.fnUntraced(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.fnUntraced(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,QAA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S,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-B6l0lWdr.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) return invalid(\"Cron has no supported next firing\");\n next = following;\n }\n\n return checkedInstant(next, \"Next cron occurrence\");\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported next firing\" }),\n }).pipe(Result.flatMap((result) => result));\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) return invalid(\"Cron has no supported due firing\");\n intended = next;\n next = Cron.next(cron.success, intended).getTime();\n }\n\n return Result.succeed({ intended, next });\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported due firing\" }),\n }).pipe(Result.flatMap((result) => result));\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.fnUntraced(function* (options: ScheduleCreateOptions) {\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.fnUntraced(function* <InputSchema extends Schema.Top>(\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 = Effect.fnUntraced(function* (limits: SchedulingLimits) {\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.fnUntraced(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(Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })));\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 ? {} : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined ? {} : { 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.fnUntraced(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.fnUntraced(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.fnUntraced(function* (scope: ScheduleScope, scheduleId: ScheduleId) {\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.fnUntraced(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.fnUntraced(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(record.configuration.timing, record.nextAtMillis, nowMillis),\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 = Effect.fnUntraced(function* (limits: SchedulingLimits) {\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.fnUntraced(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.fnUntraced(function* (key: ScheduleKey, record: ScheduleRecord) {\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.fnUntraced(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.fnUntraced(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.fnUntraced(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.fnUntraced(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,GACxB,OAAO,QAAQ,4CAA4C;CAE7D,IAAI,iBAAiB,KAAQ,OAAO,OAAO,QAAQ,KAAA,CAAS;CAC5D,IACE,OAAO,OAAO,KAAK,EAAE,KACrB,SAAS,gBAAgB,KAAK,GAAG,KAAK,KACtC,KAAK,GAAG,MAAM,OAAO,OAErB,OAAO,QAAQ,wEAAwE;CAGzF,MAAM,cAAc,OAAO,KAAK,OAAO,EAAE,CAAC,CAAC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,CAAC;CACzC,OAAO,MACL,SAA2B,yBAK3B;EACA,OAAO,MAAM,OAAO,gBAAgB,eAAe,MAAM,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC,CAAC;CAC7F;AACF"}
|
|
@@ -4,22 +4,24 @@ import { n as utf8ByteLength } from "./utf8-B5pAmhTo.mjs";
|
|
|
4
4
|
import { AgentPolicy } from "./core/AgentPolicy.mjs";
|
|
5
5
|
import { IdempotencyKey, JoinedToHost, Receipt } from "./core/Receipt.mjs";
|
|
6
6
|
import { i as Failure, o as Value } from "./FailureDiagnostic-D9oW23Cn.mjs";
|
|
7
|
+
import { AgentPolicyError } from "./core/AgentError.mjs";
|
|
7
8
|
import { IdGenerator as IdGenerator$1 } from "./core/IdGenerator.mjs";
|
|
9
|
+
import { a as SubagentDurability, i as AgentSpawner, o as SubagentDurabilityError, s as ToolCallWaiting } from "./AgentRuntime-ILtyHuQG.mjs";
|
|
8
10
|
import { BackgroundSpawnTool, DelegationTool, SubagentBudgetReservation, SubagentDelegationCaps, SubagentExecutionFailure, SubagentExecutionFailureClassification, SubagentGrant, SubagentReservationAmounts, WorkerOperationTool, narrowSubagentGrant } from "./core/SubagentContract.mjs";
|
|
9
11
|
import { RunUsageReport, unknownRunTotals } from "./core/Usage.mjs";
|
|
10
12
|
import { C as MessageStatus, S as MessageRef, _ as WorkerStop, c as WorkerError, d as WorkerPage, f as WorkerRef, g as WorkerStarted, o as WorkerCompletion, p as WorkerReport, s as WorkerContext, v as WorkerStopped, y as WorkerSummary } from "./Worker-CtuUwYOK.mjs";
|
|
11
13
|
import { BackgroundReporting, SubagentHost, WorkerReportPreparationFailure } from "./engine/SubagentHost.mjs";
|
|
12
|
-
import { a as SubagentDurability, i as AgentSpawner, o as SubagentDurabilityError, s as ToolCallWaiting } from "./AgentRuntime-BAExRlgu.mjs";
|
|
13
14
|
import { RunEventSink } from "./engine/RunEventSink.mjs";
|
|
14
15
|
import { SubagentBudgetExhausted, SubagentObservedUsage, SubagentReservationRequest, SubagentReservations, makeBudgetReservationId } from "./capabilities/SubagentReservations.mjs";
|
|
15
16
|
import { t as utf8Bytes } from "./utf8-B770uxC3.mjs";
|
|
16
|
-
import { Cause, Clock, Context, Crypto, Duration, Effect, Exit, Layer, Option, Ref, Schema, Scope, Stream } from "effect";
|
|
17
|
+
import { Cause, Clock, Context, Crypto, DateTime, Duration, Effect, Exit, Layer, Option, Ref, Schema, Scope, Stream } from "effect";
|
|
17
18
|
import { Tool, Toolkit } from "effect/ai";
|
|
18
19
|
import { Hex } from "effect/encoding";
|
|
19
20
|
//#region src/capabilities/internal/subagent-contract.ts
|
|
20
21
|
const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
|
|
21
22
|
const Natural = Schema.Natural;
|
|
22
23
|
const FinitePositiveDuration = Schema.Duration.pipe(Schema.refine((duration) => Duration.isFinite(duration) && Duration.isPositive(duration), { expected: "a finite positive duration" }));
|
|
24
|
+
const FiniteNonNegativeDuration = Schema.Duration.pipe(Schema.refine((duration) => Duration.isFinite(duration) && !Duration.isNegative(duration), { expected: "a finite nonnegative duration" }));
|
|
23
25
|
const SubagentPolicyFields = Schema.Struct({
|
|
24
26
|
/** Total invocation slots, including reserved descendants, available through this delegation budget. */
|
|
25
27
|
maxChildren: PositiveInt,
|
|
@@ -33,6 +35,11 @@ const SubagentPolicyFields = Schema.Struct({
|
|
|
33
35
|
maxToolCalls: PositiveInt,
|
|
34
36
|
/** Wall-clock duration reserved for each child invocation. */
|
|
35
37
|
maxDuration: FinitePositiveDuration,
|
|
38
|
+
/**
|
|
39
|
+
* Time held back before the in-process parent's deadline; omitted reserves zero.
|
|
40
|
+
* Does not apply to durable attached children or background workers.
|
|
41
|
+
*/
|
|
42
|
+
parentReserveDuration: Schema.optionalKey(FiniteNonNegativeDuration),
|
|
36
43
|
maxInputTokens: Schema.optionalKey(PositiveInt),
|
|
37
44
|
maxOutputTokens: Schema.optionalKey(PositiveInt),
|
|
38
45
|
maxCostMicrousd: Schema.optionalKey(Natural),
|
|
@@ -47,9 +54,11 @@ const SubagentPolicyFields = Schema.Struct({
|
|
|
47
54
|
var SubagentPolicy = class extends Schema.Class("@effect-agent/capabilities/SubagentPolicy")(SubagentPolicyFields) {
|
|
48
55
|
/** Normalize and validate finite delegation bounds, throwing on invalid input. */
|
|
49
56
|
static make(input) {
|
|
57
|
+
const { maxDuration, parentReserveDuration, ...bounds } = input;
|
|
50
58
|
return super.make({
|
|
51
|
-
...
|
|
52
|
-
maxDuration: Duration.fromInputUnsafe(
|
|
59
|
+
...bounds,
|
|
60
|
+
maxDuration: Duration.fromInputUnsafe(maxDuration),
|
|
61
|
+
...parentReserveDuration === void 0 ? {} : { parentReserveDuration: Duration.fromInputUnsafe(parentReserveDuration) }
|
|
53
62
|
});
|
|
54
63
|
}
|
|
55
64
|
};
|
|
@@ -1015,6 +1024,7 @@ const maxEventTextLength = 4096;
|
|
|
1015
1024
|
const boundedEventText = (text) => text.length <= maxEventTextLength ? text : `${text.slice(0, 4095)}…`;
|
|
1016
1025
|
const ErrorMessage = Schema.Struct({ message: Schema.String });
|
|
1017
1026
|
const ErrorTag = Schema.Struct({ _tag: Schema.NonEmptyString });
|
|
1027
|
+
const isDurationPolicyError = (error) => Schema.is(AgentPolicyError)(error) && error.limit === "duration";
|
|
1018
1028
|
const errorMessageOf = (error) => Option.match(Schema.decodeUnknownOption(ErrorMessage)(error), {
|
|
1019
1029
|
onNone: () => String(error),
|
|
1020
1030
|
onSome: ({ message }) => message
|
|
@@ -1210,8 +1220,19 @@ function layer(delegation, modelOrBinding, options = {}) {
|
|
|
1210
1220
|
consume: (delta) => reservations.observe(reservationId, observedUsageFromDelta(delta)).pipe(Effect.orDie, Effect.andThen(seededBudget === void 0 ? Effect.void : seededBudget.consume(delta)))
|
|
1211
1221
|
};
|
|
1212
1222
|
const toolCallAllowance = childToolCallAllowance(parameters, policy, childPolicy);
|
|
1223
|
+
const childStartedAt = yield* Clock.currentTimeMillis;
|
|
1224
|
+
const durationMillis = Math.max(0, Math.min(allocation.durationMillis, Math.floor(DateTime.toEpochMillis(spawner.durationDeadline) - childStartedAt - Duration.toMillis(policy.parentReserveDuration ?? Duration.zero))));
|
|
1225
|
+
if (durationMillis === 0) return yield* SubagentBudgetExhausted.make({
|
|
1226
|
+
parentRunId,
|
|
1227
|
+
dimension: "duration",
|
|
1228
|
+
limitValue: 0,
|
|
1229
|
+
observedValue: 0
|
|
1230
|
+
});
|
|
1231
|
+
const durationDeadlineMillis = childStartedAt + durationMillis;
|
|
1232
|
+
const durationDeadline = DateTime.makeUnsafe(durationDeadlineMillis);
|
|
1213
1233
|
const childOptions = {
|
|
1214
1234
|
...seededChild,
|
|
1235
|
+
durationDeadline: seededChild?.durationDeadline === void 0 ? durationDeadline : DateTime.min(durationDeadline, seededChild.durationDeadline),
|
|
1215
1236
|
subagentGrant: grant,
|
|
1216
1237
|
delegationDepth: depth,
|
|
1217
1238
|
subagentBudget: SubagentBudgetReservation.make({
|
|
@@ -1222,7 +1243,7 @@ function layer(delegation, modelOrBinding, options = {}) {
|
|
|
1222
1243
|
budget,
|
|
1223
1244
|
...toolCallAllowance === void 0 ? {} : { toolCallAllowance }
|
|
1224
1245
|
};
|
|
1225
|
-
yield* Ref.set(startedAt,
|
|
1246
|
+
yield* Ref.set(startedAt, childStartedAt);
|
|
1226
1247
|
const childScope = yield* Scope.make();
|
|
1227
1248
|
yield* Effect.addFinalizer((exit) => Scope.close(childScope, exit));
|
|
1228
1249
|
const child = yield* spawner.spawn({
|
|
@@ -1253,14 +1274,19 @@ function layer(delegation, modelOrBinding, options = {}) {
|
|
|
1253
1274
|
...payload
|
|
1254
1275
|
});
|
|
1255
1276
|
return yield* Effect.gen(function* () {
|
|
1256
|
-
const result = yield* child.await.pipe(Effect.catch((childFailure) =>
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1277
|
+
const result = yield* child.await.pipe(Effect.catch((childFailure) => Effect.gen(function* () {
|
|
1278
|
+
if (isDurationPolicyError(childFailure) && (yield* Clock.currentTimeMillis) >= durationDeadlineMillis) return void 0;
|
|
1279
|
+
const report = yield* child.usageReport;
|
|
1280
|
+
yield* emit({
|
|
1281
|
+
_tag: "SubagentFailed",
|
|
1282
|
+
...payload,
|
|
1283
|
+
...report,
|
|
1284
|
+
errorTag: errorTagOf(childFailure),
|
|
1285
|
+
message: boundedEventText(errorMessageOf(childFailure))
|
|
1286
|
+
});
|
|
1287
|
+
return yield* Effect.fail(options.mapChildFailure === void 0 ? executionFailure("child-failed", errorTagOf(childFailure), "The child Run failed") : options.mapChildFailure(childFailure));
|
|
1288
|
+
})), Effect.timeoutOrElse({
|
|
1289
|
+
duration: Math.max(0, durationDeadlineMillis - (yield* Clock.currentTimeMillis)),
|
|
1264
1290
|
orElse: () => Effect.succeed(void 0)
|
|
1265
1291
|
}), Effect.tapCause((cause) => Cause.hasDies(cause) ? child.usageReport.pipe(Effect.flatMap((report) => emit({
|
|
1266
1292
|
_tag: "SubagentFailed",
|
|
@@ -1277,13 +1303,13 @@ function layer(delegation, modelOrBinding, options = {}) {
|
|
|
1277
1303
|
...payload,
|
|
1278
1304
|
...report,
|
|
1279
1305
|
errorTag: "SubagentBudgetExhausted",
|
|
1280
|
-
message: `Attached child exceeded its ${
|
|
1306
|
+
message: `Attached child exceeded its ${durationMillis}ms delegation duration budget`
|
|
1281
1307
|
});
|
|
1282
1308
|
return yield* SubagentBudgetExhausted.make({
|
|
1283
1309
|
parentRunId,
|
|
1284
1310
|
dimension: "duration",
|
|
1285
|
-
limitValue:
|
|
1286
|
-
observedValue:
|
|
1311
|
+
limitValue: durationMillis,
|
|
1312
|
+
observedValue: durationMillis
|
|
1287
1313
|
});
|
|
1288
1314
|
}
|
|
1289
1315
|
const report = yield* child.usageReport;
|
|
@@ -1510,4 +1536,4 @@ function background(targetOrDeclaration, selected) {
|
|
|
1510
1536
|
//#endregion
|
|
1511
1537
|
export { SubagentPolicy as _, layer as a, delegationAllocationFromPolicy as b, WorkerObservation as c, followUp as d, inspect as f, stop as g, start as h, background as i, awaitWorker as l, observe as m, SubagentResult as n, make as o, list as p, Subagent_exports as r, Worker as s, SubagentDurableAccounting as t, cancel as u, SubagentPrestartDenied as v, delegationCapsFromPolicy as x, SubagentProjectionFailure as y };
|
|
1512
1538
|
|
|
1513
|
-
//# sourceMappingURL=Subagent-
|
|
1539
|
+
//# sourceMappingURL=Subagent-Bm842K7J.mjs.map
|