agents 0.23.0 → 0.25.0
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-routing-DE5zmCQ8.d.ts → agent-routing-0DR0Tk2v.d.ts} +270 -190
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-routing.js.map +1 -1
- package/dist/agent-tool-types.d.ts +13 -7
- package/dist/agent-tool-types.js +23 -1
- package/dist/agent-tool-types.js.map +1 -1
- package/dist/{agent-tools-y7zLfw4Q.js → agent-tools-CdJC-8Dc.js} +72 -9
- package/dist/agent-tools-CdJC-8Dc.js.map +1 -0
- package/dist/{agent-tools-DtXMTDGM.d.ts → agent-tools-YrATZJu2.d.ts} +29 -15
- package/dist/agent-tools.d.ts +6 -4
- package/dist/agent-tools.js.map +1 -1
- package/dist/ai-fm7xx1BK.js +312 -0
- package/dist/ai-fm7xx1BK.js.map +1 -0
- package/dist/base64-redaction-C1Uu29t5.js +59 -0
- package/dist/base64-redaction-C1Uu29t5.js.map +1 -0
- package/dist/browser/ai-sdk.d.ts +90 -0
- package/dist/browser/ai-sdk.js +51 -0
- package/dist/browser/ai-sdk.js.map +1 -0
- package/dist/browser/ai.d.ts +4 -4
- package/dist/browser/ai.js +1 -347
- package/dist/browser/index.d.ts +81 -79
- package/dist/browser/index.js +361 -2
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/tanstack-ai.d.ts +96 -1
- package/dist/browser/tanstack-ai.js +62 -2
- package/dist/browser/tanstack-ai.js.map +1 -1
- package/dist/browser-DE3d-RLk.d.ts +275 -0
- package/dist/browser-tool-CQ10e6Kj.js +480 -0
- package/dist/browser-tool-CQ10e6Kj.js.map +1 -0
- package/dist/browser-tool-DuNdlwZ9.d.ts +73 -0
- package/dist/{capability-BjSKYpzg.js → capability-B4WbF81e.js} +2 -1
- package/dist/capability-B4WbF81e.js.map +1 -0
- package/dist/{capability-runner-Be_-PLR1.d.ts → capability-runner-DBAnGr6L.d.ts} +45 -15
- package/dist/chat/index.d.ts +341 -232
- package/dist/chat/index.js +602 -72
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.d.ts +42 -2
- package/dist/chat/react.js +191 -35
- package/dist/chat/react.js.map +1 -1
- package/dist/chat/transport.d.ts +1 -1
- package/dist/chat/transport.js +1 -1
- package/dist/chat-sdk/index.d.ts +17 -3
- package/dist/chat-sdk/index.js +28 -2
- package/dist/chat-sdk/index.js.map +1 -1
- package/dist/client-4OlMIJx-.js +591 -0
- package/dist/client-4OlMIJx-.js.map +1 -0
- package/dist/{client-jagG8a9_.js → client-fyQrLGkD.js} +2 -2
- package/dist/{client-jagG8a9_.js.map → client-fyQrLGkD.js.map} +1 -1
- package/dist/client-je3koD9Z.d.ts +446 -0
- package/dist/client.d.ts +29 -283
- package/dist/client.js +2 -274
- package/dist/{connector-CptFKzRh.js → connector-58XDGvc3.js} +251 -120
- package/dist/connector-58XDGvc3.js.map +1 -0
- package/dist/{connector-CkQD4MK3.d.ts → connector-Cl-VqPmA.d.ts} +244 -146
- package/dist/context/index.d.ts +29 -0
- package/dist/context/index.js +64 -17
- package/dist/context/index.js.map +1 -1
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/current-agent-vAk_5JMt.d.ts +93 -0
- package/dist/{current-agent-Da_C9a3b.d.ts → durable-object-lifecycle-HhgOMWq9.d.ts} +26 -127
- package/dist/harnesses/pi/index.d.ts +348 -0
- package/dist/harnesses/pi/index.js +754 -0
- package/dist/harnesses/pi/index.js.map +1 -0
- package/dist/images-iiTDSyRu.js +1631 -0
- package/dist/images-iiTDSyRu.js.map +1 -0
- package/dist/index-BreL0YrQ.d.ts +78 -0
- package/dist/index-kbSUIer3.d.ts +343 -0
- package/dist/index.d.ts +43 -41
- package/dist/index.js +2 -2
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +19 -17
- package/dist/lifecycle/index.js +2 -2
- package/dist/{lifecycle-CMRGjZdw.js → lifecycle-CFu6OV03.js} +73 -29
- package/dist/lifecycle-CFu6OV03.js.map +1 -0
- package/dist/mcp/client/index.d.ts +20 -20
- package/dist/mcp/client/index.js +1 -1
- package/dist/mcp/client/x402.js +21 -19
- package/dist/mcp/client/x402.js.map +1 -1
- package/dist/mcp/index.d.ts +35 -35
- package/dist/mcp/index.js +2 -2
- package/dist/{message-builder-BymO4N_D.js → message-builder-DAl9AhHH.js} +89 -4
- package/dist/message-builder-DAl9AhHH.js.map +1 -0
- package/dist/models/ai-sdk/index.d.ts +353 -0
- package/dist/models/ai-sdk/index.js +2443 -0
- package/dist/models/ai-sdk/index.js.map +1 -0
- package/dist/models/pi-ai/index.d.ts +313 -0
- package/dist/models/pi-ai/index.js +1795 -0
- package/dist/models/pi-ai/index.js.map +1 -0
- package/dist/observability/ai/index.js +20 -4
- package/dist/observability/ai/index.js.map +1 -1
- package/dist/{protocol-B0nh6KNf.js → protocol-kHsr-f0X.js} +26 -12
- package/dist/{protocol-B0nh6KNf.js.map → protocol-kHsr-f0X.js.map} +1 -1
- package/dist/queue/index.d.ts +123 -0
- package/dist/queue/index.js +2 -0
- package/dist/queue-BB-zfIYF.js +406 -0
- package/dist/queue-BB-zfIYF.js.map +1 -0
- package/dist/react.d.ts +31 -13
- package/dist/react.js +190 -71
- package/dist/react.js.map +1 -1
- package/dist/{retries-D9Ds-1lz.d.ts → retries-CV6AkXmQ.d.ts} +23 -8
- package/dist/retries.d.ts +12 -8
- package/dist/retries.js +19 -1
- package/dist/retries.js.map +1 -1
- package/dist/routing/index.d.ts +2 -2
- package/dist/routing/index.js +1 -1
- package/dist/{scheduler-DD9NdYbF.js → scheduler-DZ3xQfeK.js} +4 -11
- package/dist/scheduler-DZ3xQfeK.js.map +1 -0
- package/dist/{scheduler-Dwh85ZGl.d.ts → scheduler-RdACNXDP.d.ts} +6 -6
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/sessions/index.d.ts +70 -3
- package/dist/sessions/index.js +276 -67
- package/dist/sessions/index.js.map +1 -1
- package/dist/skills/index.d.ts +29 -314
- package/dist/socket-address.d.ts +16 -0
- package/dist/socket-address.js +19 -0
- package/dist/socket-address.js.map +1 -0
- package/dist/{src-DlSHshb2.js → src-BZeu-SCD.js} +541 -500
- package/dist/src-BZeu-SCD.js.map +1 -0
- package/dist/state/index.d.ts +6 -0
- package/dist/state/index.js +137 -0
- package/dist/state/index.js.map +1 -0
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/{streams-D6tJ0NN9.d.ts → streams-Cmkj9QfW.d.ts} +4 -2
- package/dist/{streams-DZKgAj9b.js → streams-DW-UCOUc.js} +9 -2
- package/dist/streams-DW-UCOUc.js.map +1 -0
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-ylZgBjhj.js → tasks-68DESxf0.js} +3 -3
- package/dist/{tasks-ylZgBjhj.js.map → tasks-68DESxf0.js.map} +1 -1
- package/dist/{tasks-BRJ5zgya.d.ts → tasks-9YxYtByh.d.ts} +5 -5
- package/dist/transport-PfFnt-Ld.d.ts +525 -0
- package/dist/transport-protocol-BxyngQ_R.js +25 -0
- package/dist/transport-protocol-BxyngQ_R.js.map +1 -0
- package/dist/transport-protocol-ZTew5Wso.d.ts +27 -0
- package/dist/types-BA4anrjI.d.ts +70 -0
- package/dist/voice/index.d.ts +2 -2
- package/dist/websockets/index.d.ts +195 -69
- package/dist/websockets/index.js +3 -2
- package/dist/websockets-Ci-LZFHH.js +1030 -0
- package/dist/websockets-Ci-LZFHH.js.map +1 -0
- package/dist/wire-types-CnMt6_HR.js.map +1 -1
- package/dist/wire-types-CrjKvDyi.d.ts +300 -0
- package/dist/workflow-types.d.ts +25 -25
- package/dist/workflows.d.ts +21 -21
- package/dist/workflows.js +1 -1
- package/dist/{ws-chat-transport-UNRIS2xl.d.ts → ws-chat-transport-BbT1A5Lc.d.ts} +51 -2
- package/dist/{ws-chat-transport-rWwta645.js → ws-chat-transport-cqMKq3IY.js} +143 -16
- package/dist/ws-chat-transport-cqMKq3IY.js.map +1 -0
- package/docs/agent-class.md +2 -2
- package/docs/agent-tools.md +29 -4
- package/docs/browse-the-web.md +87 -5
- package/docs/chat-agents.md +124 -16
- package/docs/client-sdk.md +30 -0
- package/docs/context.md +27 -0
- package/docs/durable-execution.md +2 -0
- package/docs/harnesses/pi.md +91 -0
- package/docs/human-in-the-loop.md +4 -0
- package/docs/index.md +4 -1
- package/docs/lifecycle.md +114 -23
- package/docs/models-pi-ai.md +325 -0
- package/docs/models.md +504 -0
- package/docs/queue.md +135 -241
- package/docs/resumable-streaming.md +2 -0
- package/docs/retries.md +1 -1
- package/docs/routing.md +13 -13
- package/docs/sessions.md +36 -1
- package/docs/state.md +1 -0
- package/docs/sub-agents.md +12 -3
- package/package.json +51 -3
- package/dist/agent-tools-y7zLfw4Q.js.map +0 -1
- package/dist/browser/ai.js.map +0 -1
- package/dist/capability-BjSKYpzg.js.map +0 -1
- package/dist/client-tools-aIBO0Fk7.d.ts +0 -53
- package/dist/client.js.map +0 -1
- package/dist/connector-CptFKzRh.js.map +0 -1
- package/dist/lifecycle-CMRGjZdw.js.map +0 -1
- package/dist/message-builder-BymO4N_D.js.map +0 -1
- package/dist/scheduler-DD9NdYbF.js.map +0 -1
- package/dist/src-DlSHshb2.js.map +0 -1
- package/dist/streams-DZKgAj9b.js.map +0 -1
- package/dist/websockets-DUfRHPRq.js +0 -502
- package/dist/websockets-DUfRHPRq.js.map +0 -1
- package/dist/ws-chat-transport-rWwta645.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"message-builder-BymO4N_D.js","names":[],"sources":["../src/chat/message-builder.ts"],"sourcesContent":["/**\n * Shared message builder for reconstructing UIMessage parts from stream chunks.\n *\n * Used by both @cloudflare/ai-chat (server + client) and @cloudflare/think\n * to avoid duplicating the chunk-type switch/case logic.\n *\n * Operates on a mutable parts array for performance (avoids allocating new arrays\n * on every chunk during streaming).\n */\n\nimport type { UIMessage } from \"ai\";\n\n/** The parts array type from UIMessage */\nexport type MessageParts = UIMessage[\"parts\"];\n\n/** A single part from the UIMessage parts array */\nexport type MessagePart = MessageParts[number];\n\n/**\n * Parsed chunk data from an AI SDK stream event.\n * This is the JSON-parsed body of a CF_AGENT_USE_CHAT_RESPONSE message,\n * or the `data:` payload of an SSE line.\n */\nexport type StreamChunkData = {\n type: string;\n id?: string;\n delta?: string;\n text?: string;\n mediaType?: string;\n url?: string;\n sourceId?: string;\n title?: string;\n filename?: string;\n toolCallId?: string;\n toolName?: string;\n input?: unknown;\n inputTextDelta?: string;\n output?: unknown;\n state?: string;\n errorText?: string;\n /** When true, the output is preliminary (may be updated by a later chunk) */\n preliminary?: boolean;\n /** Approval ID for tools with needsApproval */\n approvalId?: string;\n /** Optional framework-specific metadata for the approval request. */\n approvalDescriptor?: unknown;\n providerMetadata?: Record<string, unknown>;\n /** Whether the tool was executed by the provider (e.g. Gemini code execution) */\n providerExecuted?: boolean;\n /** Payload for data-* parts (developer-defined typed JSON) */\n data?: unknown;\n /** When true, data parts are ephemeral and not persisted to message.parts */\n transient?: boolean;\n /** Message ID assigned by the server at stream start */\n messageId?: string;\n /** Per-message metadata attached by start/finish/message-metadata chunks */\n messageMetadata?: unknown;\n [key: string]: unknown;\n};\n\n/** Whether a value is a plain (non-array, non-null) object. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Coerce a tool part's `input` into a provider-acceptable object.\n *\n * The Anthropic Messages API requires `tool_use.input` to be a JSON **object** —\n * `null`, `undefined`, `\"\"`, a raw string, **or an array** are all rejected with\n * `tool_use.input: Input should be an object` (verified empirically against the\n * live API: `{}` → 200, but `\"\"`, `[]`, and `[{...}]` all → 400). A streamed\n * tool call that finishes with no `input_json_delta` events (the model called\n * the tool with no args), or whose input surfaces as a stringified JSON blob,\n * can persist one of these shapes — and because it lives in durable storage, the\n * session is then wedged across reconnects, redeploys, and DO evictions.\n * Enforcing the invariant at the write boundary (and as a read-side repair\n * backstop) keeps the transcript valid.\n *\n * - A plain (non-array) object is returned untouched (`changed: false`).\n * - A string that parses to a plain object is parsed.\n * - Everything else (`null`, `undefined`, `\"\"`, arrays, primitives, non-object\n * or unparseable JSON) collapses to `{}`.\n */\nexport function normalizeToolInput(raw: unknown): {\n input: unknown;\n changed: boolean;\n} {\n if (isPlainObject(raw)) return { input: raw, changed: false };\n if (typeof raw === \"string\" && raw.trim().startsWith(\"{\")) {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (isPlainObject(parsed)) return { input: parsed, changed: true };\n } catch {\n // Unparseable / partial JSON — fall through to the empty-object default.\n }\n }\n return { input: {}, changed: true };\n}\n\n/**\n * Applies a stream chunk to a mutable parts array, building up the message\n * incrementally. Returns true if the chunk was handled, false if it was\n * an unrecognized type (caller may handle it with additional logic).\n *\n * Handles all common chunk types that both server and client need:\n * - text-start / text-delta / text-end\n * - reasoning-start / reasoning-delta / reasoning-end\n * - file\n * - source-url / source-document\n * - tool-input-start / tool-input-delta / tool-input-available / tool-input-error\n * - tool-output-available / tool-output-error\n * - step-start (aliased from start-step)\n * - data-* (developer-defined typed JSON blobs)\n *\n * @param parts - The mutable parts array to update\n * @param chunk - The parsed stream chunk data\n * @returns true if handled, false if the chunk type is not recognized\n */\nexport function applyChunkToParts(\n parts: MessagePart[],\n chunk: StreamChunkData\n): boolean {\n switch (chunk.type) {\n case \"text-start\": {\n parts.push({\n type: \"text\",\n text: \"\",\n state: \"streaming\"\n } as MessagePart);\n return true;\n }\n\n case \"text-delta\": {\n const lastTextPart = findLastPartByType(parts, \"text\");\n if (lastTextPart && lastTextPart.type === \"text\") {\n (lastTextPart as { text: string }).text += chunk.delta ?? \"\";\n } else {\n // No text-start received — create a new text part (stream resumption fallback)\n parts.push({\n type: \"text\",\n text: chunk.delta ?? \"\",\n state: \"streaming\"\n } as MessagePart);\n }\n return true;\n }\n\n case \"text-end\": {\n const lastTextPart = findLastPartByType(parts, \"text\");\n if (lastTextPart && \"state\" in lastTextPart) {\n (lastTextPart as { state: string }).state = \"done\";\n }\n return true;\n }\n\n case \"reasoning-start\": {\n parts.push({\n type: \"reasoning\",\n text: \"\",\n state: \"streaming\"\n } as MessagePart);\n return true;\n }\n\n case \"reasoning-delta\": {\n const lastReasoningPart = findLastPartByType(parts, \"reasoning\");\n if (lastReasoningPart && lastReasoningPart.type === \"reasoning\") {\n (lastReasoningPart as { text: string }).text += chunk.delta ?? \"\";\n mergeProviderMetadata(lastReasoningPart, chunk.providerMetadata);\n } else {\n // No reasoning-start received — create a new reasoning part (stream resumption fallback)\n parts.push({\n type: \"reasoning\",\n text: chunk.delta ?? \"\",\n state: \"streaming\",\n ...(chunk.providerMetadata != null\n ? { providerMetadata: chunk.providerMetadata }\n : {})\n } as MessagePart);\n }\n return true;\n }\n\n case \"reasoning-end\": {\n const lastReasoningPart = findLastPartByType(parts, \"reasoning\");\n if (lastReasoningPart && \"state\" in lastReasoningPart) {\n (lastReasoningPart as { state: string }).state = \"done\";\n mergeProviderMetadata(lastReasoningPart, chunk.providerMetadata);\n }\n return true;\n }\n\n case \"file\": {\n parts.push({\n type: \"file\",\n mediaType: chunk.mediaType,\n url: chunk.url\n } as MessagePart);\n return true;\n }\n\n case \"source-url\": {\n parts.push({\n type: \"source-url\",\n sourceId: chunk.sourceId,\n url: chunk.url,\n title: chunk.title,\n providerMetadata: chunk.providerMetadata\n } as MessagePart);\n return true;\n }\n\n case \"source-document\": {\n parts.push({\n type: \"source-document\",\n sourceId: chunk.sourceId,\n mediaType: chunk.mediaType,\n title: chunk.title,\n filename: chunk.filename,\n providerMetadata: chunk.providerMetadata\n } as MessagePart);\n return true;\n }\n\n case \"tool-input-start\": {\n // Idempotent against an existing tool part with the same toolCallId.\n // Some providers (notably the OpenAI Responses API) replay prior\n // tool calls in continuation streams as a fresh `tool-input-start`\n // → `tool-input-delta` → `tool-input-available` →\n // `tool-output-available` sequence carrying the original toolCallId\n // and original output. Without this guard a replay would push a\n // duplicate part into the streaming message *and* clobber the\n // original part's state when the AI SDK's mutate-in-place\n // `updateToolPart` processes the replay on the client (issue #1404).\n // A model that genuinely wants a fresh tool call always emits a\n // new toolCallId, so an existing match is never a legitimate\n // \"start over\".\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (existing) {\n return true;\n }\n parts.push({\n type: `tool-${chunk.toolName}`,\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-streaming\",\n input: undefined,\n ...(chunk.providerExecuted != null\n ? { providerExecuted: chunk.providerExecuted }\n : {}),\n ...(chunk.providerMetadata != null\n ? { callProviderMetadata: chunk.providerMetadata }\n : {}),\n ...(chunk.title != null ? { title: chunk.title } : {})\n } as MessagePart);\n return true;\n }\n\n case \"tool-input-delta\": {\n // Only mutate input while the tool is still actively input-streaming.\n // Deltas arriving after the tool has already advanced (input-available\n // or any terminal state) are provider replay and must not regress\n // a fully-formed input back to a partial one.\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (\n toolPart &&\n (toolPart as Record<string, unknown>).state === \"input-streaming\"\n ) {\n (toolPart as Record<string, unknown>).input = chunk.input;\n }\n return true;\n }\n\n case \"tool-input-available\": {\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (existing) {\n const p = existing as Record<string, unknown>;\n // Only advance from the streaming-input phase. Once the tool is\n // already at input-available or any terminal state\n // (output-available, output-error, output-denied,\n // approval-requested, approval-responded), this chunk is a\n // provider replay and must not regress state or overwrite a\n // resolved input/output. See the comment on tool-input-start.\n if (p.state === \"input-streaming\") {\n p.state = \"input-available\";\n p.input = normalizeToolInput(chunk.input).input;\n if (chunk.providerExecuted != null) {\n p.providerExecuted = chunk.providerExecuted;\n }\n if (chunk.providerMetadata != null) {\n p.callProviderMetadata = chunk.providerMetadata;\n }\n if (chunk.title != null) {\n p.title = chunk.title;\n }\n }\n return true;\n }\n parts.push({\n type: `tool-${chunk.toolName}`,\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-available\",\n input: normalizeToolInput(chunk.input).input,\n ...(chunk.providerExecuted != null\n ? { providerExecuted: chunk.providerExecuted }\n : {}),\n ...(chunk.providerMetadata != null\n ? { callProviderMetadata: chunk.providerMetadata }\n : {}),\n ...(chunk.title != null ? { title: chunk.title } : {})\n } as MessagePart);\n return true;\n }\n\n case \"tool-input-error\": {\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (existing) {\n const p = existing as Record<string, unknown>;\n // First-write-wins: a tool that's already terminal must not be\n // regressed (or re-decided as an error) by a later chunk. A\n // tool-input-error here is either provider replay or a confused\n // upstream — preserve the existing terminal state.\n if (\n p.state === \"output-available\" ||\n p.state === \"output-error\" ||\n p.state === \"output-denied\"\n ) {\n return true;\n }\n p.state = \"output-error\";\n p.errorText = chunk.errorText;\n p.input = normalizeToolInput(chunk.input).input;\n if (chunk.providerExecuted != null) {\n p.providerExecuted = chunk.providerExecuted;\n }\n if (chunk.providerMetadata != null) {\n p.callProviderMetadata = chunk.providerMetadata;\n }\n } else {\n parts.push({\n type: `tool-${chunk.toolName}`,\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"output-error\",\n input: normalizeToolInput(chunk.input).input,\n errorText: chunk.errorText,\n ...(chunk.providerExecuted != null\n ? { providerExecuted: chunk.providerExecuted }\n : {}),\n ...(chunk.providerMetadata != null\n ? { callProviderMetadata: chunk.providerMetadata }\n : {})\n } as MessagePart);\n }\n return true;\n }\n\n case \"tool-approval-request\": {\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n // First-write-wins: a continuation can replay the prior tool\n // round-trip and re-emit `tool-approval-request`. Never regress a part\n // the user has already responded to (`approval-responded`) or that has\n // otherwise settled — that would silently discard the approval\n // decision. Matches the guards on the `tool-input-*` /\n // `tool-output-denied` handlers.\n if (\n p.state === \"approval-responded\" ||\n p.state === \"output-available\" ||\n p.state === \"output-error\" ||\n p.state === \"output-denied\"\n ) {\n return true;\n }\n p.state = \"approval-requested\";\n p.approval = {\n id: chunk.approvalId,\n ...(chunk.approvalDescriptor !== undefined && {\n descriptor: chunk.approvalDescriptor\n })\n };\n }\n return true;\n }\n\n case \"tool-output-denied\": {\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n // First-write-wins: a tool that's already terminal must not be\n // regressed by a later/replayed chunk. Also preserve an\n // `approval-responded` (user-approved) part — a continuation that\n // re-validates the transcript can emit `tool-output-denied` for an\n // approval the SDK deems unneeded (e.g. a tool without\n // `needsApproval`); that must not silently flip a granted approval\n // into a denial.\n if (\n p.state === \"output-available\" ||\n p.state === \"output-error\" ||\n p.state === \"output-denied\" ||\n p.state === \"approval-responded\"\n ) {\n return true;\n }\n p.state = \"output-denied\";\n }\n return true;\n }\n\n case \"tool-output-available\": {\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n p.state = \"output-available\";\n p.output = chunk.output;\n if (chunk.preliminary !== undefined) {\n p.preliminary = chunk.preliminary;\n }\n }\n return true;\n }\n\n case \"tool-output-error\": {\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n p.state = \"output-error\";\n p.errorText = chunk.errorText;\n }\n return true;\n }\n\n // Both \"step-start\" (client convention) and \"start-step\" (server convention)\n case \"step-start\":\n case \"start-step\": {\n parts.push({ type: \"step-start\" } as MessagePart);\n return true;\n }\n\n default: {\n // https://ai-sdk.dev/docs/ai-sdk-ui/streaming-data\n if (chunk.type.startsWith(\"data-\")) {\n // Transient parts are ephemeral — the AI SDK client fires an onData\n // callback instead of adding them to message.parts. On the server we\n // still broadcast them (so connected clients see them in real time)\n // but skip persisting them into the stored message parts.\n if (chunk.transient) {\n return true;\n }\n\n // Reconciliation: if a part with the same type AND id already exists,\n // update its data in-place instead of appending a duplicate.\n if (chunk.id != null) {\n const existing = findDataPartByTypeAndId(parts, chunk.type, chunk.id);\n if (existing) {\n (existing as Record<string, unknown>).data = chunk.data;\n return true;\n }\n }\n\n // Append new data parts to the array directly.\n // Note: `chunk.data` should always be provided — if omitted, the\n // persisted part will have `data: undefined` which JSON.stringify\n // drops, so the part will have no `data` field on reload.\n // The cast is needed because UIMessage[\"parts\"] doesn't include\n // data-* types in its union because they're an open extension point.\n parts.push({\n type: chunk.type,\n ...(chunk.id != null && { id: chunk.id }),\n data: chunk.data\n } as MessagePart);\n return true;\n }\n\n return false;\n }\n }\n}\n\n/**\n * Returns true if `chunk` would be a no-op replay against the already-known\n * `parts` — i.e. some upstream is re-emitting events for a tool call that\n * the message has already advanced past.\n *\n * Used by stream broadcasters to suppress re-broadcasting these chunks to\n * connected clients. AI SDK v6's `updateToolPart` mutates an existing tool\n * part in place when a chunk arrives with a matching `toolCallId`, so a\n * replayed `tool-input-start` would clobber an `output-available` part back\n * to `input-streaming` on the client (issue #1404).\n *\n * Only returns true when re-broadcasting would *visibly regress* state on\n * a v6 client. Safe-by-construction chunk types (e.g. `tool-output-available`\n * carrying the same output the part already has) return false.\n *\n * Conditions:\n * - `tool-input-start` for a `toolCallId` that already exists in `parts`.\n * - `tool-input-delta` for a `toolCallId` whose existing part is no longer\n * `input-streaming`.\n * - `tool-input-available` for a `toolCallId` whose existing part is no\n * longer `input-streaming` (i.e. has already advanced to `input-available`\n * or any terminal state).\n * - `tool-output-denied` for a `toolCallId` whose existing part is already\n * settled (`output-available` / `output-error` / `output-denied`) or\n * user-approved (`approval-responded`). A continuation that re-validates\n * the transcript can re-emit a denial for an approval the SDK now deems\n * unneeded; `applyChunkToParts` already drops it server-side, and this stops\n * it reaching the client (where the in-place `updateToolPart` would flip the\n * part to `output-denied`) and the replay buffer. Mirrors the\n * first-write-wins guard in `applyChunkToParts`.\n * - `tool-approval-request` for a `toolCallId` whose existing part is already\n * `approval-responded` or settled. A continuation replaying a prior tool\n * round-trip can re-emit the approval request; left unfiltered it would\n * revert an already-approved tool back to `approval-requested` on the client\n * (re-showing Approve/Reject) and replay that regression on reconnect. Same\n * pattern and rationale as `tool-output-denied`.\n */\nexport function isReplayChunk(\n parts: MessagePart[],\n chunk: StreamChunkData\n): boolean {\n if (\n chunk.type === \"tool-output-denied\" ||\n chunk.type === \"tool-approval-request\"\n ) {\n if (!chunk.toolCallId) return false;\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (!existing) return false;\n const state = (existing as Record<string, unknown>).state;\n return (\n state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\" ||\n state === \"approval-responded\"\n );\n }\n\n if (\n chunk.type !== \"tool-input-start\" &&\n chunk.type !== \"tool-input-delta\" &&\n chunk.type !== \"tool-input-available\"\n ) {\n return false;\n }\n if (!chunk.toolCallId) return false;\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (!existing) return false;\n if (chunk.type === \"tool-input-start\") return true;\n const state = (existing as Record<string, unknown>).state;\n return state !== \"input-streaming\";\n}\n\n/**\n * Finds the last part in the array matching the given type.\n * Searches from the end for efficiency (the part we want is usually recent).\n */\nfunction findLastPartByType(\n parts: MessagePart[],\n type: string\n): MessagePart | undefined {\n for (let i = parts.length - 1; i >= 0; i--) {\n if (parts[i].type === type) {\n return parts[i];\n }\n }\n return undefined;\n}\n\n/**\n * Finds a tool part by its toolCallId.\n * Searches from the end since the tool part is usually recent.\n */\nfunction findToolPartByCallId(\n parts: MessagePart[],\n toolCallId: string | undefined\n): MessagePart | undefined {\n if (!toolCallId) return undefined;\n for (let i = parts.length - 1; i >= 0; i--) {\n const p = parts[i];\n if (\"toolCallId\" in p && p.toolCallId === toolCallId) {\n return p;\n }\n }\n return undefined;\n}\n\n/**\n * Shallow-merges providerMetadata from a chunk onto an existing part.\n * Preserves any metadata already on the part (e.g. from earlier deltas)\n * while adding new keys from the chunk. This is critical for providers\n * like Anthropic that emit the thinking block signature on reasoning-end.\n */\nfunction mergeProviderMetadata(\n part: MessagePart,\n metadata: Record<string, unknown> | undefined\n): void {\n if (metadata == null) return;\n const p = part as Record<string, unknown>;\n p.providerMetadata = {\n ...(p.providerMetadata as Record<string, unknown> | undefined),\n ...metadata\n };\n}\n\n/**\n * Finds a data part by its type and id for reconciliation.\n * Data parts use type+id as a composite key so when the same combination\n * is seen again, the existing part's data is updated in-place.\n */\nfunction findDataPartByTypeAndId(\n parts: MessagePart[],\n type: string,\n id: string\n): MessagePart | undefined {\n for (let i = parts.length - 1; i >= 0; i--) {\n const p = parts[i];\n if (p.type === type && \"id\" in p && (p as { id: string }).id === id) {\n return p;\n }\n }\n return undefined;\n}\n\n/**\n * Rebuild the partial text + parts of an interrupted assistant turn from its\n * stored resumable-stream chunks. Replays each chunk body through\n * {@link applyChunkToParts}; malformed bodies are skipped. Shared by\n * `AIChatAgent` and `Think`, which read the chunks from their\n * `ResumableStream` (`getStreamChunks`) and pass them in.\n *\n * `@internal`\n */\nexport function getPartialStreamText(chunks: ReadonlyArray<{ body: string }>): {\n text: string;\n parts: MessagePart[];\n} {\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\n}\n"],"mappings":";;AA6DA,SAAS,cAAc,OAAkD;CACvE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,mBAAmB,KAGjC;CACA,IAAI,cAAc,GAAG,GAAG,OAAO;EAAE,OAAO;EAAK,SAAS;CAAM;CAC5D,IAAI,OAAO,QAAQ,YAAY,IAAI,KAAK,CAAC,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AY,MAAM;CACtB,MAAM,IAAI;CACV,EAAE,mBAAmB;EACnB,GAAI,EAAE;EACN,GAAG;CACL;AACF;;;;;;AAOA,SAAS,wBACP,OACA,MACA,IACyB;CACzB,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,IAAI,MAAM;EAChB,IAAI,EAAE,SAAS,QAAQ,QAAQ,KAAM,EAAqB,OAAO,IAC/D,OAAO;CAEX;AAEF;;;;;;;;;;AAWA,SAAgB,qBAAqB,QAGnC;CACA,MAAM,QAAuB,CAAC;CAE9B,KAAK,MAAM,SAAS,QAClB,IAAI;EAEF,kBAAkB,OADL,KAAK,MAAM,MAAM,IACF,CAAC;CAC/B,QAAQ,CAER;CAWF,OAAO;EAAE,MARI,MACV,QACE,MACC,EAAE,SAAS,UAAU,UAAU,CACnC,CAAC,CACA,KAAK,MAAM,EAAE,IAAI,CAAC,CAClB,KAAK,EAEI;EAAG;CAAM;AACvB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler-DD9NdYbF.js","names":[],"sources":["../src/schedules/schedule-timing.ts","../src/schedules/scheduler.ts"],"sourcesContent":["/**\n * Pure timing rules for persistent schedules.\n *\n * A `ScheduleTiming` is the parsed \"when and how it runs\" half of a\n * `Schedule` — everything except identity, callback, and payload. Parsing\n * user-facing inputs here keeps Scheduler's storage code to one insert path.\n */\n\nimport { parseCronExpression } from \"cron-schedule\";\n\n/** Longest allowed gap between interval executions: 30 days. */\nexport const MAX_INTERVAL_SECONDS = 30 * 24 * 60 * 60;\n\n/** When and how one schedule runs; a `Schedule` minus identity and payload. */\nexport type ScheduleTiming =\n | {\n /** One-time execution at a specific date. */\n readonly type: \"scheduled\";\n /** Unix timestamp in seconds. */\n readonly time: number;\n }\n | {\n /** One-time execution after a relative delay. */\n readonly type: \"delayed\";\n /** Unix timestamp in seconds. */\n readonly time: number;\n /** Delay from creation in seconds. */\n readonly delayInSeconds: number;\n }\n | {\n /** Recurring execution from a cron expression. */\n readonly type: \"cron\";\n /** Unix timestamp in seconds for the next execution. */\n readonly time: number;\n /** Cron expression defining the recurrence. */\n readonly cron: string;\n }\n | {\n /** Recurring execution at a fixed interval. */\n readonly type: \"interval\";\n /** Unix timestamp in seconds for the next execution. */\n readonly time: number;\n /** Number of seconds between executions. */\n readonly intervalSeconds: number;\n };\n\n/** True when this timing repeats and therefore deduplicates by default. */\nexport function isRecurring(timing: ScheduleTiming): boolean {\n return timing.type === \"cron\" || timing.type === \"interval\";\n}\n\n/**\n * Next wall-clock execution time for a cron expression.\n *\n * @param cron - A standard cron expression.\n * @param nowMs - Current epoch time in milliseconds.\n * @returns The next execution epoch time in milliseconds.\n * @throws For an unparseable cron expression.\n */\nexport function nextCronTimeMs(cron: string, nowMs: number): number {\n return parseCronExpression(cron).getNextDate(new Date(nowMs)).getTime();\n}\n\n/**\n * Parse a user-facing `when` into schedule timing.\n *\n * A `Date` runs once at that date, a number runs once after that many\n * seconds, and a string is a recurring cron expression.\n *\n * @param when - The requested execution time or recurrence.\n * @param nowMs - Current epoch time in milliseconds.\n * @param callback - Callback name, used only in error messages.\n * @returns The parsed timing.\n * @throws For a `when` value that is not a `Date`, number, or string.\n */\nexport function parseWhen(\n when: Date | string | number,\n nowMs: number,\n callback: string\n): ScheduleTiming {\n if (when instanceof Date) {\n return { type: \"scheduled\", time: Math.floor(when.getTime() / 1000) };\n }\n if (typeof when === \"number\") {\n return {\n type: \"delayed\",\n time: Math.floor((nowMs + when * 1000) / 1000),\n delayInSeconds: when\n };\n }\n if (typeof when === \"string\") {\n return {\n type: \"cron\",\n time: Math.floor(nextCronTimeMs(when, nowMs) / 1000),\n cron: when\n };\n }\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n}\n\n/**\n * Reject an interval outside the supported range.\n *\n * @param intervalSeconds - The requested gap between executions.\n * @throws For a non-positive interval or one longer than 30 days.\n */\nexport function validateIntervalSeconds(intervalSeconds: number): void {\n if (typeof intervalSeconds !== \"number\" || intervalSeconds <= 0) {\n throw new Error(\"intervalSeconds must be a positive number\");\n }\n if (intervalSeconds > MAX_INTERVAL_SECONDS) {\n throw new Error(\n `intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`\n );\n }\n}\n\n/**\n * Parse a fixed interval into schedule timing.\n *\n * @param intervalSeconds - Seconds between executions.\n * @param nowMs - Current epoch time in milliseconds.\n * @returns The parsed timing with the first execution one interval from now.\n * @throws For an interval outside the supported range.\n */\nexport function parseInterval(\n intervalSeconds: number,\n nowMs: number\n): ScheduleTiming {\n validateIntervalSeconds(intervalSeconds);\n return {\n type: \"interval\",\n time: Math.floor((nowMs + intervalSeconds * 1000) / 1000),\n intervalSeconds\n };\n}\n","/**\n * Lifecycle scheduling vocabulary. Scheduler validates schedules, resolves\n * named callbacks, and pushes jobs into the Lifecycle-owned job queue;\n * Lifecycle runs the alarm event loop, retry policy, and physical alarm\n * arming. Scheduler owns no storage of its own — each schedule is one job\n * whose `fn` is the callback name and whose payload carries the schedule's\n * timing vocabulary.\n */\n\nimport {\n LifecycleCapability,\n type LifecycleRouteAddress,\n type LifecycleRouteContext\n} from \"../lifecycle/capability\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"../lifecycle/job-queue\";\nimport {\n isDurableObjectCodeUpdateReset,\n isPlatformFailure,\n tryN,\n validateRetryOptions\n} from \"../retries\";\nimport type { RetryOptions } from \"../retries\";\nimport type { SchedulerEventType, SchedulerOptions } from \"./options\";\nimport {\n isRecurring,\n nextCronTimeMs,\n parseInterval,\n parseWhen,\n validateIntervalSeconds,\n type ScheduleTiming\n} from \"./schedule-timing\";\nimport type {\n RecoveryLoopScheduleOptions,\n Schedule,\n ScheduleCriteria,\n ScheduleOptions,\n ScheduleStorageRow,\n SchedulerCallbacks,\n SchedulerHandlers,\n SchedulerPayload\n} from \"./types\";\n\n/**\n * A resolved fallback handler for a callback name outside the registered map.\n */\ntype ResolvedSchedulerCallback = (\n payload: unknown,\n schedule: Schedule<unknown>\n) => unknown;\n\nconst schedulerCallbackResolvers = new WeakMap<\n object,\n (name: string) => ResolvedSchedulerCallback | undefined\n>();\n\n/**\n * @internal Supply a composition-root fallback for callback names outside the\n * registered map. Agent uses this to keep its historical name-based\n * scheduling API (`this.schedule(60, \"methodName\")`) working: the resolver\n * looks the method up on the Agent, and the resolved handler still runs\n * inside the Lifecycle host boundary.\n */\nexport function setSchedulerCallbackResolver(\n scheduler: Scheduler<never>,\n resolver: (name: string) => ResolvedSchedulerCallback | undefined\n): void {\n schedulerCallbackResolvers.set(scheduler, resolver);\n}\n\nconst SCHEDULE_SCHEMA_VERSION_KEY = \"cf_agents:schedules_schema_version\";\n/** Version 2: schedule rows live in the Lifecycle job queue. */\nconst CURRENT_SCHEDULE_SCHEMA_VERSION = 2;\n\n/**\n * Legacy schedule callbacks whose rows drive chat recovery loops from before\n * the job queue carried breaker membership. The migration is the one place\n * allowed to know legacy names (it already drops `_cf_keepAliveHeartbeat`\n * rows by name): a recovery row migrated without its `recoveryLoop` flag\n * would escape the alarm memory-limit breaker (#1825) and could re-trigger\n * a doomed loop on an upgraded object.\n */\nconst LEGACY_RECOVERY_LOOP_CALLBACKS = new Set([\n \"_chatRecoveryContinue\",\n \"_chatRecoveryRetry\"\n]);\n\nconst DEFAULT_RETRY: Required<RetryOptions> = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n};\n\n/**\n * The schedule timing vocabulary carried in one job's payload. The callback\n * name is the job's `fn`; the user payload rides in `payload`.\n */\ntype SchedulerJobPayload = {\n readonly payload: unknown;\n readonly type: \"scheduled\" | \"delayed\" | \"cron\" | \"interval\";\n /** The caller-supplied retry override, unresolved, for public projection.\n The job's own retry options are fully resolved against the Scheduler\n defaults at push so the Lifecycle driver applies the configured\n policy. */\n readonly retry?: RetryOptions;\n readonly delayInSeconds?: number;\n readonly cron?: string;\n readonly intervalSeconds?: number;\n readonly owner_path?: string | null;\n readonly owner_path_key?: string | null;\n};\n\ntype SchedulerRouteMessage =\n | {\n readonly type: \"schedule\";\n readonly when: Date | string | number;\n readonly callback: string;\n readonly payload?: unknown;\n readonly options?: ScheduleOptions;\n }\n | {\n readonly type: \"every\";\n readonly intervalSeconds: number;\n readonly callback: string;\n readonly payload?: unknown;\n readonly options?: ScheduleOptions;\n }\n | { readonly type: \"get\" | \"cancel\"; readonly id: string }\n | { readonly type: \"list\"; readonly criteria?: ScheduleCriteria }\n | {\n readonly type: \"dispatch\";\n readonly id: string;\n readonly fn: string;\n readonly job: SchedulerJobPayload;\n readonly retry?: RetryOptions;\n };\n\ntype InsertResult<T> = {\n readonly schedule: Schedule<T>;\n readonly created: boolean;\n};\n\nfunction resolveRetryConfig(\n retry: RetryOptions | undefined,\n defaults: Required<RetryOptions>\n): Required<RetryOptions> {\n return {\n maxAttempts: retry?.maxAttempts ?? defaults.maxAttempts,\n baseDelayMs: retry?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: retry?.maxDelayMs ?? defaults.maxDelayMs\n };\n}\n\nfunction isSchedulerJobPayload(value: unknown): value is SchedulerJobPayload {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as SchedulerJobPayload).type === \"string\"\n );\n}\n\n/**\n * Persistent task scheduling for a Lifecycle Object.\n *\n * Register callbacks in the constructor and install the instance with\n * `Lifecycle.use()`. Scheduler validates schedules and pushes them into the\n * Lifecycle job queue; Lifecycle owns the physical alarm and the alarm\n * event loop, and Scheduler runs registered callbacks through Lifecycle's\n * host invocation boundary when its jobs come due.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Scheduler<\n Handlers extends SchedulerHandlers = SchedulerCallbacks\n> extends LifecycleCapability {\n readonly #handlers: SchedulerHandlers;\n readonly #retryDefaults: Required<RetryOptions>;\n readonly #hungScheduleTimeoutSeconds: number;\n readonly #onError: ((error: unknown) => void | Promise<void>) | undefined;\n readonly #warnedStartupCallbacks = new Set<string>();\n\n /**\n * Create a persistent Scheduler.\n *\n * @param options - Registered callbacks plus optional retry,\n * hung-interval, and error policy. Registering `callbacks` types\n * {@link set} and {@link every} against the map — names and\n * payloads are checked where the handlers are declared and where they are\n * scheduled. Names outside the map are rejected unless a composition-root\n * resolver supplies them — the internal aperture behind `Agent`'s\n * name-based scheduling API.\n */\n constructor(options: SchedulerOptions<Handlers> = {}) {\n super(\"scheduler\");\n this.#handlers = options.callbacks ?? {};\n // Retry defaults are resolved, not validated, here: a host whose\n // historically tolerated invalid retry config throws at construction\n // would brick every entry point of its Durable Object. Invalid defaults\n // surface per execution as schedule:error instead, and per-schedule\n // retry overrides are still validated when each schedule is created.\n this.#retryDefaults = resolveRetryConfig(options.retry, DEFAULT_RETRY);\n this.#hungScheduleTimeoutSeconds = options.hungScheduleTimeoutSeconds ?? 30;\n this.#onError = options.onError;\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate legacy schedule storage into the Lifecycle job queue. */\n async onStart(): Promise<void> {\n this.#warnedStartupCallbacks.clear();\n const storage = this.lifecycle.storage;\n const version =\n (await storage.get<number>(SCHEDULE_SCHEMA_VERSION_KEY)) ?? 0;\n if (version >= CURRENT_SCHEDULE_SCHEMA_VERSION) return;\n\n await this.#migrateLegacyScheduleTable(storage);\n await storage.put(\n SCHEDULE_SCHEMA_VERSION_KEY,\n CURRENT_SCHEDULE_SCHEMA_VERSION\n );\n }\n\n /**\n * Move every `cf_agents_schedules` row into the job queue and drop the\n * table. Idempotent: a missing table means a fresh object or a completed\n * migration. Times convert from epoch seconds to epoch milliseconds.\n */\n async #migrateLegacyScheduleTable(\n storage: DurableObjectStorage\n ): Promise<void> {\n const tables = storage.sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name='cf_agents_schedules'\"\n )\n .toArray();\n if (tables.length === 0) return;\n\n const rows = storage.sql\n .exec(\"SELECT * FROM cf_agents_schedules\")\n .toArray() as unknown as ScheduleStorageRow[];\n for (const row of rows) {\n // Keep-alive heartbeats stopped using schedule rows long ago; drop\n // orphans instead of migrating them.\n if (row.callback === \"_cf_keepAliveHeartbeat\") continue;\n let payload: unknown;\n try {\n payload =\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined;\n } catch (error) {\n console.error(\n `Skipping schedule \"${row.id}\" during job-queue migration: ` +\n \"its payload is not valid JSON\",\n error\n );\n continue;\n }\n let retry: RetryOptions | undefined;\n try {\n retry =\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined;\n } catch {\n retry = undefined;\n }\n await this.lifecycle.jobs.push({\n id: row.id,\n fn: row.callback,\n time: row.time * 1000,\n payload: {\n payload,\n retry,\n type: row.type,\n delayInSeconds: row.delayInSeconds ?? undefined,\n cron: row.cron ?? undefined,\n intervalSeconds: row.intervalSeconds ?? undefined,\n owner_path: row.owner_path ?? null,\n owner_path_key: row.owner_path_key ?? null\n } satisfies SchedulerJobPayload,\n retry: resolveRetryConfig(retry, this.#retryDefaults),\n singleflight: row.type === \"interval\",\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop: LEGACY_RECOVERY_LOOP_CALLBACKS.has(row.callback)\n });\n }\n storage.sql.exec(\"DROP TABLE cf_agents_schedules\");\n }\n\n /** Drive one due schedule job dispatched by the Lifecycle event loop. */\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n const { job, attempt } = context;\n const timing = job.payload;\n if (!isSchedulerJobPayload(timing)) {\n console.error(`Malformed schedule job ${job.id}; dropping it`);\n return undefined;\n }\n\n if (attempt === 1) {\n this.#emit(\"schedule:execute\", { callback: job.fn, id: job.id });\n } else {\n this.#emit(\"schedule:retry\", {\n callback: job.fn,\n id: job.id,\n attempt,\n maxAttempts: resolveRetryConfig(job.retry, this.#retryDefaults)\n .maxAttempts\n });\n }\n\n if (timing.owner_path) {\n // A routed schedule executes inside its owning Lifecycle; retries run\n // there too, so this dispatch is a single routed attempt.\n try {\n await this.lifecycle.routes.to(\n {\n key: timing.owner_path_key ?? timing.owner_path,\n data: timing.owner_path\n },\n {\n type: \"dispatch\",\n id: job.id,\n fn: job.fn,\n job: timing,\n retry: job.retry\n } satisfies SchedulerRouteMessage\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n // Preserve the job; Lifecycle defers platform-class failures to a\n // fresh invocation or the memory-limit breaker.\n throw error;\n }\n console.error(\n `error dispatching scheduled callback \"${job.fn}\"`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: 0\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n // Leave the job due so a later alarm cycle can retry dispatch, for\n // example once a transport can resolve its owner again.\n return \"yield\";\n }\n return this.#recurrenceOutcome(timing);\n }\n\n const handler = this.#resolveCallback(job.fn);\n if (!handler) {\n console.error(`callback ${job.fn} not found`);\n return this.#recurrenceOutcome(timing);\n }\n const schedule = this.#jobToSchedule<unknown>(job, timing);\n await this.lifecycle.runInHostContext(() =>\n handler(timing.payload, schedule)\n );\n return this.#recurrenceOutcome(timing);\n }\n\n /** Observe one schedule's terminal application failure. */\n async onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): Promise<LifecycleJobOutcome | void> {\n const { job } = context;\n const timing = job.payload;\n if (!isSchedulerJobPayload(timing)) return undefined;\n const { maxAttempts } = resolveRetryConfig(job.retry, this.#retryDefaults);\n console.error(\n `error executing callback \"${job.fn}\" after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n return this.#recurrenceOutcome(timing);\n }\n\n /** Advance a recurring schedule; complete a one-shot. */\n #recurrenceOutcome(timing: SchedulerJobPayload): LifecycleJobOutcome {\n if (timing.type === \"cron\") {\n return { rescheduleAt: nextCronTimeMs(timing.cron ?? \"\", Date.now()) };\n }\n if (timing.type === \"interval\") {\n return {\n rescheduleAt: Date.now() + (timing.intervalSeconds ?? 0) * 1000\n };\n }\n return undefined;\n }\n\n /** Handle Scheduler protocol messages routed by another Lifecycle. */\n async onRoute(context: LifecycleRouteContext): Promise<unknown> {\n const message = context.payload as SchedulerRouteMessage;\n const owner = context.source ?? null;\n switch (message.type) {\n case \"schedule\":\n return this.#insert(\n owner,\n parseWhen(message.when, Date.now(), message.callback),\n message.callback,\n message.payload,\n message.options\n );\n case \"every\":\n return this.#insert(\n owner,\n parseInterval(message.intervalSeconds, Date.now()),\n message.callback,\n message.payload,\n message.options\n );\n case \"get\":\n return this.#getForOwner(owner, message.id);\n case \"list\":\n return this.#listForOwner(owner, message.criteria);\n case \"cancel\":\n return this.#cancelForOwner(owner, message.id);\n case \"dispatch\":\n await this.#executeRouted(\n message.id,\n message.fn,\n message.job,\n message.retry\n );\n return true;\n default:\n throw new Error(\"Unknown routed Scheduler message\");\n }\n }\n\n /**\n * Execute a routed schedule locally with the historical retry handling.\n * Runs on the owning (facet) Scheduler, outside the root's event loop, so\n * it applies its own in-process retry budget. Platform-class failures on a\n * one-shot re-throw so the root preserves the job and the durable alarm\n * retries on a fresh invocation.\n */\n async #executeRouted(\n id: string,\n fn: string,\n timing: SchedulerJobPayload,\n retry: RetryOptions | undefined\n ): Promise<void> {\n const handler = this.#resolveCallback(fn);\n if (!handler) {\n console.error(`callback ${fn} not found`);\n return;\n }\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n retry,\n this.#retryDefaults\n );\n const isOneShot = timing.type === \"delayed\" || timing.type === \"scheduled\";\n const schedule = this.#payloadToSchedule<unknown>(id, fn, timing);\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this.#emit(\"schedule:retry\", {\n callback: fn,\n id,\n attempt,\n maxAttempts\n });\n }\n await this.lifecycle.runInHostContext(() =>\n handler(timing.payload, schedule)\n );\n },\n {\n baseDelayMs,\n maxDelayMs,\n shouldRetry: (error) =>\n !(isOneShot && isDurableObjectCodeUpdateReset(error))\n }\n );\n } catch (error) {\n if (isOneShot && isPlatformFailure(error)) {\n throw error;\n }\n console.error(\n `error executing callback \"${fn}\" after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"schedule:error\", {\n callback: fn,\n id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n }\n }\n\n // ── Scheduling API ───────────────────────────────────────────────────────\n\n /** Set a delayed, dated, or cron schedule for a registered callback. */\n async set<Name extends keyof Handlers & string>(\n when: Date | string | number,\n callback: Name,\n payload?: SchedulerPayload<Handlers[Name]>,\n options?: ScheduleOptions\n ): Promise<Schedule<SchedulerPayload<Handlers[Name]>>> {\n await this.lifecycle.ready();\n this.#validateSchedule(when, callback, options);\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"schedule\",\n when,\n callback,\n payload,\n options\n } satisfies SchedulerRouteMessage)) as InsertResult<\n SchedulerPayload<Handlers[Name]>\n >)\n : await this.#insert<SchedulerPayload<Handlers[Name]>>(\n null,\n parseWhen(when, Date.now(), callback),\n callback,\n payload,\n options\n );\n this.#emitCreated(result);\n return result.schedule;\n }\n\n /** Set a fixed-interval schedule for a registered callback. */\n async every<Name extends keyof Handlers & string>(\n intervalSeconds: number,\n callback: Name,\n payload?: SchedulerPayload<Handlers[Name]>,\n options?: ScheduleOptions\n ): Promise<Schedule<SchedulerPayload<Handlers[Name]>>> {\n await this.lifecycle.ready();\n this.#validateInterval(intervalSeconds, callback, options?.retry);\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"every\",\n intervalSeconds,\n callback,\n payload,\n options\n } satisfies SchedulerRouteMessage)) as InsertResult<\n SchedulerPayload<Handlers[Name]>\n >)\n : await this.#insert<SchedulerPayload<Handlers[Name]>>(\n null,\n parseInterval(intervalSeconds, Date.now()),\n callback,\n payload,\n options\n );\n this.#emitCreated(result);\n return result.schedule;\n }\n\n /** Get a schedule by ID. Works inside routed sub-agents. */\n async get(id: string): Promise<Schedule<unknown> | undefined> {\n await this.lifecycle.ready();\n return this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"get\",\n id\n } satisfies SchedulerRouteMessage)) as Schedule<unknown> | undefined)\n : this.#getForOwner(null, id);\n }\n\n /** List schedules matching criteria. Works inside routed sub-agents. */\n async list(criteria: ScheduleCriteria = {}): Promise<Schedule<unknown>[]> {\n await this.lifecycle.ready();\n return this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"list\",\n criteria\n } satisfies SchedulerRouteMessage)) as Schedule<unknown>[])\n : this.#listForOwner(null, criteria);\n }\n\n /**\n * Cancel one schedule owned by this Scheduler.\n *\n * @param id - ID of the schedule to cancel.\n * @returns True when a schedule was cancelled, false when none matched.\n */\n async cancel(id: string): Promise<boolean> {\n await this.lifecycle.ready();\n const result = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"cancel\",\n id\n } satisfies SchedulerRouteMessage)) as {\n ok: boolean;\n callback?: string;\n })\n : await this.#cancelForOwner(null, id);\n if (result.ok && result.callback) {\n this.#emit(\"schedule:cancel\", { callback: result.callback, id });\n }\n return result.ok;\n }\n\n // ── Host-owned policy apertures ──────────────────────────────────────────\n\n /**\n * @internal Synchronous read backing Agent's deprecated `getSchedule()`.\n * Not part of the primitive's contract — use {@link get}. Cannot cross\n * Durable Object boundaries and throws inside routed sub-agents.\n */\n __DO_NOT_USE_WILL_REMOVE__getSchedule<T = string>(\n id: string\n ): Schedule<T> | undefined {\n if (this.lifecycle.routes.source) {\n throw new Error(\n \"getSchedule() is synchronous and cannot read routed schedule storage. \" +\n \"Use await getScheduleById(id) on Agent, or await scheduler.get(id) \" +\n \"on a standalone Scheduler.\"\n );\n }\n return this.#getForOwner(null, id);\n }\n\n /**\n * @internal Synchronous read backing Agent's deprecated `getSchedules()`.\n * Not part of the primitive's contract — use {@link list}. Cannot cross\n * Durable Object boundaries and throws inside routed sub-agents.\n */\n __DO_NOT_USE_WILL_REMOVE__getSchedules<T = string>(\n criteria: ScheduleCriteria = {}\n ): Schedule<T>[] {\n if (this.lifecycle.routes.source) {\n throw new Error(\n \"getSchedules() is synchronous and cannot read routed schedule storage. \" +\n \"Use await listSchedules(criteria) on Agent, or await \" +\n \"scheduler.list(criteria) on a standalone Scheduler.\"\n );\n }\n return this.#listForOwner(null, criteria);\n }\n\n /** @internal Remove schedules owned by one routed Lifecycle subtree. */\n async __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(\n prefix: string\n ): Promise<void> {\n for (const { job, timing } of this.#ownedJobs()) {\n const ownerKey = timing.owner_path_key ?? timing.owner_path;\n if (!timing.owner_path || ownerKey === null || ownerKey === undefined) {\n continue;\n }\n if (ownerKey !== prefix && !ownerKey.startsWith(`${prefix}/`)) continue;\n this.#emit(\"schedule:cancel\", { callback: job.fn, id: job.id });\n await this.lifecycle.jobs.cancel(job.id);\n }\n }\n\n // ── Validation ───────────────────────────────────────────────────────────\n\n #validateSchedule(\n when: Date | string | number,\n callback: string,\n options?: ScheduleOptions\n ): void {\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown scheduled callback \"${callback}\": not registered on this Scheduler`\n );\n }\n if (options?.retry) {\n validateRetryOptions(options.retry, this.#retryDefaults);\n }\n if (\n !(when instanceof Date) &&\n typeof when !== \"number\" &&\n typeof when !== \"string\"\n ) {\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n }\n this.#warnWhenScheduledDuringStartup(when, callback, options);\n }\n\n #validateInterval(\n intervalSeconds: number,\n callback: string,\n retry?: RetryOptions\n ): void {\n validateIntervalSeconds(intervalSeconds);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown scheduled callback \"${callback}\": not registered on this Scheduler`\n );\n }\n if (retry) validateRetryOptions(retry, this.#retryDefaults);\n }\n\n /**\n * A non-idempotent one-shot created during startup accumulates one row per\n * Durable Object wake, whether it came from the host's onStart or another\n * startup hook. Warn once per callback; an explicit `idempotent` choice\n * (either value) opts out.\n */\n #warnWhenScheduledDuringStartup(\n when: Date | string | number,\n callback: string,\n options?: ScheduleOptions\n ): void {\n if (!this.lifecycle.starting()) return;\n if (options?.idempotent !== undefined) return;\n if (typeof when === \"string\") return;\n if (this.#warnedStartupCallbacks.has(callback)) return;\n this.#warnedStartupCallbacks.add(callback);\n console.warn(\n `Scheduling \"${callback}\" during startup (e.g. onStart()) without ` +\n `{ idempotent: true } creates a new row on every Durable Object ` +\n `restart, which can cause duplicate executions. Pass ` +\n `{ idempotent: true } to deduplicate, or use an interval schedule ` +\n `for recurring tasks.`\n );\n }\n\n /** Resolve a name to its registered or composition-root-supplied handler. */\n #resolveCallback(name: string): ResolvedSchedulerCallback | undefined {\n const handler = this.#handlers[name];\n if (handler) {\n // SAFETY: registered handlers are constrained with `never` parameters\n // so concrete handler types satisfy the map under contravariance; the\n // payload passed at dispatch was persisted with this handler's name.\n return handler as ResolvedSchedulerCallback;\n }\n return schedulerCallbackResolvers.get(this)?.(name);\n }\n\n /** True when a name resolves to a runnable callback. */\n #hasCallback(name: string): boolean {\n return this.#resolveCallback(name) !== undefined;\n }\n\n // ── Jobs ─────────────────────────────────────────────────────────────────\n\n /** Every schedule job this Scheduler owns, with its parsed vocabulary. */\n #ownedJobs(): Array<{ job: LifecycleJob; timing: SchedulerJobPayload }> {\n const owned: Array<{ job: LifecycleJob; timing: SchedulerJobPayload }> = [];\n for (const job of this.lifecycle.jobs.list()) {\n if (isSchedulerJobPayload(job.payload)) {\n owned.push({ job, timing: job.payload });\n }\n }\n return owned;\n }\n\n /**\n * Push a schedule job for the given owner, or return the existing job\n * when an idempotent request matches one. One-shot timings deduplicate only\n * when `idempotent: true` is passed; recurring timings deduplicate unless\n * `idempotent: false` opts out. `created: false` marks a dedup hit so\n * callers suppress the `schedule:create` event.\n */\n async #insert<T = string>(\n owner: LifecycleRouteAddress | null,\n timing: ScheduleTiming,\n callback: string,\n payload: unknown,\n options?: ScheduleOptions\n ): Promise<InsertResult<T>> {\n // Recurring timings deduplicate unless explicitly opted out; one-shot\n // timings deduplicate on any truthy value (historic Agent behavior).\n const idempotent = isRecurring(timing)\n ? options?.idempotent !== false\n : Boolean(options?.idempotent);\n // Not part of public ScheduleOptions. See RecoveryLoopScheduleOptions.\n const recoveryLoop = (\n options as Partial<RecoveryLoopScheduleOptions> | undefined\n )?.recoveryLoop;\n\n if (idempotent) {\n const existing = this.#findMatchingJob(\n owner?.key ?? null,\n timing,\n callback,\n JSON.stringify(payload)\n );\n if (existing) {\n // A dedup hit onto a row without breaker membership the caller asks\n // for (a row migrated from the legacy schedule table) re-pushes the\n // same durable intent in place with the flag — otherwise the row\n // would escape the alarm memory-limit breaker (#1825) forever.\n if (recoveryLoop && !existing.job.recoveryLoop) {\n await this.lifecycle.jobs.push({\n id: existing.job.id,\n fn: existing.job.fn,\n time: existing.job.time,\n payload: existing.job.payload,\n retry: existing.job.retry,\n singleflight: existing.job.singleflight,\n exclusive: existing.job.exclusive,\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop: true\n });\n }\n // A dedup hit still re-arms so a lost physical alarm recovers, as\n // idempotent re-scheduling on startup historically guaranteed.\n await this.lifecycle.jobs.rearm();\n return {\n schedule: this.#jobToSchedule<T>(existing.job, existing.timing),\n created: false\n };\n }\n }\n\n const jobPayload: SchedulerJobPayload = {\n payload,\n retry: options?.retry,\n type: timing.type,\n delayInSeconds:\n timing.type === \"delayed\" ? timing.delayInSeconds : undefined,\n cron: timing.type === \"cron\" ? timing.cron : undefined,\n intervalSeconds:\n timing.type === \"interval\" ? timing.intervalSeconds : undefined,\n owner_path: owner?.data ?? null,\n owner_path_key: owner?.key ?? null\n };\n const job = await this.lifecycle.jobs.push({\n fn: callback,\n time: timing.time * 1000,\n payload: jobPayload,\n retry: resolveRetryConfig(options?.retry, this.#retryDefaults),\n singleflight: timing.type === \"interval\",\n hungTimeoutSeconds: this.#hungScheduleTimeoutSeconds,\n recoveryLoop\n });\n\n return {\n schedule: {\n id: job.id,\n callback,\n // SAFETY: payload is optional at the call site; historical API shape\n // types an omitted payload as the schedule's payload type.\n payload: payload as T,\n retry: options?.retry,\n ...timing\n },\n created: true\n };\n }\n\n /** Find the job an idempotent insert deduplicates onto, if any. */\n #findMatchingJob(\n ownerKey: string | null,\n timing: ScheduleTiming,\n callback: string,\n payloadJson: string\n ): { job: LifecycleJob; timing: SchedulerJobPayload } | undefined {\n for (const owned of this.#ownedJobs()) {\n const { job, timing: candidate } = owned;\n if (candidate.type !== timing.type) continue;\n if (job.fn !== callback) continue;\n if ((candidate.owner_path_key ?? null) !== ownerKey) continue;\n if (JSON.stringify(candidate.payload) !== payloadJson) continue;\n if (timing.type === \"cron\" && candidate.cron !== timing.cron) continue;\n if (\n timing.type === \"interval\" &&\n candidate.intervalSeconds !== timing.intervalSeconds\n ) {\n continue;\n }\n return owned;\n }\n return undefined;\n }\n\n #jobToSchedule<T>(\n job: LifecycleJob,\n timing: SchedulerJobPayload\n ): Schedule<T> {\n return this.#payloadToSchedule<T>(\n job.id,\n job.fn,\n timing,\n Math.floor(job.time / 1000)\n );\n }\n\n #payloadToSchedule<T>(\n id: string,\n fn: string,\n timing: SchedulerJobPayload,\n timeSeconds?: number\n ): Schedule<T> {\n const base = {\n callback: fn,\n id,\n payload: timing.payload as T,\n retry: timing.retry\n };\n const time = timeSeconds ?? 0;\n switch (timing.type) {\n case \"scheduled\":\n return { ...base, time, type: \"scheduled\" };\n case \"delayed\":\n return {\n ...base,\n delayInSeconds: timing.delayInSeconds ?? 0,\n time,\n type: \"delayed\"\n };\n case \"cron\":\n return { ...base, cron: timing.cron ?? \"\", time, type: \"cron\" };\n case \"interval\":\n return {\n ...base,\n intervalSeconds: timing.intervalSeconds ?? 0,\n time,\n type: \"interval\"\n };\n }\n }\n\n #getForOwner<T = string>(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Schedule<T> | undefined {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isSchedulerJobPayload(job.payload)) return undefined;\n if ((job.payload.owner_path_key ?? null) !== ownerKey) return undefined;\n return this.#jobToSchedule<T>(job, job.payload);\n }\n\n #listForOwner<T = string>(\n owner: LifecycleRouteAddress | null,\n criteria: ScheduleCriteria = {}\n ): Schedule<T>[] {\n const ownerKey = owner?.key ?? null;\n const startSeconds = criteria.timeRange\n ? Math.floor((criteria.timeRange.start ?? new Date(0)).getTime() / 1000)\n : null;\n const endSeconds = criteria.timeRange\n ? Math.floor(\n (criteria.timeRange.end ?? new Date(999999999999999)).getTime() / 1000\n )\n : null;\n\n const schedules: Schedule<T>[] = [];\n for (const { job, timing } of this.#ownedJobs()) {\n if ((timing.owner_path_key ?? null) !== ownerKey) continue;\n if (criteria.id && job.id !== criteria.id) continue;\n if (criteria.type && timing.type !== criteria.type) continue;\n const timeSeconds = Math.floor(job.time / 1000);\n if (startSeconds !== null && timeSeconds < startSeconds) continue;\n if (endSeconds !== null && timeSeconds > endSeconds) continue;\n schedules.push(this.#jobToSchedule<T>(job, timing));\n }\n return schedules;\n }\n\n async #cancelForOwner(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Promise<{ ok: boolean; callback?: string }> {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isSchedulerJobPayload(job.payload)) return { ok: false };\n if ((job.payload.owner_path_key ?? null) !== ownerKey) {\n return { ok: false };\n }\n const callback = job.fn;\n await this.lifecycle.jobs.cancel(id);\n return { ok: true, callback };\n }\n\n // ── Events ───────────────────────────────────────────────────────────────\n\n #emit(type: SchedulerEventType, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n\n #emitCreated(result: InsertResult<unknown>): void {\n if (!result.created) return;\n this.#emit(\"schedule:create\", {\n callback: result.schedule.callback,\n id: result.schedule.id\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,uBAAuB,MAAU,KAAK;;AAoCnD,SAAgB,YAAY,QAAiC;CAC3D,OAAO,OAAO,SAAS,UAAU,OAAO,SAAS;AACnD;;;;;;;;;AAUA,SAAgB,eAAe,MAAc,OAAuB;CAClE,OAAO,oBAAoB,IAAI,CAAC,CAAC,YAAY,IAAI,KAAK,KAAK,CAAC,CAAC,CAAC,QAAQ;AACxE;;;;;;;;;;;;;AAcA,SAAgB,UACd,MACA,OACA,UACgB;CAChB,IAAI,gBAAgB,MAClB,OAAO;EAAE,MAAM;EAAa,MAAM,KAAK,MAAM,KAAK,QAAQ,IAAI,GAAI;CAAE;CAEtE,IAAI,OAAO,SAAS,UAClB,OAAO;EACL,MAAM;EACN,MAAM,KAAK,OAAO,QAAQ,OAAO,OAAQ,GAAI;EAC7C,gBAAgB;CAClB;CAEF,IAAI,OAAO,SAAS,UAClB,OAAO;EACL,MAAM;EACN,MAAM,KAAK,MAAM,eAAe,MAAM,KAAK,IAAI,GAAI;EACnD,MAAM;CACR;CAEF,MAAM,IAAI,MACR,0BAA0B,KAAK,UAAU,IAAI,EAAE,GAAG,OAAO,KAAK,uBAAuB,UACvF;AACF;;;;;;;AAQA,SAAgB,wBAAwB,iBAA+B;CACrE,IAAI,OAAO,oBAAoB,YAAY,mBAAmB,GAC5D,MAAM,IAAI,MAAM,2CAA2C;CAE7D,IAAI,kBAAA,QACF,MAAM,IAAI,MACR,iCAAiC,qBAAqB,mBACxD;AAEJ;;;;;;;;;AAUA,SAAgB,cACd,iBACA,OACgB;CAChB,wBAAwB,eAAe;CACvC,OAAO;EACL,MAAM;EACN,MAAM,KAAK,OAAO,QAAQ,kBAAkB,OAAQ,GAAI;EACxD;CACF;AACF;;;;;;;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