effect-agent 0.1.0-beta.103 → 0.1.0-beta.106
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Agent-CM6JubNX.d.mts → Agent-Bk-mLtov.d.mts} +2 -2
- package/dist/{AgentError-CggcAQ7V.d.mts → AgentError-Bn1ytXRD.d.mts} +20 -4
- package/dist/{AgentRuntime-B1SXMVN7.d.mts → AgentRuntime-BEXToYl1.d.mts} +8 -8
- package/dist/{AgentRuntime-BWOnNc0d.mjs → AgentRuntime-e2M5UoXn.mjs} +4 -3
- package/dist/AgentRuntime-e2M5UoXn.mjs.map +1 -0
- package/dist/{DurableAgentRuntime-C9eRZS9N.mjs → DurableAgentRuntime-wd1x0TcB.mjs} +67 -36
- package/dist/DurableAgentRuntime-wd1x0TcB.mjs.map +1 -0
- package/dist/{EventSource-K7XUzurY.d.mts → EventSource-pH-v0k42.d.mts} +3 -3
- package/dist/FailureDiagnostic-BElLOoED.mjs +274 -0
- package/dist/FailureDiagnostic-BElLOoED.mjs.map +1 -0
- package/dist/FailureDiagnostic-CaAkzGHL.d.mts +223 -0
- package/dist/{Messaging-QMYhp297.d.mts → Messaging-Bl4SBKpR.d.mts} +3 -3
- package/dist/{MessagingHost-gAxs5gme.d.mts → MessagingHost-nwBMdRoh.d.mts} +3 -3
- package/dist/{Output-CjocJzsl.d.mts → Output-B6RQ5jRU.d.mts} +2 -2
- package/dist/{PreparedInputAdmission-KLk5rGFI.d.mts → PreparedInputAdmission-D3-BgmA9.d.mts} +8 -4
- package/dist/{Records-Bidb7ByL.d.mts → Records-B4S02MX1.d.mts} +201 -14
- package/dist/{RunJournal-srpbEBEy.mjs → RunJournal-BdIlgAEj.mjs} +2 -2
- package/dist/{RunJournal-srpbEBEy.mjs.map → RunJournal-BdIlgAEj.mjs.map} +1 -1
- package/dist/{RunOptions-Bruk54SE.d.mts → RunOptions-qOcPv08p.d.mts} +10 -5
- package/dist/{Schedule-Cy9up8Uf.d.mts → Schedule-D2TVEu3W.d.mts} +7 -2
- package/dist/{Scheduling-CHCsSCGo.mjs → Scheduling-DPb2QyAK.mjs} +2 -2
- package/dist/{Scheduling-CHCsSCGo.mjs.map → Scheduling-DPb2QyAK.mjs.map} +1 -1
- package/dist/{Subagent-DP0CzO16.d.mts → Subagent-BxuDuCHt.d.mts} +172 -8
- package/dist/{Subagent-C2s8PFrd.mjs → Subagent-uXWHXiKb.mjs} +64 -29
- package/dist/Subagent-uXWHXiKb.mjs.map +1 -0
- package/dist/{SubagentHost-CYcxkpRc.d.mts → SubagentHost-DEPw4YME.d.mts} +6 -3
- package/dist/{Subscription-CHyoQelH.d.mts → Subscription-nX0rz4GQ.d.mts} +3 -3
- package/dist/{SubscriptionInput-DqrHW-Ja.d.mts → SubscriptionInput-CAG3_pyJ.d.mts} +3 -3
- package/dist/{Worker--j87JI__.d.mts → Worker-Bbj9uq5H.d.mts} +5 -2
- package/dist/{agent-registration-ByeHejH3.mjs → agent-registration-B5CI-Ygk.mjs} +7 -5
- package/dist/agent-registration-B5CI-Ygk.mjs.map +1 -0
- package/dist/capabilities/Commands.d.mts +1 -1
- package/dist/capabilities/Messaging.d.mts +2 -2
- package/dist/capabilities/RunHooks.d.mts +1 -1
- package/dist/capabilities/Subagent.d.mts +2 -2
- package/dist/capabilities/Subagent.mjs +1 -1
- package/dist/core/Agent.d.mts +1 -1
- package/dist/core/AgentError.d.mts +2 -2
- package/dist/core/AgentError.mjs +19 -2
- package/dist/core/AgentError.mjs.map +1 -1
- package/dist/core/FailureDiagnostic.d.mts +2 -0
- package/dist/core/FailureDiagnostic.mjs +2 -0
- package/dist/core/Worker.d.mts +1 -1
- package/dist/core/Worker.mjs +4 -1
- package/dist/core/Worker.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 +1 -1
- package/dist/durable/CommittedActivity.mjs +1 -1
- package/dist/durable/Digest.d.mts +1 -1
- package/dist/durable/Digest.mjs +7 -7
- package/dist/durable/Digest.mjs.map +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.mjs +1 -1
- 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/GitHubWorkflowSource.mjs +1 -1
- package/dist/durable/MessageDelivery.d.mts +15 -3
- package/dist/durable/MessageDelivery.mjs +44 -24
- package/dist/durable/MessageDelivery.mjs.map +1 -1
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +4 -1
- package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
- package/dist/durable/PersistentHistory.d.mts +1 -1
- package/dist/durable/PersistentHistory.mjs +2 -2
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/PreparedInputAdmission.mjs +8 -4
- package/dist/durable/PreparedInputAdmission.mjs.map +1 -1
- package/dist/durable/Records.d.mts +1 -1
- package/dist/durable/Records.mjs +831 -2
- package/dist/durable/Records.mjs.map +1 -0
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/Recovery.mjs +1 -1
- package/dist/durable/RunJournal.d.mts +1 -1
- package/dist/durable/RunJournal.mjs +1 -1
- package/dist/durable/Schedule.d.mts +1 -1
- package/dist/durable/Schedule.mjs +12 -3
- package/dist/durable/Schedule.mjs.map +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 +2 -2
- package/dist/durable/Scheduling.mjs +1 -1
- package/dist/durable/SqlMessageDeliveryStore.mjs +13 -11
- package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -1
- package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
- package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
- package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
- package/dist/durable/SqlSubscriptionStore.mjs +1 -1
- package/dist/durable/SqlThreadNativeReads.d.mts +1 -1
- package/dist/durable/SqlThreadNativeReads.mjs +2 -2
- package/dist/durable/SubmissionLedger.d.mts +1 -1
- package/dist/durable/SubmissionLedger.mjs +6 -3
- package/dist/durable/SubmissionLedger.mjs.map +1 -1
- package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
- package/dist/durable/SubmissionLedgerConformance.mjs +1 -1
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/Subscription.mjs +1 -1
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionInput.mjs +2 -2
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
- package/dist/durable/SubscriptionTools.d.mts +3 -3
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/SubscriptionTransition.mjs +1 -1
- package/dist/durable/Subscriptions.d.mts +5 -5
- package/dist/durable/Subscriptions.mjs +1 -1
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadContextHistory.mjs +1 -1
- package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
- package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
- package/dist/durable/ThreadInvariants.d.mts +1 -1
- package/dist/durable/ThreadInvariants.mjs +2 -2
- 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/ThreadStore.d.mts +1 -1
- package/dist/durable/ThreadStore.mjs +2 -2
- package/dist/durable/ThreadStoreConformance.d.mts +1 -1
- package/dist/durable/ThreadStoreConformance.mjs +1 -1
- package/dist/durable/ToolReconciler.mjs +1 -1
- package/dist/durable/WorkerHost.d.mts +3 -3
- package/dist/engine/AgentRuntime.d.mts +1 -1
- package/dist/engine/AgentRuntime.mjs +1 -1
- package/dist/engine/MessagingHost.d.mts +1 -1
- package/dist/engine/Output.d.mts +1 -1
- package/dist/engine/RunOptions.d.mts +1 -1
- package/dist/engine/RunOptions.mjs +2 -0
- package/dist/engine/RunOptions.mjs.map +1 -1
- package/dist/engine/SubagentHost.d.mts +1 -1
- package/dist/engine/SubagentHost.mjs.map +1 -1
- package/dist/index.d.mts +18 -17
- package/dist/index.mjs +8 -7
- package/package.json +1 -1
- package/src/capabilities/internal/subagent-background.ts +66 -23
- package/src/capabilities/internal/subagent-contract.ts +4 -0
- package/src/core/AgentError.ts +20 -0
- package/src/core/FailureDiagnostic.ts +343 -0
- package/src/core/Worker.ts +4 -1
- package/src/durable/Digest.ts +22 -28
- package/src/durable/DurableAgentRuntime.ts +37 -13
- package/src/durable/MessageDelivery.ts +82 -24
- package/src/durable/PreparedInputAdmission.ts +17 -4
- package/src/durable/Records.ts +5 -15
- package/src/durable/Schedule.ts +11 -2
- package/src/durable/SqlMessageDeliveryStore.ts +21 -9
- package/src/durable/SubmissionLedger.ts +4 -1
- package/src/durable/internal/agent-registration.ts +46 -14
- package/src/durable/internal/worker-host.ts +32 -19
- package/src/engine/RunOptions.ts +11 -3
- package/src/engine/SubagentHost.ts +3 -0
- package/src/engine/internal/agent-runtime.ts +23 -16
- package/src/index.ts +1 -0
- package/dist/AgentRuntime-BWOnNc0d.mjs.map +0 -1
- package/dist/DurableAgentRuntime-C9eRZS9N.mjs.map +0 -1
- package/dist/Records-D8167fHn.mjs +0 -844
- package/dist/Records-D8167fHn.mjs.map +0 -1
- package/dist/Subagent-C2s8PFrd.mjs.map +0 -1
- package/dist/agent-registration-ByeHejH3.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Scheduling-CHCsSCGo.mjs","names":["ScheduleTimingRequestSchema","ScheduleDestinationSchema"],"sources":["../src/durable/internal/schedule-time.ts","../src/durable/Scheduling.ts"],"sourcesContent":["import { Cron, DateTime, Option, Result, Schema } from \"effect\";\n\nimport {\n ScheduleValidationError,\n ScheduleInstant,\n type ScheduleSkippedRange,\n type ScheduleTiming,\n type ScheduleTimingRequest,\n} from \"../Schedule.ts\";\n\nconst invalid = (message: string) => Result.fail(ScheduleValidationError.make({ message }));\n\nconst checkedInstant = (millis: number, label: string) =>\n Schema.decodeResult(ScheduleInstant)(millis).pipe(\n Result.mapError(() =>\n ScheduleValidationError.make({\n message: `${label} is outside the supported ScheduleInstant range`,\n }),\n ),\n );\n\nconst values = (set: ReadonlySet<number>, size: number): ReadonlyArray<number> =>\n set.size === 0 ? Array.from({ length: size }, (_, index) => index) : [...set];\n\n/**\n * Cron frequency proof without calendar enumeration. It checks the minimum circular spacing of\n * the allowed hour/minute pairs. Day restrictions may make a rule sparser, so this deliberately\n * rejects some safe rules when a configured minimum exceeds one minute.\n */\nconst validateCronFrequency = (\n cron: Cron.Cron,\n minimumMillis: number,\n): Result.Result<void, ScheduleValidationError> => {\n if (cron.seconds.size !== 1) {\n return invalid(\"Cron must select exactly one seconds value\");\n }\n if (minimumMillis <= 60_000) return Result.succeed(undefined);\n if (\n Option.isSome(cron.tz) &&\n DateTime.isTimeZoneNamed(cron.tz.value) &&\n cron.tz.value.id !== \"UTC\"\n ) {\n return invalid(\"Cron minimums above one minute require UTC or a fixed-offset time zone\");\n }\n\n const minuteOfDay = values(cron.hours, 24).flatMap((hour) =>\n values(cron.minutes, 60).map((minute) => hour * 60 + minute),\n );\n\n minuteOfDay.sort((left, right) => left - right);\n let minimumGap = 24 * 60;\n\n for (let index = 0; index < minuteOfDay.length; index += 1) {\n const current = minuteOfDay[index];\n const next = minuteOfDay[(index + 1) % minuteOfDay.length];\n\n if (current === undefined || next === undefined) continue;\n const gap = next > current ? next - current : 24 * 60 - current + next;\n\n minimumGap = Math.min(minimumGap, gap);\n }\n\n return minimumGap * 60_000 >= minimumMillis\n ? Result.succeed(undefined)\n : invalid(`Cron may fire more often than the configured ${minimumMillis}ms minimum`);\n};\n\nexport const parseScheduleCron = (\n expression: string,\n timeZone: string,\n minimumMillis: number,\n): Result.Result<Cron.Cron, ScheduleValidationError> => {\n const parsed = Cron.parse(expression, timeZone);\n\n if (Result.isFailure(parsed)) return invalid(parsed.failure.message);\n const frequency = validateCronFrequency(parsed.success, minimumMillis);\n\n return Result.isFailure(frequency)\n ? Result.fail(frequency.failure)\n : Result.succeed(parsed.success);\n};\n\nexport const normalizeScheduleTiming = (\n request: ScheduleTimingRequest,\n nowMillis: number,\n minimumMillis: number,\n): Result.Result<ScheduleTiming, ScheduleValidationError> => {\n switch (request._tag) {\n case \"At\":\n return Result.succeed(request);\n case \"After\": {\n const at = checkedInstant(nowMillis + request.delayMillis, \"Relative deadline\");\n\n return Result.map(at, (atMillis) => ({ _tag: \"At\" as const, atMillis }));\n }\n case \"Interval\": {\n if (request.everyMillis < minimumMillis) {\n return invalid(`Interval must be at least ${minimumMillis}ms`);\n }\n\n const anchor = checkedInstant(\n request.anchorMillis ?? nowMillis + request.everyMillis,\n \"Interval anchor\",\n );\n\n return Result.map(anchor, (anchorMillis) => ({\n _tag: \"Interval\" as const,\n everyMillis: request.everyMillis,\n anchorMillis,\n }));\n }\n case \"Cron\": {\n const timeZone = request.timeZone ?? \"UTC\";\n const cron = parseScheduleCron(request.expression, timeZone, minimumMillis);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.succeed({ _tag: \"Cron\", expression: request.expression, timeZone });\n }\n }\n};\n\nconst parsedStoredCron = (timing: Extract<ScheduleTiming, { _tag: \"Cron\" }>) => {\n const parsed = Cron.parse(timing.expression, timing.timeZone);\n\n return Result.isFailure(parsed)\n ? invalid(`Stored cron is invalid: ${parsed.failure.message}`)\n : Result.succeed(parsed.success);\n};\n\n/** Strictly selects the first occurrence after an instant. */\nexport const scheduleNextAfter = (\n timing: ScheduleTiming,\n afterMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n switch (timing._tag) {\n case \"At\":\n return Result.succeed(timing.atMillis > afterMillis ? timing.atMillis : null);\n case \"Interval\": {\n if (afterMillis < timing.anchorMillis) return Result.succeed(timing.anchorMillis);\n const steps = Math.floor((afterMillis - timing.anchorMillis) / timing.everyMillis) + 1;\n const next = timing.anchorMillis + steps * timing.everyMillis;\n\n return checkedInstant(next, \"Next interval occurrence\");\n }\n case \"Cron\": {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.try({\n try: () => {\n let next = Cron.next(cron.success, afterMillis).getTime();\n\n // Inside a fall fold Effect may select the first, already elapsed local instant.\n while (next <= afterMillis) {\n const following = Cron.next(cron.success, next).getTime();\n\n if (following <= next) throw new Error(\"Cron did not advance\");\n next = following;\n }\n\n return next;\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported next firing\" }),\n }).pipe(Result.flatMap((next) => checkedInstant(next, \"Next cron occurrence\")));\n }\n }\n};\n\n/** Initial cursor. Past one-shots remain due; recurring rules start strictly after registration. */\nexport const scheduleInitialCursor = (\n timing: ScheduleTiming,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> =>\n timing._tag === \"At\" ? Result.succeed(timing.atMillis) : scheduleNextAfter(timing, nowMillis);\n\nexport interface DueScheduleOccurrence {\n readonly intendedAtMillis: number;\n readonly nextAtMillis: number | null;\n readonly skippedRange: ScheduleSkippedRange | null;\n}\n\n/** Coalesces recurring occurrences using the same forward sequence as registration. */\nexport const scheduleDueOccurrence = (\n timing: ScheduleTiming,\n cursorMillis: number,\n nowMillis: number,\n): Result.Result<DueScheduleOccurrence | null, ScheduleValidationError> => {\n if (cursorMillis > nowMillis) return Result.succeed(null);\n if (timing._tag === \"At\") {\n return Result.succeed({\n intendedAtMillis: cursorMillis,\n nextAtMillis: null,\n skippedRange: null,\n });\n }\n\n let intendedAtMillis: number;\n\n if (timing._tag === \"Interval\") {\n const steps = Math.floor((nowMillis - timing.anchorMillis) / timing.everyMillis);\n\n intendedAtMillis = Math.max(cursorMillis, timing.anchorMillis + steps * timing.everyMillis);\n } else {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n const due = Result.try({\n try: () => {\n let intended = cursorMillis;\n // Reverse traversal is safe only without offset transitions. Named-zone reverse\n // traversal has different gap/fold semantics from the forward occurrence sequence.\n const zone = Option.getOrUndefined(cron.success.tz);\n\n if (zone !== undefined && (DateTime.isTimeZoneOffset(zone) || zone.id === \"UTC\")) {\n intended = Math.max(cursorMillis, Cron.prev(cron.success, nowMillis + 1_000).getTime());\n } else {\n // Seek by calendar date in UTC, where reverse traversal has no DST ambiguity.\n // Include two prior civil days to cover even IANA date-line shifts. There are no\n // matching dates between this seed day and that boundary, so forward traversal\n // visits only the seed day and the recent days, regardless of downtime length.\n const calendar = Cron.make({\n ...cron.success,\n seconds: [0],\n minutes: [0],\n hours: [0],\n tz: DateTime.zoneMakeNamedUnsafe(\"UTC\"),\n });\n\n const localDay = DateTime.makeUnsafe(\n DateTime.toDate(DateTime.makeZonedUnsafe(nowMillis, { timeZone: zone })),\n ).pipe(DateTime.startOf(\"day\"), DateTime.subtract({ days: 2 }));\n\n const seedDay = Cron.prev(calendar, DateTime.toEpochMillis(localDay) + 1_000);\n\n const seed =\n DateTime.makeZonedUnsafe(seedDay, {\n timeZone: zone,\n adjustForTimeZone: true,\n }).pipe(DateTime.toEpochMillis) - 1_000;\n\n if (seed > cursorMillis) {\n const first = Cron.next(cron.success, seed).getTime();\n\n if (first <= nowMillis) intended = Math.max(intended, first);\n }\n }\n let next = Cron.next(cron.success, intended).getTime();\n\n while (next <= nowMillis) {\n if (next <= intended) throw new Error(\"Cron did not advance\");\n intended = next;\n next = Cron.next(cron.success, intended).getTime();\n }\n\n return { intended, next };\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported due firing\" }),\n });\n\n if (Result.isFailure(due)) return Result.fail(due.failure);\n const next = checkedInstant(due.success.next, \"Next cron occurrence\");\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis: due.success.intended,\n nextAtMillis: next.success,\n skippedRange:\n due.success.intended === cursorMillis\n ? null\n : {\n fromMillis: cursorMillis,\n toMillis: due.success.intended,\n },\n });\n }\n\n const next = scheduleNextAfter(timing, nowMillis);\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis,\n nextAtMillis: next.success,\n skippedRange:\n intendedAtMillis === cursorMillis\n ? null\n : { fromMillis: cursorMillis, toMillis: intendedAtMillis },\n });\n};\n\nexport const scheduleResumeCursor = (\n timing: ScheduleTiming,\n existingCursor: number | null,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n if (timing._tag === \"At\") return Result.succeed(existingCursor);\n\n return scheduleNextAfter(timing, nowMillis);\n};\n","import {\n Cause,\n Context,\n Crypto,\n DateTime,\n Effect,\n Layer,\n Option,\n Result,\n Schema,\n Semaphore,\n} from \"effect\";\n\nimport { type AgentId, ThreadId } from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { digestJson } from \"./Digest.ts\";\nimport type { DurableSubmitAgent } from \"./DurableAgentRuntime.ts\";\nimport {\n normalizeScheduleTiming,\n scheduleDueOccurrence,\n scheduleInitialCursor,\n scheduleNextAfter,\n scheduleResumeCursor,\n} from \"./internal/schedule-time.ts\";\nimport { admitPreparedInput } from \"./PreparedInputAdmission.ts\";\nimport { DefinitionDigests, type Digest, PersistedJson } from \"./Records.ts\";\nimport {\n defaultSchedulingLimits,\n type ScheduleAuthorizationError,\n ScheduleAuthorizer,\n ScheduleConflict,\n type ScheduleConfiguration,\n ScheduleDestination as ScheduleDestinationSchema,\n type ScheduleDestination,\n ScheduleFailpoint,\n type ScheduleId,\n type ScheduleDueCursor,\n ScheduleInstant,\n type ScheduleKey,\n SchedulingLimits,\n ScheduleNotFound,\n type ScheduleOwner,\n type ScheduleRecord,\n type ScheduleRefusal,\n type ScheduleRetryReason,\n type ScheduleScope,\n type ScheduleSnapshot,\n type ScheduleSnapshotPage,\n ScheduleStorageError,\n ScheduleStore,\n type ScheduleStoreFailure,\n ScheduleTimingRequest as ScheduleTimingRequestSchema,\n type ScheduleTimingRequest,\n ScheduleValidationError,\n ScheduledInputAdmission,\n ScheduleWake,\n} from \"./Schedule.ts\";\nimport { type AdmissionFence, IdempotencyKey, type Principal } from \"./SubmissionLedger.ts\";\n\nexport interface ScheduleCreateOptions {\n readonly scope: ScheduleScope;\n readonly scheduleId: ScheduleId;\n readonly timing: ScheduleTimingRequest;\n readonly destination: ScheduleDestination;\n readonly deliveryPrincipal: Principal;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionFence;\n readonly definitions: DefinitionDigests;\n}\n\nexport interface ScheduleUpdateOptions extends ScheduleCreateOptions {\n readonly expectedRevision: number;\n}\n\nexport interface ScheduleListOptions {\n readonly after?: ScheduleId | undefined;\n readonly limit?: number | undefined;\n}\n\nexport type ScheduleManagementFailure =\n | ScheduleValidationError\n | ScheduleAuthorizationError\n | ScheduleStoreFailure;\n\nexport type ScheduleProcessFailure =\n | ScheduleValidationError\n | ScheduleStoreFailure\n | ScheduleStorageError;\n\nconst equivalentDefinitions = Schema.toEquivalence(DefinitionDigests);\nconst equivalentInput = Schema.toEquivalence(PersistedJson);\n\nconst keyOf = (scope: ScheduleScope, scheduleId: ScheduleId): ScheduleKey => ({\n owner: scope.owner,\n scheduleId,\n});\n\nconst notFound = (key: ScheduleKey) => ScheduleNotFound.make({ key });\n\nconst asSnapshot = (record: ScheduleRecord, observedAtMillis: number): ScheduleSnapshot => {\n const intendedAtMillis = record.pending?.envelope.intendedAtMillis ?? record.nextAtMillis;\n\n return {\n owner: record.owner,\n scheduleId: record.scheduleId,\n createdAtMillis: record.createdAtMillis,\n updatedAtMillis: record.updatedAtMillis,\n configurationRevision: record.configurationRevision,\n configuration: {\n timing: record.configuration.timing,\n destination: record.configuration.destination,\n deliveryPrincipal: record.configuration.deliveryPrincipal,\n ...(record.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: record.configuration.admissionGroup }),\n ...(record.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: record.configuration.admissionFence }),\n agentId: record.configuration.agentId,\n },\n state: record.state,\n nextAtMillis: record.nextAtMillis,\n pending:\n record.pending === null\n ? null\n : {\n intendedAtMillis: record.pending.envelope.intendedAtMillis,\n preparedAtMillis: record.pending.envelope.preparedAtMillis,\n configurationRevision: record.pending.envelope.configurationRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: record.pending.retry,\n },\n lastReceipt: record.lastReceipt,\n lastRefusal: record.lastRefusal,\n lastSkippedRange: record.lastSkippedRange,\n observedAtMillis,\n pendingAgeMillis:\n record.pending === null\n ? null\n : Math.max(0, observedAtMillis - record.pending.envelope.preparedAtMillis),\n latenessMillis:\n intendedAtMillis === null ? 0 : Math.max(0, observedAtMillis - intendedAtMillis),\n };\n};\n\nconst inputByteLength = (input: PersistedJson): number => utf8ByteLength(JSON.stringify(input));\n\nconst currentMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));\n\nconst validateRequestedFields = Effect.fn(\"Scheduling.validateRequestedFields\")(function* (\n options: ScheduleCreateOptions,\n) {\n yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n yield* Schema.encodeEffect(ScheduleDestinationSchema)(options.destination).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid definition digests\" })),\n );\n});\n\nconst resolveInput = Effect.fn(\"Scheduling.resolveInput\")(function* <\n InputSchema extends Schema.Top,\n>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n maximumBytes: number,\n): Effect.fn.Return<\n { readonly payload: PersistedJson; readonly digest: Digest },\n ScheduleValidationError,\n InputSchema[\"EncodingServices\"] | Crypto.Crypto\n> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to encode Agent input\" }),\n ),\n );\n\n const payload = yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n\n if (inputByteLength(payload) > maximumBytes) {\n return yield* ScheduleValidationError.make({\n message: `Encoded Agent input exceeds the configured ${maximumBytes} byte limit`,\n });\n }\n\n const digest = yield* digestJson(payload).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest encoded Agent input\" }),\n ),\n );\n\n return { payload, digest };\n});\n\nconst makeManagement = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const nowMillis = yield* currentMillis;\n\n yield* Schema.decodeEffect(ScheduleInstant)(nowMillis + limits.recoveryPollMillis).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Scheduling recovery deadline exceeds the supported instant range\",\n }),\n ),\n );\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const wake = yield* ScheduleWake;\n const crypto = yield* Crypto.Crypto;\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const fingerprint = Effect.fn(\"Scheduling.fingerprint\")(function* (\n agentId: AgentId,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n ) {\n const timing = yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n\n const destination = yield* Schema.encodeEffect(ScheduleDestinationSchema)(\n options.destination,\n ).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n\n const definitions = yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Invalid definition digests\" }),\n ),\n );\n\n return yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n registeringPrincipal: options.scope.principal,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined\n ? {}\n : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined\n ? {}\n : { admissionFence: options.admissionFence }),\n agentId,\n definitions,\n destination,\n timing,\n inputDigest,\n }),\n ).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest Schedule registration\" }),\n ),\n );\n });\n\n const configuration = (\n agentId: AgentId,\n payload: PersistedJson,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n timing: ScheduleConfiguration[\"timing\"],\n ): ScheduleConfiguration => ({\n timing,\n destination: options.destination,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined ? {} : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined ? {} : { admissionFence: options.admissionFence }),\n agentId,\n definitions: options.definitions,\n input: payload,\n inputDigest,\n });\n\n const create = Effect.fn(\"Scheduling.create\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const creationFingerprint = yield* fingerprint(\n agent.definition.id,\n resolvedInput.digest,\n options,\n );\n\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n const existing = yield* store.get(key);\n\n if (existing !== null) {\n if (existing.creationFingerprint !== creationFingerprint) {\n return yield* ScheduleConflict.make({ reason: \"creation\", key });\n }\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: existing.configuration,\n });\n\n return asSnapshot(existing, nowMillis);\n }\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(options.timing, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis = yield* Effect.fromResult(scheduleInitialCursor(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const record: ScheduleRecord = {\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n creationFingerprint,\n createdBy: options.scope.principal,\n createdAtMillis: nowMillis,\n updatedAtMillis: nowMillis,\n configurationRevision: 1,\n version: 1,\n configuration: nextConfiguration,\n state: \"active\",\n nextAtMillis,\n pending: null,\n lastReceipt: null,\n lastRefusal: null,\n lastSkippedRange: null,\n };\n\n const inserted = yield* store.insert(record, limits.maxSchedulesPerOwner);\n\n yield* wake.notify;\n\n return asSnapshot(inserted, nowMillis);\n });\n\n const update = Effect.fn(\"Scheduling.update\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n yield* validateRequestedFields(options);\n const existing = yield* store.get(key);\n\n if (existing === null) return yield* notFound(key);\n if (existing.configurationRevision !== options.expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const timingRequest =\n options.timing._tag === \"Interval\" &&\n options.timing.anchorMillis === undefined &&\n existing.configuration.timing._tag === \"Interval\" &&\n existing.configuration.timing.everyMillis === options.timing.everyMillis\n ? { ...options.timing, anchorMillis: existing.configuration.timing.anchorMillis }\n : options.timing;\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(timingRequest, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis =\n timing._tag === \"At\"\n ? timing.atMillis\n : yield* Effect.fromResult(scheduleNextAfter(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const changed = yield* store.change(\n key,\n {\n _tag: \"Update\",\n expectedRevision: options.expectedRevision,\n configuration: nextConfiguration,\n nextAtMillis,\n nowMillis,\n },\n limits.maxSchedulesPerOwner,\n );\n\n yield* wake.notify;\n\n return asSnapshot(changed, nowMillis);\n });\n\n const get = Effect.fn(\"Scheduling.get\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) {\n yield* authorizer.manage({ operation: \"get\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n return asSnapshot(record, yield* currentMillis);\n });\n\n const list = Effect.fn(\"Scheduling.list\")(function* (\n scope: ScheduleScope,\n options: ScheduleListOptions = {},\n ) {\n yield* authorizer.manage({ operation: \"list\", scope });\n const limit = options.limit ?? 50;\n\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n return yield* ScheduleValidationError.make({\n message: \"Schedule page limit must be an integer from 1 through 100\",\n });\n }\n\n const page = yield* store.list({\n owner: scope.owner,\n ...(options.after === undefined ? {} : { after: options.after }),\n limit,\n });\n\n const nowMillis = yield* currentMillis;\n\n return { items: page.items.map((record) => asSnapshot(record, nowMillis)), next: page.next };\n });\n\n const control = Effect.fn(\"Scheduling.control\")(function* (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ): Effect.fn.Return<ScheduleSnapshot, ScheduleManagementFailure> {\n yield* authorizer.manage({ operation, scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n\n const attempt = (): Effect.Effect<ScheduleRecord, ScheduleManagementFailure> =>\n Effect.suspend(() =>\n Effect.gen(function* () {\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n if (operation === \"resume\" && record.state === \"active\") return record;\n const nowMillis = yield* currentMillis;\n\n const nextAtMillis =\n operation === \"resume\"\n ? yield* Effect.fromResult(\n scheduleResumeCursor(\n record.configuration.timing,\n record.nextAtMillis,\n nowMillis,\n ),\n )\n : operation === \"cancel\"\n ? null\n : record.nextAtMillis;\n\n const skippedRange =\n operation === \"resume\" &&\n record.configuration.timing._tag !== \"At\" &&\n record.nextAtMillis !== null &&\n nextAtMillis !== null &&\n nextAtMillis > record.nextAtMillis\n ? { fromMillis: record.nextAtMillis, toMillis: nextAtMillis }\n : null;\n\n return yield* store\n .change(\n key,\n {\n _tag: \"Control\",\n expectedRevision,\n expectedVersion: record.version,\n action: operation,\n nextAtMillis,\n nowMillis,\n skippedRange,\n },\n limits.maxSchedulesPerOwner,\n )\n .pipe(\n Effect.catchTag(\"ScheduleConflict\", (error) =>\n error.reason === \"revision\" ? attempt() : Effect.fail(error),\n ),\n );\n }),\n );\n\n const changed = yield* attempt();\n\n yield* wake.notify;\n\n return asSnapshot(changed, yield* currentMillis);\n });\n\n const recover = Effect.fn(\"Scheduling.recover\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) {\n yield* authorizer.manage({ operation: \"recover\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision)\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n const time = yield* currentMillis;\n\n if (record.pending === null) return asSnapshot(record, time);\n\n const recovered = yield* store.change(key, {\n _tag: \"Recover\",\n expectedGeneration,\n expectedRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n nowMillis: time,\n });\n\n yield* wake.notify;\n\n return asSnapshot(recovered, time);\n });\n\n return Scheduling.of({\n recover,\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n });\n\nconst makeDriver = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const admission = yield* ScheduledInputAdmission;\n const failpoint = yield* ScheduleFailpoint;\n const crypto = yield* Crypto.Crypto;\n const admissionSemaphore = yield* Semaphore.make(limits.admissionConcurrency);\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const retry = Effect.fn(\"Scheduling.retry\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n reason: ScheduleRetryReason,\n nowMillis: number,\n ) {\n if (record.pending === null) return record;\n const current = record.pending.retry;\n\n const delay = Math.min(\n limits.retryBaseMillis * 2 ** Math.min(current.attempts, 52),\n limits.retryMaxMillis,\n );\n\n return yield* store.change(key, {\n _tag: \"Retry\",\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: {\n generation: current.generation,\n attempts: current.attempts + 1,\n automaticAttempts: current.automaticAttempts + 1,\n parked: current.automaticAttempts + 1 >= (limits.maxAutomaticAttempts ?? 8),\n nextAttemptAtMillis: Math.min(nowMillis + delay, 8_640_000_000_000_000),\n lastAttemptAtMillis: nowMillis,\n lastFailure: reason,\n },\n nowMillis,\n });\n });\n\n const verifyPending = Effect.fn(\"Scheduling.verifyPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n ) {\n const pending = record.pending;\n\n if (pending === null) return;\n const envelope = pending.envelope;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: envelope.owner,\n scheduleId: envelope.scheduleId,\n configurationRevision: envelope.configurationRevision,\n intendedAtMillis: envelope.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"process\")));\n\n const usesCurrentConfiguration =\n envelope.configurationRevision === record.configurationRevision;\n\n const expectedThreadId = usesCurrentConfiguration\n ? record.configuration.destination._tag === \"ExistingThread\"\n ? record.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${envelope.occurrenceId}`)\n : null;\n\n const expectedAdmissionKey = Schema.decodeSync(IdempotencyKey)(\n `schedule-occurrence:${envelope.occurrenceId}`,\n );\n\n const digest = yield* withCrypto(digestJson(envelope.input)).pipe(\n Effect.mapError(() => corrupt(\"process\")),\n );\n\n if (\n envelope.schemaVersion !== 1 ||\n envelope.owner.tenantId !== key.owner.tenantId ||\n envelope.owner.ownerId !== key.owner.ownerId ||\n envelope.scheduleId !== key.scheduleId ||\n envelope.configurationRevision > record.configurationRevision ||\n envelope.occurrenceId !== occurrenceId ||\n (usesCurrentConfiguration &&\n (envelope.deliveryPrincipal !== record.configuration.deliveryPrincipal ||\n envelope.agentId !== record.configuration.agentId ||\n !equivalentDefinitions(envelope.definitions, record.configuration.definitions) ||\n !equivalentInput(envelope.input, record.configuration.input) ||\n envelope.inputDigest !== record.configuration.inputDigest)) ||\n envelope.inputDigest !== digest ||\n (expectedThreadId !== null && envelope.threadId !== expectedThreadId) ||\n envelope.admissionKey !== expectedAdmissionKey\n ) {\n return yield* corrupt(\"process\");\n }\n });\n\n const deliverPending = Effect.fn(\"Scheduling.deliverPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n nowMillis: number,\n ) {\n if (\n record.pending === null ||\n record.pending.retry.parked === true ||\n record.pending.retry.nextAttemptAtMillis > nowMillis\n ) {\n return record;\n }\n yield* verifyPending(key, record);\n const envelope = record.pending.envelope;\n\n const outcome = yield* admissionSemaphore.withPermit(\n admitPreparedInput(admission.submit(envelope), limits.admissionTimeoutMillis).pipe(\n Effect.tap((outcome) =>\n outcome._tag === \"Receipt\" ? failpoint.hit(\"schedule:admission:after\") : Effect.void,\n ),\n ),\n );\n\n const completedAtMillis = yield* currentMillis;\n\n if (outcome._tag === \"Receipt\") {\n if (outcome.receipt.threadId !== envelope.threadId) {\n return yield* corrupt(\"admission\");\n }\n\n return yield* store\n .change(key, {\n _tag: \"Complete\",\n occurrenceId: envelope.occurrenceId,\n receipt: outcome.receipt,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n if (outcome._tag === \"Refused\") {\n const refusal: ScheduleRefusal = {\n atMillis: completedAtMillis,\n intendedAtMillis: envelope.intendedAtMillis,\n occurrenceId: envelope.occurrenceId,\n phase: \"admission\",\n code: outcome.error.code,\n };\n\n return yield* store\n .change(key, {\n _tag: \"Refuse\",\n occurrenceId: envelope.occurrenceId,\n refusal,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n\n return yield* retry(key, record, outcome.reason, completedAtMillis);\n });\n\n const processRecord = Effect.fn(\"Scheduling.processRecord\")(function* (\n key: ScheduleKey,\n initial: ScheduleRecord,\n nowMillis: number,\n ): Effect.fn.Return<ScheduleRecord, ScheduleProcessFailure> {\n if (initial.pending !== null) return yield* deliverPending(key, initial, nowMillis);\n if (\n initial.state !== \"active\" ||\n initial.nextAtMillis === null ||\n initial.nextAtMillis > nowMillis\n ) {\n return initial;\n }\n\n const currentInputDigest = yield* withCrypto(digestJson(initial.configuration.input)).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"prepare\", reason: \"unavailable\" }),\n ),\n );\n\n if (currentInputDigest !== initial.configuration.inputDigest) {\n return yield* corrupt(\"prepare\");\n }\n\n const due = yield* Effect.fromResult(\n scheduleDueOccurrence(initial.configuration.timing, initial.nextAtMillis, nowMillis),\n );\n\n if (due === null) return initial;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"prepare\")));\n\n const occurrence = {\n key,\n configurationRevision: initial.configurationRevision,\n configuration: initial.configuration,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n };\n\n const authorization = yield* authorizer.prepare(occurrence).pipe(Effect.result);\n\n if (Result.isFailure(authorization)) {\n if (authorization.failure._tag === \"ScheduleStorageError\") {\n return yield* authorization.failure;\n }\n\n return yield* store.change(key, {\n _tag: \"DenyPreparation\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n refusal: {\n atMillis: nowMillis,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n phase: \"preparation\",\n code: authorization.failure.code,\n },\n nowMillis,\n });\n }\n\n const threadId =\n initial.configuration.destination._tag === \"ExistingThread\"\n ? initial.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${occurrenceId}`);\n\n const admissionKey = Schema.decodeSync(IdempotencyKey)(`schedule-occurrence:${occurrenceId}`);\n\n const prepared = yield* store.change(key, {\n _tag: \"Prepare\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n envelope: {\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n preparedAtMillis: nowMillis,\n occurrenceId,\n threadId,\n deliveryPrincipal: initial.configuration.deliveryPrincipal,\n ...(initial.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: initial.configuration.admissionGroup }),\n ...(initial.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: initial.configuration.admissionFence }),\n agentId: initial.configuration.agentId,\n definitions: initial.configuration.definitions,\n input: initial.configuration.input,\n inputDigest: initial.configuration.inputDigest,\n admissionKey,\n authorization: authorization.success,\n },\n nextAtMillis: due.nextAtMillis,\n skippedRange: due.skippedRange,\n nowMillis,\n });\n\n return yield* deliverPending(key, prepared, nowMillis);\n });\n\n const process = Effect.fn(\"Scheduling.process\")(function* (key: ScheduleKey) {\n const nowMillis = yield* currentMillis;\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n const processed = yield* processRecord(key, record, nowMillis).pipe(\n Effect.catchTag(\"ScheduleConflict\", () =>\n store\n .get(key)\n .pipe(\n Effect.flatMap((current) =>\n current === null\n ? Effect.fail(notFound(key))\n : processRecord(key, current, nowMillis),\n ),\n ),\n ),\n );\n\n return processed;\n });\n\n const runDue = Effect.fn(\"ScheduleDriver.runDue\")(function* (owner?: ScheduleOwner) {\n const nowMillis = yield* currentMillis;\n let after: ScheduleDueCursor | undefined;\n let processed = 0;\n let failed = 0;\n\n while (true) {\n const due = yield* store.due(nowMillis, limits.dueBatchSize, owner, after);\n\n if (due.length === 0) break;\n yield* Effect.forEach(\n due,\n (key) =>\n process(key).pipe(\n Effect.matchCauseEffect({\n onSuccess: () =>\n Effect.sync(() => {\n processed += 1;\n }),\n onFailure: (cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.gen(function* () {\n failed += 1;\n yield* Effect.logWarning(\"Schedule processing failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n );\n }),\n }),\n ),\n { concurrency: limits.admissionConcurrency },\n );\n after = due.at(-1);\n if (due.length < limits.dueBatchSize) break;\n }\n\n return { processed, failed };\n });\n\n return ScheduleDriver.of({ process, runDue });\n });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst validateLimits = (limits: SchedulingLimits) =>\n Schema.decodeEffect(SchedulingLimits)(limits).pipe(\n Effect.mapError((error) =>\n ScheduleValidationError.make({ message: `Invalid Scheduling limits: ${error.message}` }),\n ),\n Effect.filterOrFail(\n (validated) => validated.retryBaseMillis <= validated.retryMaxMillis,\n () =>\n ScheduleValidationError.make({\n message: \"Scheduling retryBaseMillis must not exceed retryMaxMillis\",\n }),\n ),\n );\n\nexport class Scheduling extends Context.Service<\n Scheduling,\n {\n readonly create: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly update: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly get: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly list: (\n scope: ScheduleScope,\n options?: ScheduleListOptions,\n ) => Effect.Effect<ScheduleSnapshotPage, ScheduleManagementFailure>;\n readonly pause: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly resume: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly recover: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly cancel: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n }\n>()(\"@effect-agent/thread/Scheduling\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n Scheduling,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduleWake | Crypto.Crypto\n > {\n return Layer.effect(Scheduling, validateLimits(limits).pipe(Effect.flatMap(makeManagement)));\n }\n}\n\nexport const ScheduleWakeNoop: Layer.Layer<ScheduleWake> = Layer.succeed(ScheduleWake, {\n notify: Effect.void,\n await: Effect.never,\n});\n\n/** Privileged host capability. Never provide this service to management callers or model tools. */\nexport class ScheduleDriver extends Context.Service<\n ScheduleDriver,\n {\n readonly process: (key: ScheduleKey) => Effect.Effect<ScheduleRecord, ScheduleProcessFailure>;\n readonly runDue: (\n owner?: ScheduleOwner,\n ) => Effect.Effect<\n { readonly processed: number; readonly failed: number },\n ScheduleStorageError\n >;\n }\n>()(\"@effect-agent/thread/ScheduleDriver\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n ScheduleDriver,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduledInputAdmission | Crypto.Crypto\n > {\n return Layer.effect(ScheduleDriver, validateLimits(limits).pipe(Effect.flatMap(makeDriver)));\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,WAAW,YAAoB,OAAO,KAAK,wBAAwB,KAAK,EAAE,QAAQ,CAAC,CAAC;AAE1F,MAAM,kBAAkB,QAAgB,UACtC,OAAO,aAAa,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC,KAC3C,OAAO,eACL,wBAAwB,KAAK,EAC3B,SAAS,GAAG,MAAM,iDACpB,CAAC,CACH,CACF;AAEF,MAAM,UAAU,KAA0B,SACxC,IAAI,SAAS,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAAG,UAAU,KAAK,IAAI,CAAC,GAAG,GAAG;;;;;;AAO9E,MAAM,yBACJ,MACA,kBACiD;CACjD,IAAI,KAAK,QAAQ,SAAS,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,SAAS,SAClD,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,KAAK,WAAW,OAAO,KAAK,MAAM,CAC7D;CAEA,YAAY,MAAM,MAAM,UAAU,OAAO,KAAK;CAC9C,IAAI,aAAa;CAEjB,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,QAAQ,SAAS,GAAG;EAC1D,MAAM,UAAU,YAAY;EAC5B,MAAM,OAAO,aAAa,QAAQ,KAAK,YAAY;EAEnD,IAAI,Y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AC,KAAK,OAAO,QAAQ,UAAU,CAAC,CAAC;CAC7F;AACF"}
|
|
1
|
+
{"version":3,"file":"Scheduling-DPb2QyAK.mjs","names":["ScheduleTimingRequestSchema","ScheduleDestinationSchema"],"sources":["../src/durable/internal/schedule-time.ts","../src/durable/Scheduling.ts"],"sourcesContent":["import { Cron, DateTime, Option, Result, Schema } from \"effect\";\n\nimport {\n ScheduleValidationError,\n ScheduleInstant,\n type ScheduleSkippedRange,\n type ScheduleTiming,\n type ScheduleTimingRequest,\n} from \"../Schedule.ts\";\n\nconst invalid = (message: string) => Result.fail(ScheduleValidationError.make({ message }));\n\nconst checkedInstant = (millis: number, label: string) =>\n Schema.decodeResult(ScheduleInstant)(millis).pipe(\n Result.mapError(() =>\n ScheduleValidationError.make({\n message: `${label} is outside the supported ScheduleInstant range`,\n }),\n ),\n );\n\nconst values = (set: ReadonlySet<number>, size: number): ReadonlyArray<number> =>\n set.size === 0 ? Array.from({ length: size }, (_, index) => index) : [...set];\n\n/**\n * Cron frequency proof without calendar enumeration. It checks the minimum circular spacing of\n * the allowed hour/minute pairs. Day restrictions may make a rule sparser, so this deliberately\n * rejects some safe rules when a configured minimum exceeds one minute.\n */\nconst validateCronFrequency = (\n cron: Cron.Cron,\n minimumMillis: number,\n): Result.Result<void, ScheduleValidationError> => {\n if (cron.seconds.size !== 1) {\n return invalid(\"Cron must select exactly one seconds value\");\n }\n if (minimumMillis <= 60_000) return Result.succeed(undefined);\n if (\n Option.isSome(cron.tz) &&\n DateTime.isTimeZoneNamed(cron.tz.value) &&\n cron.tz.value.id !== \"UTC\"\n ) {\n return invalid(\"Cron minimums above one minute require UTC or a fixed-offset time zone\");\n }\n\n const minuteOfDay = values(cron.hours, 24).flatMap((hour) =>\n values(cron.minutes, 60).map((minute) => hour * 60 + minute),\n );\n\n minuteOfDay.sort((left, right) => left - right);\n let minimumGap = 24 * 60;\n\n for (let index = 0; index < minuteOfDay.length; index += 1) {\n const current = minuteOfDay[index];\n const next = minuteOfDay[(index + 1) % minuteOfDay.length];\n\n if (current === undefined || next === undefined) continue;\n const gap = next > current ? next - current : 24 * 60 - current + next;\n\n minimumGap = Math.min(minimumGap, gap);\n }\n\n return minimumGap * 60_000 >= minimumMillis\n ? Result.succeed(undefined)\n : invalid(`Cron may fire more often than the configured ${minimumMillis}ms minimum`);\n};\n\nexport const parseScheduleCron = (\n expression: string,\n timeZone: string,\n minimumMillis: number,\n): Result.Result<Cron.Cron, ScheduleValidationError> => {\n const parsed = Cron.parse(expression, timeZone);\n\n if (Result.isFailure(parsed)) return invalid(parsed.failure.message);\n const frequency = validateCronFrequency(parsed.success, minimumMillis);\n\n return Result.isFailure(frequency)\n ? Result.fail(frequency.failure)\n : Result.succeed(parsed.success);\n};\n\nexport const normalizeScheduleTiming = (\n request: ScheduleTimingRequest,\n nowMillis: number,\n minimumMillis: number,\n): Result.Result<ScheduleTiming, ScheduleValidationError> => {\n switch (request._tag) {\n case \"At\":\n return Result.succeed(request);\n case \"After\": {\n const at = checkedInstant(nowMillis + request.delayMillis, \"Relative deadline\");\n\n return Result.map(at, (atMillis) => ({ _tag: \"At\" as const, atMillis }));\n }\n case \"Interval\": {\n if (request.everyMillis < minimumMillis) {\n return invalid(`Interval must be at least ${minimumMillis}ms`);\n }\n\n const anchor = checkedInstant(\n request.anchorMillis ?? nowMillis + request.everyMillis,\n \"Interval anchor\",\n );\n\n return Result.map(anchor, (anchorMillis) => ({\n _tag: \"Interval\" as const,\n everyMillis: request.everyMillis,\n anchorMillis,\n }));\n }\n case \"Cron\": {\n const timeZone = request.timeZone ?? \"UTC\";\n const cron = parseScheduleCron(request.expression, timeZone, minimumMillis);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.succeed({ _tag: \"Cron\", expression: request.expression, timeZone });\n }\n }\n};\n\nconst parsedStoredCron = (timing: Extract<ScheduleTiming, { _tag: \"Cron\" }>) => {\n const parsed = Cron.parse(timing.expression, timing.timeZone);\n\n return Result.isFailure(parsed)\n ? invalid(`Stored cron is invalid: ${parsed.failure.message}`)\n : Result.succeed(parsed.success);\n};\n\n/** Strictly selects the first occurrence after an instant. */\nexport const scheduleNextAfter = (\n timing: ScheduleTiming,\n afterMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n switch (timing._tag) {\n case \"At\":\n return Result.succeed(timing.atMillis > afterMillis ? timing.atMillis : null);\n case \"Interval\": {\n if (afterMillis < timing.anchorMillis) return Result.succeed(timing.anchorMillis);\n const steps = Math.floor((afterMillis - timing.anchorMillis) / timing.everyMillis) + 1;\n const next = timing.anchorMillis + steps * timing.everyMillis;\n\n return checkedInstant(next, \"Next interval occurrence\");\n }\n case \"Cron\": {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n return Result.try({\n try: () => {\n let next = Cron.next(cron.success, afterMillis).getTime();\n\n // Inside a fall fold Effect may select the first, already elapsed local instant.\n while (next <= afterMillis) {\n const following = Cron.next(cron.success, next).getTime();\n\n if (following <= next) throw new Error(\"Cron did not advance\");\n next = following;\n }\n\n return next;\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported next firing\" }),\n }).pipe(Result.flatMap((next) => checkedInstant(next, \"Next cron occurrence\")));\n }\n }\n};\n\n/** Initial cursor. Past one-shots remain due; recurring rules start strictly after registration. */\nexport const scheduleInitialCursor = (\n timing: ScheduleTiming,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> =>\n timing._tag === \"At\" ? Result.succeed(timing.atMillis) : scheduleNextAfter(timing, nowMillis);\n\nexport interface DueScheduleOccurrence {\n readonly intendedAtMillis: number;\n readonly nextAtMillis: number | null;\n readonly skippedRange: ScheduleSkippedRange | null;\n}\n\n/** Coalesces recurring occurrences using the same forward sequence as registration. */\nexport const scheduleDueOccurrence = (\n timing: ScheduleTiming,\n cursorMillis: number,\n nowMillis: number,\n): Result.Result<DueScheduleOccurrence | null, ScheduleValidationError> => {\n if (cursorMillis > nowMillis) return Result.succeed(null);\n if (timing._tag === \"At\") {\n return Result.succeed({\n intendedAtMillis: cursorMillis,\n nextAtMillis: null,\n skippedRange: null,\n });\n }\n\n let intendedAtMillis: number;\n\n if (timing._tag === \"Interval\") {\n const steps = Math.floor((nowMillis - timing.anchorMillis) / timing.everyMillis);\n\n intendedAtMillis = Math.max(cursorMillis, timing.anchorMillis + steps * timing.everyMillis);\n } else {\n const cron = parsedStoredCron(timing);\n\n if (Result.isFailure(cron)) return Result.fail(cron.failure);\n\n const due = Result.try({\n try: () => {\n let intended = cursorMillis;\n // Reverse traversal is safe only without offset transitions. Named-zone reverse\n // traversal has different gap/fold semantics from the forward occurrence sequence.\n const zone = Option.getOrUndefined(cron.success.tz);\n\n if (zone !== undefined && (DateTime.isTimeZoneOffset(zone) || zone.id === \"UTC\")) {\n intended = Math.max(cursorMillis, Cron.prev(cron.success, nowMillis + 1_000).getTime());\n } else {\n // Seek by calendar date in UTC, where reverse traversal has no DST ambiguity.\n // Include two prior civil days to cover even IANA date-line shifts. There are no\n // matching dates between this seed day and that boundary, so forward traversal\n // visits only the seed day and the recent days, regardless of downtime length.\n const calendar = Cron.make({\n ...cron.success,\n seconds: [0],\n minutes: [0],\n hours: [0],\n tz: DateTime.zoneMakeNamedUnsafe(\"UTC\"),\n });\n\n const localDay = DateTime.makeUnsafe(\n DateTime.toDate(DateTime.makeZonedUnsafe(nowMillis, { timeZone: zone })),\n ).pipe(DateTime.startOf(\"day\"), DateTime.subtract({ days: 2 }));\n\n const seedDay = Cron.prev(calendar, DateTime.toEpochMillis(localDay) + 1_000);\n\n const seed =\n DateTime.makeZonedUnsafe(seedDay, {\n timeZone: zone,\n adjustForTimeZone: true,\n }).pipe(DateTime.toEpochMillis) - 1_000;\n\n if (seed > cursorMillis) {\n const first = Cron.next(cron.success, seed).getTime();\n\n if (first <= nowMillis) intended = Math.max(intended, first);\n }\n }\n let next = Cron.next(cron.success, intended).getTime();\n\n while (next <= nowMillis) {\n if (next <= intended) throw new Error(\"Cron did not advance\");\n intended = next;\n next = Cron.next(cron.success, intended).getTime();\n }\n\n return { intended, next };\n },\n catch: () => ScheduleValidationError.make({ message: \"Cron has no supported due firing\" }),\n });\n\n if (Result.isFailure(due)) return Result.fail(due.failure);\n const next = checkedInstant(due.success.next, \"Next cron occurrence\");\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis: due.success.intended,\n nextAtMillis: next.success,\n skippedRange:\n due.success.intended === cursorMillis\n ? null\n : {\n fromMillis: cursorMillis,\n toMillis: due.success.intended,\n },\n });\n }\n\n const next = scheduleNextAfter(timing, nowMillis);\n\n if (Result.isFailure(next)) return Result.fail(next.failure);\n\n return Result.succeed({\n intendedAtMillis,\n nextAtMillis: next.success,\n skippedRange:\n intendedAtMillis === cursorMillis\n ? null\n : { fromMillis: cursorMillis, toMillis: intendedAtMillis },\n });\n};\n\nexport const scheduleResumeCursor = (\n timing: ScheduleTiming,\n existingCursor: number | null,\n nowMillis: number,\n): Result.Result<number | null, ScheduleValidationError> => {\n if (timing._tag === \"At\") return Result.succeed(existingCursor);\n\n return scheduleNextAfter(timing, nowMillis);\n};\n","import {\n Cause,\n Context,\n Crypto,\n DateTime,\n Effect,\n Layer,\n Option,\n Result,\n Schema,\n Semaphore,\n} from \"effect\";\n\nimport { type AgentId, ThreadId } from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { digestJson } from \"./Digest.ts\";\nimport type { DurableSubmitAgent } from \"./DurableAgentRuntime.ts\";\nimport {\n normalizeScheduleTiming,\n scheduleDueOccurrence,\n scheduleInitialCursor,\n scheduleNextAfter,\n scheduleResumeCursor,\n} from \"./internal/schedule-time.ts\";\nimport { admitPreparedInput } from \"./PreparedInputAdmission.ts\";\nimport { DefinitionDigests, type Digest, PersistedJson } from \"./Records.ts\";\nimport {\n defaultSchedulingLimits,\n type ScheduleAuthorizationError,\n ScheduleAuthorizer,\n ScheduleConflict,\n type ScheduleConfiguration,\n ScheduleDestination as ScheduleDestinationSchema,\n type ScheduleDestination,\n ScheduleFailpoint,\n type ScheduleId,\n type ScheduleDueCursor,\n ScheduleInstant,\n type ScheduleKey,\n SchedulingLimits,\n ScheduleNotFound,\n type ScheduleOwner,\n type ScheduleRecord,\n type ScheduleRefusal,\n type ScheduleRetryReason,\n type ScheduleScope,\n type ScheduleSnapshot,\n type ScheduleSnapshotPage,\n ScheduleStorageError,\n ScheduleStore,\n type ScheduleStoreFailure,\n ScheduleTimingRequest as ScheduleTimingRequestSchema,\n type ScheduleTimingRequest,\n ScheduleValidationError,\n ScheduledInputAdmission,\n ScheduleWake,\n} from \"./Schedule.ts\";\nimport { type AdmissionFence, IdempotencyKey, type Principal } from \"./SubmissionLedger.ts\";\n\nexport interface ScheduleCreateOptions {\n readonly scope: ScheduleScope;\n readonly scheduleId: ScheduleId;\n readonly timing: ScheduleTimingRequest;\n readonly destination: ScheduleDestination;\n readonly deliveryPrincipal: Principal;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionFence;\n readonly definitions: DefinitionDigests;\n}\n\nexport interface ScheduleUpdateOptions extends ScheduleCreateOptions {\n readonly expectedRevision: number;\n}\n\nexport interface ScheduleListOptions {\n readonly after?: ScheduleId | undefined;\n readonly limit?: number | undefined;\n}\n\nexport type ScheduleManagementFailure =\n | ScheduleValidationError\n | ScheduleAuthorizationError\n | ScheduleStoreFailure;\n\nexport type ScheduleProcessFailure =\n | ScheduleValidationError\n | ScheduleStoreFailure\n | ScheduleStorageError;\n\nconst equivalentDefinitions = Schema.toEquivalence(DefinitionDigests);\nconst equivalentInput = Schema.toEquivalence(PersistedJson);\n\nconst keyOf = (scope: ScheduleScope, scheduleId: ScheduleId): ScheduleKey => ({\n owner: scope.owner,\n scheduleId,\n});\n\nconst notFound = (key: ScheduleKey) => ScheduleNotFound.make({ key });\n\nconst asSnapshot = (record: ScheduleRecord, observedAtMillis: number): ScheduleSnapshot => {\n const intendedAtMillis = record.pending?.envelope.intendedAtMillis ?? record.nextAtMillis;\n\n return {\n owner: record.owner,\n scheduleId: record.scheduleId,\n createdAtMillis: record.createdAtMillis,\n updatedAtMillis: record.updatedAtMillis,\n configurationRevision: record.configurationRevision,\n configuration: {\n timing: record.configuration.timing,\n destination: record.configuration.destination,\n deliveryPrincipal: record.configuration.deliveryPrincipal,\n ...(record.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: record.configuration.admissionGroup }),\n ...(record.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: record.configuration.admissionFence }),\n agentId: record.configuration.agentId,\n },\n state: record.state,\n nextAtMillis: record.nextAtMillis,\n pending:\n record.pending === null\n ? null\n : {\n intendedAtMillis: record.pending.envelope.intendedAtMillis,\n preparedAtMillis: record.pending.envelope.preparedAtMillis,\n configurationRevision: record.pending.envelope.configurationRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: record.pending.retry,\n },\n lastReceipt: record.lastReceipt,\n lastRefusal: record.lastRefusal,\n lastSkippedRange: record.lastSkippedRange,\n observedAtMillis,\n pendingAgeMillis:\n record.pending === null\n ? null\n : Math.max(0, observedAtMillis - record.pending.envelope.preparedAtMillis),\n latenessMillis:\n intendedAtMillis === null ? 0 : Math.max(0, observedAtMillis - intendedAtMillis),\n };\n};\n\nconst inputByteLength = (input: PersistedJson): number => utf8ByteLength(JSON.stringify(input));\n\nconst currentMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));\n\nconst validateRequestedFields = Effect.fn(\"Scheduling.validateRequestedFields\")(function* (\n options: ScheduleCreateOptions,\n) {\n yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n yield* Schema.encodeEffect(ScheduleDestinationSchema)(options.destination).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid definition digests\" })),\n );\n});\n\nconst resolveInput = Effect.fn(\"Scheduling.resolveInput\")(function* <\n InputSchema extends Schema.Top,\n>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n maximumBytes: number,\n): Effect.fn.Return<\n { readonly payload: PersistedJson; readonly digest: Digest },\n ScheduleValidationError,\n InputSchema[\"EncodingServices\"] | Crypto.Crypto\n> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to encode Agent input\" }),\n ),\n );\n\n const payload = yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n\n if (inputByteLength(payload) > maximumBytes) {\n return yield* ScheduleValidationError.make({\n message: `Encoded Agent input exceeds the configured ${maximumBytes} byte limit`,\n });\n }\n\n const digest = yield* digestJson(payload).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest encoded Agent input\" }),\n ),\n );\n\n return { payload, digest };\n});\n\nconst makeManagement = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const nowMillis = yield* currentMillis;\n\n yield* Schema.decodeEffect(ScheduleInstant)(nowMillis + limits.recoveryPollMillis).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Scheduling recovery deadline exceeds the supported instant range\",\n }),\n ),\n );\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const wake = yield* ScheduleWake;\n const crypto = yield* Crypto.Crypto;\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const fingerprint = Effect.fn(\"Scheduling.fingerprint\")(function* (\n agentId: AgentId,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n ) {\n const timing = yield* Schema.encodeEffect(ScheduleTimingRequestSchema)(options.timing).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid timing request\" })),\n );\n\n const destination = yield* Schema.encodeEffect(ScheduleDestinationSchema)(\n options.destination,\n ).pipe(\n Effect.mapError(() => ScheduleValidationError.make({ message: \"Invalid destination\" })),\n );\n\n const definitions = yield* Schema.encodeEffect(DefinitionDigests)(options.definitions).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Invalid definition digests\" }),\n ),\n );\n\n return yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n registeringPrincipal: options.scope.principal,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined\n ? {}\n : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined\n ? {}\n : { admissionFence: options.admissionFence }),\n agentId,\n definitions,\n destination,\n timing,\n inputDigest,\n }),\n ).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({ message: \"Unable to digest Schedule registration\" }),\n ),\n );\n });\n\n const configuration = (\n agentId: AgentId,\n payload: PersistedJson,\n inputDigest: Digest,\n options: ScheduleCreateOptions,\n timing: ScheduleConfiguration[\"timing\"],\n ): ScheduleConfiguration => ({\n timing,\n destination: options.destination,\n deliveryPrincipal: options.deliveryPrincipal,\n ...(options.admissionGroup === undefined ? {} : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined ? {} : { admissionFence: options.admissionFence }),\n agentId,\n definitions: options.definitions,\n input: payload,\n inputDigest,\n });\n\n const create = Effect.fn(\"Scheduling.create\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const creationFingerprint = yield* fingerprint(\n agent.definition.id,\n resolvedInput.digest,\n options,\n );\n\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n const existing = yield* store.get(key);\n\n if (existing !== null) {\n if (existing.creationFingerprint !== creationFingerprint) {\n return yield* ScheduleConflict.make({ reason: \"creation\", key });\n }\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: existing.configuration,\n });\n\n return asSnapshot(existing, nowMillis);\n }\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(options.timing, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis = yield* Effect.fromResult(scheduleInitialCursor(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"create\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const record: ScheduleRecord = {\n schemaVersion: 1,\n owner: options.scope.owner,\n scheduleId: options.scheduleId,\n creationFingerprint,\n createdBy: options.scope.principal,\n createdAtMillis: nowMillis,\n updatedAtMillis: nowMillis,\n configurationRevision: 1,\n version: 1,\n configuration: nextConfiguration,\n state: \"active\",\n nextAtMillis,\n pending: null,\n lastReceipt: null,\n lastRefusal: null,\n lastSkippedRange: null,\n };\n\n const inserted = yield* store.insert(record, limits.maxSchedulesPerOwner);\n\n yield* wake.notify;\n\n return asSnapshot(inserted, nowMillis);\n });\n\n const update = Effect.fn(\"Scheduling.update\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ): Effect.fn.Return<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n > {\n const nowMillis = yield* currentMillis;\n const key = keyOf(options.scope, options.scheduleId);\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n });\n yield* validateRequestedFields(options);\n const existing = yield* store.get(key);\n\n if (existing === null) return yield* notFound(key);\n if (existing.configurationRevision !== options.expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n\n const resolvedInput = yield* resolveInput(agent, input, limits.maxInputBytes).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const timingRequest =\n options.timing._tag === \"Interval\" &&\n options.timing.anchorMillis === undefined &&\n existing.configuration.timing._tag === \"Interval\" &&\n existing.configuration.timing.everyMillis === options.timing.everyMillis\n ? { ...options.timing, anchorMillis: existing.configuration.timing.anchorMillis }\n : options.timing;\n\n const timing = yield* Effect.fromResult(\n normalizeScheduleTiming(timingRequest, nowMillis, limits.minIntervalMillis),\n );\n\n const nextAtMillis =\n timing._tag === \"At\"\n ? timing.atMillis\n : yield* Effect.fromResult(scheduleNextAfter(timing, nowMillis));\n\n if (nextAtMillis === null) {\n return yield* ScheduleValidationError.make({ message: \"Timing has no next occurrence\" });\n }\n\n const nextConfiguration = configuration(\n agent.definition.id,\n resolvedInput.payload,\n resolvedInput.digest,\n options,\n timing,\n );\n\n yield* authorizer.manage({\n operation: \"update\",\n scope: options.scope,\n scheduleId: options.scheduleId,\n configuration: nextConfiguration,\n });\n\n const changed = yield* store.change(\n key,\n {\n _tag: \"Update\",\n expectedRevision: options.expectedRevision,\n configuration: nextConfiguration,\n nextAtMillis,\n nowMillis,\n },\n limits.maxSchedulesPerOwner,\n );\n\n yield* wake.notify;\n\n return asSnapshot(changed, nowMillis);\n });\n\n const get = Effect.fn(\"Scheduling.get\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) {\n yield* authorizer.manage({ operation: \"get\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n return asSnapshot(record, yield* currentMillis);\n });\n\n const list = Effect.fn(\"Scheduling.list\")(function* (\n scope: ScheduleScope,\n options: ScheduleListOptions = {},\n ) {\n yield* authorizer.manage({ operation: \"list\", scope });\n const limit = options.limit ?? 50;\n\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n return yield* ScheduleValidationError.make({\n message: \"Schedule page limit must be an integer from 1 through 100\",\n });\n }\n\n const page = yield* store.list({\n owner: scope.owner,\n ...(options.after === undefined ? {} : { after: options.after }),\n limit,\n });\n\n const nowMillis = yield* currentMillis;\n\n return { items: page.items.map((record) => asSnapshot(record, nowMillis)), next: page.next };\n });\n\n const control = Effect.fn(\"Scheduling.control\")(function* (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ): Effect.fn.Return<ScheduleSnapshot, ScheduleManagementFailure> {\n yield* authorizer.manage({ operation, scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n\n const attempt = (): Effect.Effect<ScheduleRecord, ScheduleManagementFailure> =>\n Effect.suspend(() =>\n Effect.gen(function* () {\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision) {\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n }\n if (operation === \"resume\" && record.state === \"active\") return record;\n const nowMillis = yield* currentMillis;\n\n const nextAtMillis =\n operation === \"resume\"\n ? yield* Effect.fromResult(\n scheduleResumeCursor(\n record.configuration.timing,\n record.nextAtMillis,\n nowMillis,\n ),\n )\n : operation === \"cancel\"\n ? null\n : record.nextAtMillis;\n\n const skippedRange =\n operation === \"resume\" &&\n record.configuration.timing._tag !== \"At\" &&\n record.nextAtMillis !== null &&\n nextAtMillis !== null &&\n nextAtMillis > record.nextAtMillis\n ? { fromMillis: record.nextAtMillis, toMillis: nextAtMillis }\n : null;\n\n return yield* store\n .change(\n key,\n {\n _tag: \"Control\",\n expectedRevision,\n expectedVersion: record.version,\n action: operation,\n nextAtMillis,\n nowMillis,\n skippedRange,\n },\n limits.maxSchedulesPerOwner,\n )\n .pipe(\n Effect.catchTag(\"ScheduleConflict\", (error) =>\n error.reason === \"revision\" ? attempt() : Effect.fail(error),\n ),\n );\n }),\n );\n\n const changed = yield* attempt();\n\n yield* wake.notify;\n\n return asSnapshot(changed, yield* currentMillis);\n });\n\n const recover = Effect.fn(\"Scheduling.recover\")(function* (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) {\n yield* authorizer.manage({ operation: \"recover\", scope, scheduleId });\n const key = keyOf(scope, scheduleId);\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n if (record.configurationRevision !== expectedRevision)\n return yield* ScheduleConflict.make({ reason: \"revision\", key });\n const time = yield* currentMillis;\n\n if (record.pending === null) return asSnapshot(record, time);\n\n const recovered = yield* store.change(key, {\n _tag: \"Recover\",\n expectedGeneration,\n expectedRevision,\n occurrenceId: record.pending.envelope.occurrenceId,\n nowMillis: time,\n });\n\n yield* wake.notify;\n\n return asSnapshot(recovered, time);\n });\n\n return Scheduling.of({\n recover,\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n });\n\nconst makeDriver = (limits: SchedulingLimits) =>\n Effect.gen(function* () {\n const store = yield* ScheduleStore;\n const authorizer = yield* ScheduleAuthorizer;\n const admission = yield* ScheduledInputAdmission;\n const failpoint = yield* ScheduleFailpoint;\n const crypto = yield* Crypto.Crypto;\n const admissionSemaphore = yield* Semaphore.make(limits.admissionConcurrency);\n\n const withCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n\n const retry = Effect.fn(\"Scheduling.retry\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n reason: ScheduleRetryReason,\n nowMillis: number,\n ) {\n if (record.pending === null) return record;\n const current = record.pending.retry;\n\n const delay = Math.min(\n limits.retryBaseMillis * 2 ** Math.min(current.attempts, 52),\n limits.retryMaxMillis,\n );\n\n return yield* store.change(key, {\n _tag: \"Retry\",\n occurrenceId: record.pending.envelope.occurrenceId,\n retry: {\n generation: current.generation,\n attempts: current.attempts + 1,\n automaticAttempts: current.automaticAttempts + 1,\n parked: current.automaticAttempts + 1 >= (limits.maxAutomaticAttempts ?? 8),\n nextAttemptAtMillis: Math.min(nowMillis + delay, 8_640_000_000_000_000),\n lastAttemptAtMillis: nowMillis,\n lastFailure: reason,\n },\n nowMillis,\n });\n });\n\n const verifyPending = Effect.fn(\"Scheduling.verifyPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n ) {\n const pending = record.pending;\n\n if (pending === null) return;\n const envelope = pending.envelope;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: envelope.owner,\n scheduleId: envelope.scheduleId,\n configurationRevision: envelope.configurationRevision,\n intendedAtMillis: envelope.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"process\")));\n\n const usesCurrentConfiguration =\n envelope.configurationRevision === record.configurationRevision;\n\n const expectedThreadId = usesCurrentConfiguration\n ? record.configuration.destination._tag === \"ExistingThread\"\n ? record.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${envelope.occurrenceId}`)\n : null;\n\n const expectedAdmissionKey = Schema.decodeSync(IdempotencyKey)(\n `schedule-occurrence:${envelope.occurrenceId}`,\n );\n\n const digest = yield* withCrypto(digestJson(envelope.input)).pipe(\n Effect.mapError(() => corrupt(\"process\")),\n );\n\n if (\n envelope.schemaVersion !== 1 ||\n envelope.owner.tenantId !== key.owner.tenantId ||\n envelope.owner.ownerId !== key.owner.ownerId ||\n envelope.scheduleId !== key.scheduleId ||\n envelope.configurationRevision > record.configurationRevision ||\n envelope.occurrenceId !== occurrenceId ||\n (usesCurrentConfiguration &&\n (envelope.deliveryPrincipal !== record.configuration.deliveryPrincipal ||\n envelope.agentId !== record.configuration.agentId ||\n !equivalentDefinitions(envelope.definitions, record.configuration.definitions) ||\n !equivalentInput(envelope.input, record.configuration.input) ||\n envelope.inputDigest !== record.configuration.inputDigest)) ||\n envelope.inputDigest !== digest ||\n (expectedThreadId !== null && envelope.threadId !== expectedThreadId) ||\n envelope.admissionKey !== expectedAdmissionKey\n ) {\n return yield* corrupt(\"process\");\n }\n });\n\n const deliverPending = Effect.fn(\"Scheduling.deliverPending\")(function* (\n key: ScheduleKey,\n record: ScheduleRecord,\n nowMillis: number,\n ) {\n if (\n record.pending === null ||\n record.pending.retry.parked === true ||\n record.pending.retry.nextAttemptAtMillis > nowMillis\n ) {\n return record;\n }\n yield* verifyPending(key, record);\n const envelope = record.pending.envelope;\n\n const outcome = yield* admissionSemaphore.withPermit(\n admitPreparedInput(admission.submit(envelope), limits.admissionTimeoutMillis).pipe(\n Effect.tap((outcome) =>\n outcome._tag === \"Receipt\" ? failpoint.hit(\"schedule:admission:after\") : Effect.void,\n ),\n ),\n );\n\n const completedAtMillis = yield* currentMillis;\n\n if (outcome._tag === \"Receipt\") {\n if (outcome.receipt.threadId !== envelope.threadId) {\n return yield* corrupt(\"admission\");\n }\n\n return yield* store\n .change(key, {\n _tag: \"Complete\",\n occurrenceId: envelope.occurrenceId,\n receipt: outcome.receipt,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n if (outcome._tag === \"Refused\") {\n const refusal: ScheduleRefusal = {\n atMillis: completedAtMillis,\n intendedAtMillis: envelope.intendedAtMillis,\n occurrenceId: envelope.occurrenceId,\n phase: \"admission\",\n code: outcome.error.code,\n };\n\n return yield* store\n .change(key, {\n _tag: \"Refuse\",\n occurrenceId: envelope.occurrenceId,\n refusal,\n nowMillis: completedAtMillis,\n })\n .pipe(\n Effect.catchTag(\"ScheduleStorageError\", (error) =>\n error.reason === \"unavailable\"\n ? retry(key, record, \"storage\", completedAtMillis)\n : Effect.fail(error),\n ),\n );\n }\n\n return yield* retry(key, record, outcome.reason, completedAtMillis);\n });\n\n const processRecord = Effect.fn(\"Scheduling.processRecord\")(function* (\n key: ScheduleKey,\n initial: ScheduleRecord,\n nowMillis: number,\n ): Effect.fn.Return<ScheduleRecord, ScheduleProcessFailure> {\n if (initial.pending !== null) return yield* deliverPending(key, initial, nowMillis);\n if (\n initial.state !== \"active\" ||\n initial.nextAtMillis === null ||\n initial.nextAtMillis > nowMillis\n ) {\n return initial;\n }\n\n const currentInputDigest = yield* withCrypto(digestJson(initial.configuration.input)).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"prepare\", reason: \"unavailable\" }),\n ),\n );\n\n if (currentInputDigest !== initial.configuration.inputDigest) {\n return yield* corrupt(\"prepare\");\n }\n\n const due = yield* Effect.fromResult(\n scheduleDueOccurrence(initial.configuration.timing, initial.nextAtMillis, nowMillis),\n );\n\n if (due === null) return initial;\n\n const occurrenceId = yield* withCrypto(\n digestJson({\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n }),\n ).pipe(Effect.mapError(() => corrupt(\"prepare\")));\n\n const occurrence = {\n key,\n configurationRevision: initial.configurationRevision,\n configuration: initial.configuration,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n };\n\n const authorization = yield* authorizer.prepare(occurrence).pipe(Effect.result);\n\n if (Result.isFailure(authorization)) {\n if (authorization.failure._tag === \"ScheduleStorageError\") {\n return yield* authorization.failure;\n }\n\n return yield* store.change(key, {\n _tag: \"DenyPreparation\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n refusal: {\n atMillis: nowMillis,\n intendedAtMillis: due.intendedAtMillis,\n occurrenceId,\n phase: \"preparation\",\n code: authorization.failure.code,\n },\n nowMillis,\n });\n }\n\n const threadId =\n initial.configuration.destination._tag === \"ExistingThread\"\n ? initial.configuration.destination.threadId\n : Schema.decodeSync(ThreadId)(`schedule-thread:${occurrenceId}`);\n\n const admissionKey = Schema.decodeSync(IdempotencyKey)(`schedule-occurrence:${occurrenceId}`);\n\n const prepared = yield* store.change(key, {\n _tag: \"Prepare\",\n expectedRevision: initial.configurationRevision,\n expectedCursor: initial.nextAtMillis,\n envelope: {\n schemaVersion: 1,\n owner: initial.owner,\n scheduleId: initial.scheduleId,\n configurationRevision: initial.configurationRevision,\n intendedAtMillis: due.intendedAtMillis,\n preparedAtMillis: nowMillis,\n occurrenceId,\n threadId,\n deliveryPrincipal: initial.configuration.deliveryPrincipal,\n ...(initial.configuration.admissionGroup === undefined\n ? {}\n : { admissionGroup: initial.configuration.admissionGroup }),\n ...(initial.configuration.admissionFence === undefined\n ? {}\n : { admissionFence: initial.configuration.admissionFence }),\n agentId: initial.configuration.agentId,\n definitions: initial.configuration.definitions,\n input: initial.configuration.input,\n inputDigest: initial.configuration.inputDigest,\n admissionKey,\n authorization: authorization.success,\n },\n nextAtMillis: due.nextAtMillis,\n skippedRange: due.skippedRange,\n nowMillis,\n });\n\n return yield* deliverPending(key, prepared, nowMillis);\n });\n\n const process = Effect.fn(\"Scheduling.process\")(function* (key: ScheduleKey) {\n const nowMillis = yield* currentMillis;\n const record = yield* store.get(key);\n\n if (record === null) return yield* notFound(key);\n\n const processed = yield* processRecord(key, record, nowMillis).pipe(\n Effect.catchTag(\"ScheduleConflict\", () =>\n store\n .get(key)\n .pipe(\n Effect.flatMap((current) =>\n current === null\n ? Effect.fail(notFound(key))\n : processRecord(key, current, nowMillis),\n ),\n ),\n ),\n );\n\n return processed;\n });\n\n const runDue = Effect.fn(\"ScheduleDriver.runDue\")(function* (owner?: ScheduleOwner) {\n const nowMillis = yield* currentMillis;\n let after: ScheduleDueCursor | undefined;\n let processed = 0;\n let failed = 0;\n\n while (true) {\n const due = yield* store.due(nowMillis, limits.dueBatchSize, owner, after);\n\n if (due.length === 0) break;\n yield* Effect.forEach(\n due,\n (key) =>\n process(key).pipe(\n Effect.matchCauseEffect({\n onSuccess: () =>\n Effect.sync(() => {\n processed += 1;\n }),\n onFailure: (cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.gen(function* () {\n failed += 1;\n yield* Effect.logWarning(\"Schedule processing failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n );\n }),\n }),\n ),\n { concurrency: limits.admissionConcurrency },\n );\n after = due.at(-1);\n if (due.length < limits.dueBatchSize) break;\n }\n\n return { processed, failed };\n });\n\n return ScheduleDriver.of({ process, runDue });\n });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst validateLimits = (limits: SchedulingLimits) =>\n Schema.decodeEffect(SchedulingLimits)(limits).pipe(\n Effect.mapError((error) =>\n ScheduleValidationError.make({ message: `Invalid Scheduling limits: ${error.message}` }),\n ),\n Effect.filterOrFail(\n (validated) => validated.retryBaseMillis <= validated.retryMaxMillis,\n () =>\n ScheduleValidationError.make({\n message: \"Scheduling retryBaseMillis must not exceed retryMaxMillis\",\n }),\n ),\n );\n\nexport class Scheduling extends Context.Service<\n Scheduling,\n {\n readonly create: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleCreateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly update: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: ScheduleUpdateOptions,\n ) => Effect.Effect<\n ScheduleSnapshot,\n ScheduleManagementFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly get: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly list: (\n scope: ScheduleScope,\n options?: ScheduleListOptions,\n ) => Effect.Effect<ScheduleSnapshotPage, ScheduleManagementFailure>;\n readonly pause: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly resume: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly recover: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n expectedGeneration: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n readonly cancel: (\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) => Effect.Effect<ScheduleSnapshot, ScheduleManagementFailure>;\n }\n>()(\"@effect-agent/thread/Scheduling\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n Scheduling,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduleWake | Crypto.Crypto\n > {\n return Layer.effect(Scheduling, validateLimits(limits).pipe(Effect.flatMap(makeManagement)));\n }\n}\n\nexport const ScheduleWakeNoop: Layer.Layer<ScheduleWake> = Layer.succeed(ScheduleWake, {\n notify: Effect.void,\n await: Effect.never,\n});\n\n/** Privileged host capability. Never provide this service to management callers or model tools. */\nexport class ScheduleDriver extends Context.Service<\n ScheduleDriver,\n {\n readonly process: (key: ScheduleKey) => Effect.Effect<ScheduleRecord, ScheduleProcessFailure>;\n readonly runDue: (\n owner?: ScheduleOwner,\n ) => Effect.Effect<\n { readonly processed: number; readonly failed: number },\n ScheduleStorageError\n >;\n }\n>()(\"@effect-agent/thread/ScheduleDriver\") {\n static layer(\n limits: SchedulingLimits = defaultSchedulingLimits,\n ): Layer.Layer<\n ScheduleDriver,\n ScheduleValidationError,\n ScheduleStore | ScheduleAuthorizer | ScheduledInputAdmission | Crypto.Crypto\n > {\n return Layer.effect(ScheduleDriver, validateLimits(limits).pipe(Effect.flatMap(makeDriver)));\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,WAAW,YAAoB,OAAO,KAAK,wBAAwB,KAAK,EAAE,QAAQ,CAAC,CAAC;AAE1F,MAAM,kBAAkB,QAAgB,UACtC,OAAO,aAAa,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC,KAC3C,OAAO,eACL,wBAAwB,KAAK,EAC3B,SAAS,GAAG,MAAM,iDACpB,CAAC,CACH,CACF;AAEF,MAAM,UAAU,KAA0B,SACxC,IAAI,SAAS,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAAG,UAAU,KAAK,IAAI,CAAC,GAAG,GAAG;;;;;;AAO9E,MAAM,yBACJ,MACA,kBACiD;CACjD,IAAI,KAAK,QAAQ,SAAS,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,SAAS,SAClD,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,KAAK,WAAW,OAAO,KAAK,MAAM,CAC7D;CAEA,YAAY,MAAM,MAAM,UAAU,OAAO,KAAK;CAC9C,IAAI,aAAa;CAEjB,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,QAAQ,SAAS,GAAG;EAC1D,MAAM,UAAU,YAAY;EAC5B,MAAM,OAAO,aAAa,QAAQ,KAAK,YAAY;EAEnD,IA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C,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC,CAAC;CAC7F;AACF"}
|
|
@@ -4,11 +4,12 @@ import { SubagentBudgetExhausted, SubagentReservations } from "./capabilities/Su
|
|
|
4
4
|
import { a as Receipt, n as JoinedToHost, t as IdempotencyKey } from "./Receipt-BAHyigAF.mjs";
|
|
5
5
|
import { s as RunTotals } from "./Usage-Dx0aknfk.mjs";
|
|
6
6
|
import { t as ThreadHistory } from "./ThreadHistory-tS1KwxHR.mjs";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
7
|
+
import { a as FailureDiagnostic_d_exports, r as Diagnostic } from "./FailureDiagnostic-CaAkzGHL.mjs";
|
|
8
|
+
import { T as RunDispositionDeclaration, _ as InstructionSource, c as Definition, m as InputPromptSource, r as AnyDefinition } from "./Agent-Bk-mLtov.mjs";
|
|
9
|
+
import { a as WorkerError, c as WorkerRef, l as WorkerReport, n as WorkerBudgetScope, r as WorkerCompletion } from "./Worker-Bbj9uq5H.mjs";
|
|
10
|
+
import { V as RunSubagentDigests, x as RunContextPreparation } from "./RunOptions-qOcPv08p.mjs";
|
|
11
|
+
import { i as SubagentHost, l as WorkerReporting } from "./SubagentHost-DEPw4YME.mjs";
|
|
12
|
+
import { S as ToolCallWaiting, _ as SubagentDurability, b as SubagentDurabilityError, c as AgentSpawner, h as SpawnRunOptions, l as AgentSpawnerParent, o as AgentRuntimeFailure, p as RuntimeBinding, s as AgentRuntimeRequirements } from "./AgentRuntime-BEXToYl1.mjs";
|
|
12
13
|
import { t as RunEventSink } from "./RunEventSink-D5aVhISG.mjs";
|
|
13
14
|
import { Tool, Toolkit } from "effect/unstable/ai";
|
|
14
15
|
import { Crypto, Duration, Effect, Layer, Schema, Scope, Stream } from "effect";
|
|
@@ -81,6 +82,9 @@ declare const SubagentProjectionFailure_base: Schema.Class<SubagentProjectionFai
|
|
|
81
82
|
readonly delegationId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/DelegationId">;
|
|
82
83
|
readonly stage: Schema.Literals<readonly ["input", "result"]>;
|
|
83
84
|
readonly message: Schema.String;
|
|
85
|
+
/** Original validation error; detailed diagnostics are never part of the safe message. */
|
|
86
|
+
readonly cause: Schema.optionalKey<Schema.decodeTo<Schema.Unknown, Schema.Codec<Diagnostic, Diagnostic, never, never>, never, never>>;
|
|
87
|
+
readonly stack: Schema.optionalKey<Schema.String>;
|
|
84
88
|
}>, import("effect/Cause").YieldableError>;
|
|
85
89
|
/**
|
|
86
90
|
* Input or result projection failed its Schema or bounds.
|
|
@@ -120,7 +124,26 @@ declare const Worker: <const Name extends string>(declaration: WorkerDeclaration
|
|
|
120
124
|
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
121
125
|
}>, `@effect-agent/Worker/${Name}`>;
|
|
122
126
|
type Worker<Name extends string> = ReturnType<typeof Worker<Name>>["Type"];
|
|
123
|
-
/**
|
|
127
|
+
/** Model-facing projection deliberately excludes operator-private diagnostics. */
|
|
128
|
+
declare const toolObservation: <Success extends Schema.Top>(success: Success) => Schema.Union<readonly [Schema.Struct<{
|
|
129
|
+
readonly _tag: Schema.Literal<"Pending">;
|
|
130
|
+
readonly receipt: typeof Receipt;
|
|
131
|
+
}>, Schema.Struct<{
|
|
132
|
+
readonly _tag: Schema.Literal<"Settled">;
|
|
133
|
+
readonly receipt: typeof Receipt;
|
|
134
|
+
readonly runId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/RunId">;
|
|
135
|
+
readonly settlementId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/SettlementId">;
|
|
136
|
+
readonly outcome: Schema.Literal<"completed">;
|
|
137
|
+
readonly result: Success;
|
|
138
|
+
}>, Schema.Struct<{
|
|
139
|
+
readonly _tag: Schema.Literal<"Settled">;
|
|
140
|
+
readonly receipt: typeof Receipt;
|
|
141
|
+
readonly runId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "@effect-agent/core/RunId">>;
|
|
142
|
+
readonly settlementId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/SettlementId">;
|
|
143
|
+
readonly outcome: Schema.Literals<readonly ["failed", "aborted"]>;
|
|
144
|
+
readonly failure: typeof SubagentExecutionFailure;
|
|
145
|
+
}>]>;
|
|
146
|
+
/** One exact Receipt, including private canonical failure evidence for programmatic callers. */
|
|
124
147
|
declare const WorkerObservation: <Success extends Schema.Top>(success: Success) => Schema.Union<readonly [Schema.Struct<{
|
|
125
148
|
readonly _tag: Schema.Literal<"Pending">;
|
|
126
149
|
readonly receipt: typeof Receipt;
|
|
@@ -138,6 +161,111 @@ declare const WorkerObservation: <Success extends Schema.Top>(success: Success)
|
|
|
138
161
|
readonly settlementId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/SettlementId">;
|
|
139
162
|
readonly outcome: Schema.Literals<readonly ["failed", "aborted"]>;
|
|
140
163
|
readonly failure: typeof SubagentExecutionFailure;
|
|
164
|
+
readonly diagnostic: Schema.optionalKey<Schema.declareConstructor<{
|
|
165
|
+
readonly errorTag: string;
|
|
166
|
+
readonly message: string;
|
|
167
|
+
readonly diagnostic?: Diagnostic | undefined;
|
|
168
|
+
readonly context?: {
|
|
169
|
+
readonly agentId?: string | undefined;
|
|
170
|
+
readonly threadId?: string | undefined;
|
|
171
|
+
readonly runId?: string | undefined;
|
|
172
|
+
readonly submissionId?: string | undefined;
|
|
173
|
+
readonly attemptId?: string | undefined;
|
|
174
|
+
readonly turnId?: string | undefined;
|
|
175
|
+
readonly toolCallId?: string | undefined;
|
|
176
|
+
readonly toolName?: string | undefined;
|
|
177
|
+
readonly callId?: string | undefined;
|
|
178
|
+
readonly check?: string | undefined;
|
|
179
|
+
readonly operation?: string | undefined;
|
|
180
|
+
} | undefined;
|
|
181
|
+
}, {
|
|
182
|
+
readonly errorTag: string;
|
|
183
|
+
readonly message: string;
|
|
184
|
+
readonly diagnostic?: Diagnostic | undefined;
|
|
185
|
+
readonly context?: {
|
|
186
|
+
readonly agentId?: string | undefined;
|
|
187
|
+
readonly threadId?: string | undefined;
|
|
188
|
+
readonly runId?: string | undefined;
|
|
189
|
+
readonly submissionId?: string | undefined;
|
|
190
|
+
readonly attemptId?: string | undefined;
|
|
191
|
+
readonly turnId?: string | undefined;
|
|
192
|
+
readonly toolCallId?: string | undefined;
|
|
193
|
+
readonly toolName?: string | undefined;
|
|
194
|
+
readonly callId?: string | undefined;
|
|
195
|
+
readonly check?: string | undefined;
|
|
196
|
+
readonly operation?: string | undefined;
|
|
197
|
+
} | undefined;
|
|
198
|
+
}, readonly [Schema.Struct<{
|
|
199
|
+
readonly errorTag: Schema.NonEmptyString;
|
|
200
|
+
readonly message: Schema.String;
|
|
201
|
+
readonly diagnostic: Schema.optionalKey<Schema.Codec<Diagnostic, Diagnostic, never, never>>;
|
|
202
|
+
readonly context: Schema.optionalKey<Schema.declareConstructor<{
|
|
203
|
+
readonly agentId?: string | undefined;
|
|
204
|
+
readonly threadId?: string | undefined;
|
|
205
|
+
readonly runId?: string | undefined;
|
|
206
|
+
readonly submissionId?: string | undefined;
|
|
207
|
+
readonly attemptId?: string | undefined;
|
|
208
|
+
readonly turnId?: string | undefined;
|
|
209
|
+
readonly toolCallId?: string | undefined;
|
|
210
|
+
readonly toolName?: string | undefined;
|
|
211
|
+
readonly callId?: string | undefined;
|
|
212
|
+
readonly check?: string | undefined;
|
|
213
|
+
readonly operation?: string | undefined;
|
|
214
|
+
}, {
|
|
215
|
+
readonly agentId?: string | undefined;
|
|
216
|
+
readonly threadId?: string | undefined;
|
|
217
|
+
readonly runId?: string | undefined;
|
|
218
|
+
readonly submissionId?: string | undefined;
|
|
219
|
+
readonly attemptId?: string | undefined;
|
|
220
|
+
readonly turnId?: string | undefined;
|
|
221
|
+
readonly toolCallId?: string | undefined;
|
|
222
|
+
readonly toolName?: string | undefined;
|
|
223
|
+
readonly callId?: string | undefined;
|
|
224
|
+
readonly check?: string | undefined;
|
|
225
|
+
readonly operation?: string | undefined;
|
|
226
|
+
}, readonly [Schema.Struct<{
|
|
227
|
+
readonly agentId: Schema.optionalKey<Schema.String>;
|
|
228
|
+
readonly threadId: Schema.optionalKey<Schema.String>;
|
|
229
|
+
readonly runId: Schema.optionalKey<Schema.String>;
|
|
230
|
+
readonly submissionId: Schema.optionalKey<Schema.String>;
|
|
231
|
+
readonly attemptId: Schema.optionalKey<Schema.String>;
|
|
232
|
+
readonly turnId: Schema.optionalKey<Schema.String>;
|
|
233
|
+
readonly toolCallId: Schema.optionalKey<Schema.String>;
|
|
234
|
+
readonly toolName: Schema.optionalKey<Schema.String>;
|
|
235
|
+
readonly callId: Schema.optionalKey<Schema.String>;
|
|
236
|
+
readonly check: Schema.optionalKey<Schema.String>;
|
|
237
|
+
readonly operation: Schema.optionalKey<Schema.String>;
|
|
238
|
+
}>], {
|
|
239
|
+
readonly agentId?: string | undefined;
|
|
240
|
+
readonly threadId?: string | undefined;
|
|
241
|
+
readonly runId?: string | undefined;
|
|
242
|
+
readonly submissionId?: string | undefined;
|
|
243
|
+
readonly attemptId?: string | undefined;
|
|
244
|
+
readonly turnId?: string | undefined;
|
|
245
|
+
readonly toolCallId?: string | undefined;
|
|
246
|
+
readonly toolName?: string | undefined;
|
|
247
|
+
readonly callId?: string | undefined;
|
|
248
|
+
readonly check?: string | undefined;
|
|
249
|
+
readonly operation?: string | undefined;
|
|
250
|
+
}>>;
|
|
251
|
+
}>], {
|
|
252
|
+
readonly errorTag: string;
|
|
253
|
+
readonly message: string;
|
|
254
|
+
readonly diagnostic?: Diagnostic | undefined;
|
|
255
|
+
readonly context?: {
|
|
256
|
+
readonly agentId?: string | undefined;
|
|
257
|
+
readonly threadId?: string | undefined;
|
|
258
|
+
readonly runId?: string | undefined;
|
|
259
|
+
readonly submissionId?: string | undefined;
|
|
260
|
+
readonly attemptId?: string | undefined;
|
|
261
|
+
readonly turnId?: string | undefined;
|
|
262
|
+
readonly toolCallId?: string | undefined;
|
|
263
|
+
readonly toolName?: string | undefined;
|
|
264
|
+
readonly callId?: string | undefined;
|
|
265
|
+
readonly check?: string | undefined;
|
|
266
|
+
readonly operation?: string | undefined;
|
|
267
|
+
} | undefined;
|
|
268
|
+
}>>;
|
|
141
269
|
}>]>;
|
|
142
270
|
type WorkerObservation<Success extends Schema.Top> = ReturnType<typeof WorkerObservation<Success>>["Type"];
|
|
143
271
|
declare const operations: <const Name extends string, Input extends Schema.Top, Output extends Schema.Top, Parameters extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top, Prepare, Project>(declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>) => {
|
|
@@ -176,6 +304,24 @@ declare const operations: <const Name extends string, Input extends Schema.Top,
|
|
|
176
304
|
readonly settlementId: string & import("effect/Brand").Brand<"@effect-agent/core/SettlementId">;
|
|
177
305
|
readonly outcome: "aborted" | "failed";
|
|
178
306
|
readonly failure: SubagentExecutionFailure;
|
|
307
|
+
readonly diagnostic?: {
|
|
308
|
+
readonly errorTag: string;
|
|
309
|
+
readonly message: string;
|
|
310
|
+
readonly diagnostic?: Diagnostic | undefined;
|
|
311
|
+
readonly context?: {
|
|
312
|
+
readonly agentId?: string | undefined;
|
|
313
|
+
readonly threadId?: string | undefined;
|
|
314
|
+
readonly runId?: string | undefined;
|
|
315
|
+
readonly submissionId?: string | undefined;
|
|
316
|
+
readonly attemptId?: string | undefined;
|
|
317
|
+
readonly turnId?: string | undefined;
|
|
318
|
+
readonly toolCallId?: string | undefined;
|
|
319
|
+
readonly toolName?: string | undefined;
|
|
320
|
+
readonly callId?: string | undefined;
|
|
321
|
+
readonly check?: string | undefined;
|
|
322
|
+
readonly operation?: string | undefined;
|
|
323
|
+
} | undefined;
|
|
324
|
+
} | undefined;
|
|
179
325
|
} | Schema.Struct.View<{
|
|
180
326
|
readonly _tag: Schema.Literal<"Settled">;
|
|
181
327
|
readonly receipt: typeof Receipt;
|
|
@@ -265,6 +411,24 @@ declare const awaitWorker: <const Name extends string, Input extends Schema.Top,
|
|
|
265
411
|
readonly settlementId: string & import("effect/Brand").Brand<"@effect-agent/core/SettlementId">;
|
|
266
412
|
readonly outcome: "aborted" | "failed";
|
|
267
413
|
readonly failure: SubagentExecutionFailure;
|
|
414
|
+
readonly diagnostic?: {
|
|
415
|
+
readonly errorTag: string;
|
|
416
|
+
readonly message: string;
|
|
417
|
+
readonly diagnostic?: Diagnostic | undefined;
|
|
418
|
+
readonly context?: {
|
|
419
|
+
readonly agentId?: string | undefined;
|
|
420
|
+
readonly threadId?: string | undefined;
|
|
421
|
+
readonly runId?: string | undefined;
|
|
422
|
+
readonly submissionId?: string | undefined;
|
|
423
|
+
readonly attemptId?: string | undefined;
|
|
424
|
+
readonly turnId?: string | undefined;
|
|
425
|
+
readonly toolCallId?: string | undefined;
|
|
426
|
+
readonly toolName?: string | undefined;
|
|
427
|
+
readonly callId?: string | undefined;
|
|
428
|
+
readonly check?: string | undefined;
|
|
429
|
+
readonly operation?: string | undefined;
|
|
430
|
+
} | undefined;
|
|
431
|
+
} | undefined;
|
|
268
432
|
} | Schema.Struct.View<{
|
|
269
433
|
readonly _tag: Schema.Literal<"Settled">;
|
|
270
434
|
readonly receipt: typeof Receipt;
|
|
@@ -396,7 +560,7 @@ type ToolSchemas<Name extends string, Parameters extends Schema.Top, Success ext
|
|
|
396
560
|
};
|
|
397
561
|
inspect: {
|
|
398
562
|
parameters: ReturnType<typeof ReceiptParameters<Name>>;
|
|
399
|
-
success: ReturnType<typeof
|
|
563
|
+
success: ReturnType<typeof toolObservation<Success>>;
|
|
400
564
|
failure: ReturnType<typeof preparationFailure<Failure>>;
|
|
401
565
|
};
|
|
402
566
|
summary: {
|
|
@@ -823,4 +987,4 @@ declare function background<const Name extends string, Input extends Schema.Top,
|
|
|
823
987
|
declare function background<const Name extends string, Input extends Schema.Top, Output extends Schema.Top, Parameters extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top, Prepare, Project, const Selected extends BackgroundOptions>(declaration: Declaration<Name, Input, Output, Parameters, Success, Failure, Prepare, Project>, selected: Selected): ReturnType<typeof background$1<Name, Input, Output, Parameters, Success, Failure, Prepare, Project, Selected>>;
|
|
824
988
|
//#endregion
|
|
825
989
|
export { cancel as A, delegationAllocationFromPolicy as B, reporting as C, Worker as D, BackgroundTools as E, start as F, SubagentPolicy as I, SubagentPolicyInput as L, inspect as M, list as N, WorkerObservation as O, observe as P, SubagentPrestartDenied as R, make as S, BackgroundOptions as T, delegationCapsFromPolicy as V, SubagentTools as _, SubagentDelegation as a, define as b, SubagentFailureMode as c, SubagentResult as d, SubagentResultContext as f, SubagentToolFailure as g, SubagentTool as h, SubagentDefineOptions as i, followUp as j, awaitWorker as k, SubagentLayerRequirements as l, SubagentRuntimeOptions as m, SubagentContainedFailure as n, SubagentDurableAccounting as o, SubagentReturnModeFailure as p, SubagentDeclarationOptions as r, SubagentDurableOptions as s, SubagentChildRunFailure as t, SubagentPrepareContext as u, Subagent_d_exports as v, reportingToWorker as w, layer as x, background as y, SubagentProjectionFailure as z };
|
|
826
|
-
//# sourceMappingURL=Subagent-
|
|
990
|
+
//# sourceMappingURL=Subagent-BxuDuCHt.d.mts.map
|