agents 0.26.0 → 0.28.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/README.md +8 -9
- package/dist/abortable-C1SpfVoi.js +21 -0
- package/dist/abortable-C1SpfVoi.js.map +1 -0
- package/dist/{agent-routing-0DR0Tk2v.d.ts → agent-routing-QDcchcQP.d.ts} +16 -16
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-YrATZJu2.d.ts → agent-tools-DHL2XI7u.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/ai-ahruGw7e.d.ts +239 -0
- package/dist/ai-sdk-Bdsf6mSA.js +2444 -0
- package/dist/ai-sdk-Bdsf6mSA.js.map +1 -0
- package/dist/apply-chunks-1FheRb9W.js +99 -0
- package/dist/apply-chunks-1FheRb9W.js.map +1 -0
- package/dist/broadcast-state-CEyI4uAK.js +69 -0
- package/dist/broadcast-state-CEyI4uAK.js.map +1 -0
- package/dist/browser/ai.d.ts +8 -227
- package/dist/browser/ai.js +259 -1
- package/dist/browser/ai.js.map +1 -0
- package/dist/browser/index.d.ts +56 -46
- package/dist/browser/index.js +4 -361
- package/dist/browser/{ai-sdk.d.ts → tools/ai-sdk.d.ts} +7 -7
- package/dist/browser/{ai-sdk.js → tools/ai-sdk.js} +6 -5
- package/dist/browser/tools/ai-sdk.js.map +1 -0
- package/dist/browser/tools/pi.d.ts +111 -0
- package/dist/browser/tools/pi.js +119 -0
- package/dist/browser/tools/pi.js.map +1 -0
- package/dist/browser/{tanstack-ai.d.ts → tools/tanstack-ai.d.ts} +39 -37
- package/dist/browser/{tanstack-ai.js → tools/tanstack-ai.js} +73 -59
- package/dist/browser/tools/tanstack-ai.js.map +1 -0
- package/dist/browser-CEdNlsaD.js +481 -0
- package/dist/browser-CEdNlsaD.js.map +1 -0
- package/dist/{browser-DE3d-RLk.d.ts → browser-D30VlpcA.d.ts} +63 -37
- package/dist/{browser-tool-CQ10e6Kj.js → browser-tool-4iomavs_.js} +198 -62
- package/dist/browser-tool-4iomavs_.js.map +1 -0
- package/dist/{browser-tool-DuNdlwZ9.d.ts → browser-tool-vtrPOV8e.d.ts} +25 -6
- package/dist/{capability-B4WbF81e.js → capability-DBAKc6UZ.js} +1 -3
- package/dist/capability-DBAKc6UZ.js.map +1 -0
- package/dist/{capability-runner-DBAnGr6L.d.ts → capability-runner-BiVUtjqC.d.ts} +9 -7
- package/dist/channel-Bak_6zDP.d.ts +333 -0
- package/dist/chat/index.d.ts +11 -9
- package/dist/chat/index.js +5 -194
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.d.ts +2 -4
- package/dist/chat/react.js +3 -1
- package/dist/chat/react.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +144 -0
- package/dist/{client-je3koD9Z.d.ts → client-BGIQKJhX.d.ts} +2 -2
- package/dist/{client-fyQrLGkD.js → client-BnYbNT3z.js} +29 -5
- package/dist/client-BnYbNT3z.js.map +1 -0
- package/dist/client-tools-aIBO0Fk7.d.ts +53 -0
- package/dist/client.d.ts +1 -1
- package/dist/{connector-58XDGvc3.js → connector-CtZylXdk.js} +3 -603
- package/dist/connector-CtZylXdk.js.map +1 -0
- package/dist/{connector-Cl-VqPmA.d.ts → connector-DEXzVoaY.d.ts} +9 -374
- package/dist/conversations-FjHDRZyD.d.ts +192 -0
- package/dist/{current-agent-vAk_5JMt.d.ts → current-agent-CKgT5d1O.d.ts} +3 -5
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/daemon-core-Buubj-y1.js +481 -0
- package/dist/daemon-core-Buubj-y1.js.map +1 -0
- package/dist/daemon-core-CbohVPAu.d.ts +132 -0
- package/dist/{do-oauth-client-provider-Tmf1vgKz.d.ts → do-oauth-client-provider-DfsUcpc3.d.ts} +7 -1
- package/dist/{durable-object-lifecycle-HhgOMWq9.d.ts → durable-object-lifecycle-DOI_bzCH.d.ts} +2 -2
- package/dist/{channels/email.d.ts → experimental/channels/email/index.d.ts} +25 -12
- package/dist/{channels/email.js → experimental/channels/email/index.js} +13 -35
- package/dist/experimental/channels/email/index.js.map +1 -0
- package/dist/experimental/channels/index.d.ts +270 -0
- package/dist/experimental/channels/index.js +1186 -0
- package/dist/experimental/channels/index.js.map +1 -0
- package/dist/{channels/slack.d.ts → experimental/channels/slack/index.d.ts} +19 -9
- package/dist/experimental/channels/slack/index.js +267 -0
- package/dist/experimental/channels/slack/index.js.map +1 -0
- package/dist/{channels/telegram.d.ts → experimental/channels/telegram/index.d.ts} +19 -9
- package/dist/experimental/channels/telegram/index.js +198 -0
- package/dist/experimental/channels/telegram/index.js.map +1 -0
- package/dist/experimental/channels/web/ai-sdk.d.ts +55 -0
- package/dist/experimental/channels/web/ai-sdk.js +266 -0
- package/dist/experimental/channels/web/ai-sdk.js.map +1 -0
- package/dist/experimental/channels/web/client.d.ts +97 -0
- package/dist/experimental/channels/web/client.js +349 -0
- package/dist/experimental/channels/web/client.js.map +1 -0
- package/dist/experimental/channels/web/index.d.ts +189 -0
- package/dist/experimental/channels/web/index.js +332 -0
- package/dist/experimental/channels/web/index.js.map +1 -0
- package/dist/gateway-BFO6vRDn.d.ts +100 -0
- package/dist/handle-zAzh0UW2.d.ts +460 -0
- package/dist/harness/ai-sdk/index.d.ts +175 -0
- package/dist/harness/ai-sdk/index.js +605 -0
- package/dist/harness/ai-sdk/index.js.map +1 -0
- package/dist/harness/container/daemon/index.d.ts +76 -0
- package/dist/harness/container/daemon/index.js +3 -0
- package/dist/harness/container/index.d.ts +740 -0
- package/dist/harness/container/index.js +2152 -0
- package/dist/harness/container/index.js.map +1 -0
- package/dist/harness/container/runtime/index.d.ts +144 -0
- package/dist/harness/container/runtime/index.js +1082 -0
- package/dist/harness/container/runtime/index.js.map +1 -0
- package/dist/harness/opencode/index.d.ts +369 -0
- package/dist/harness/opencode/index.js +1072 -0
- package/dist/harness/opencode/index.js.map +1 -0
- package/dist/harness/pi/index.d.ts +3 -2
- package/dist/harness/pi/index.js +3 -3
- package/dist/harness/store/index.d.ts +24 -0
- package/dist/harness/store/index.js +2 -0
- package/dist/harness/think/index.d.ts +821 -0
- package/dist/harness/think/index.js +2721 -0
- package/dist/harness/think/index.js.map +1 -0
- package/dist/harness-B6B9S3rb.d.ts +203 -0
- package/dist/{images-iiTDSyRu.js → images-Ce9SCu3X.js} +2 -248
- package/dist/images-Ce9SCu3X.js.map +1 -0
- package/dist/{index-BreL0YrQ.d.ts → index-BEL3ZV-s.d.ts} +2 -6
- package/dist/index-CBt8oRJt.d.ts +198 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/ingress-EFbrS547.js +9 -0
- package/dist/ingress-EFbrS547.js.map +1 -0
- package/dist/input-schema-BQykTEp_.js +20 -0
- package/dist/input-schema-BQykTEp_.js.map +1 -0
- package/dist/input-schema-D2QAtHZH.js +23 -0
- package/dist/input-schema-D2QAtHZH.js.map +1 -0
- package/dist/internal-kmw70xwR.js +46 -0
- package/dist/internal-kmw70xwR.js.map +1 -0
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +2 -2
- package/dist/{lifecycle-CFu6OV03.js → lifecycle-DGorpAmA.js} +2 -4
- package/dist/lifecycle-DGorpAmA.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +9 -0
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +1 -1
- package/dist/mcp/client/index.js +1 -1
- package/dist/mcp/client/x402.d.ts +35 -4
- package/dist/mcp/client/x402.js +24 -3
- package/dist/mcp/client/x402.js.map +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +2 -2
- package/dist/models/ai-sdk/index.d.ts +16 -14
- package/dist/models/ai-sdk/index.js +1 -2442
- package/dist/models/opencode/index.d.ts +65 -0
- package/dist/models/opencode/index.js +285 -0
- package/dist/models/opencode/index.js.map +1 -0
- package/dist/models/pi-ai/index.d.ts +9 -7
- package/dist/models/pi-ai/index.js +2 -1
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/options-CiIsJHXR.d.ts +130 -0
- package/dist/protocol-BEgrJYC5.d.ts +331 -0
- package/dist/protocol-CukuI73M.d.ts +386 -0
- package/dist/protocol-cOklVBBD.js +227 -0
- package/dist/protocol-cOklVBBD.js.map +1 -0
- package/dist/{protocol-kHsr-f0X.js → protocol-eXeJxhgu.js} +2 -67
- package/dist/protocol-eXeJxhgu.js.map +1 -0
- package/dist/protocol-y2sSY584.js +148 -0
- package/dist/protocol-y2sSY584.js.map +1 -0
- package/dist/queue/index.d.ts +1 -1
- package/dist/queue/index.js +1 -1
- package/dist/{queue-BB-zfIYF.js → queue-CcIjVYTE.js} +2 -2
- package/dist/{queue-BB-zfIYF.js.map → queue-CcIjVYTE.js.map} +1 -1
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/routing/index.js +1 -1
- package/dist/{scheduler-RdACNXDP.d.ts → scheduler-BCLESHSC.d.ts} +2 -12
- package/dist/{scheduler-DZ3xQfeK.js → scheduler-FIHv2-kJ.js} +2 -4
- package/dist/scheduler-FIHv2-kJ.js.map +1 -0
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/session-store-Do4xkDcf.js +606 -0
- package/dist/session-store-Do4xkDcf.js.map +1 -0
- package/dist/session-store-DoPY12xM.d.ts +383 -0
- package/dist/sessions/index.d.ts +11 -434
- package/dist/sessions/index.js +1 -2271
- package/dist/sessions-_vN5BEZX.js +2272 -0
- package/dist/sessions-_vN5BEZX.js.map +1 -0
- package/dist/settings-C45hDliX.js +253 -0
- package/dist/settings-C45hDliX.js.map +1 -0
- package/dist/{transport-PfFnt-Ld.d.ts → settings-NgGwF7Qt.d.ts} +14 -208
- package/dist/{src-BZeu-SCD.js → src-CQxJFv4l.js} +8 -8
- package/dist/src-CQxJFv4l.js.map +1 -0
- package/dist/stall-watchdog-BpRF2uwG.js +195 -0
- package/dist/stall-watchdog-BpRF2uwG.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/state/index.js +1 -3
- package/dist/state/index.js.map +1 -1
- package/dist/store-BKM4Xm9M.d.ts +332 -0
- package/dist/store-CslVzfN7.js +458 -0
- package/dist/store-CslVzfN7.js.map +1 -0
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/{streams-DW-UCOUc.js → streams-lsHMJhRW.js} +17 -4
- package/dist/streams-lsHMJhRW.js.map +1 -0
- package/dist/{streams-Cmkj9QfW.d.ts → streams-vrCtbUIn.d.ts} +2 -2
- package/dist/sub-routing.d.ts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-68DESxf0.js → tasks-BN_5AWqI.js} +3 -2
- package/dist/tasks-BN_5AWqI.js.map +1 -0
- package/dist/{tasks-9YxYtByh.d.ts → tasks-E89KdwkS.d.ts} +2 -2
- package/dist/tool-CTp72Jb_.d.ts +278 -0
- package/dist/tool-CxKsvxjm.js +1126 -0
- package/dist/tool-CxKsvxjm.js.map +1 -0
- package/dist/tool-DoVberpN.d.ts +301 -0
- package/dist/tool-cQRkwSZZ.js +410 -0
- package/dist/tool-cQRkwSZZ.js.map +1 -0
- package/dist/tool-helpers-O5BDVEAY.js +58 -0
- package/dist/tool-helpers-O5BDVEAY.js.map +1 -0
- package/dist/transport-k2mFrtL8.d.ts +200 -0
- package/dist/turns-DCV3ycDl.js +317 -0
- package/dist/turns-DCV3ycDl.js.map +1 -0
- package/dist/voice/client.js +1 -1
- package/dist/voice/index.d.ts +2 -2
- package/dist/voice/index.js +1 -1
- package/dist/web/fetch/index.d.ts +89 -0
- package/dist/web/fetch/index.js +20 -0
- package/dist/web/fetch/index.js.map +1 -0
- package/dist/web/fetch/tools/ai-sdk.d.ts +80 -0
- package/dist/web/fetch/tools/ai-sdk.js +47 -0
- package/dist/web/fetch/tools/ai-sdk.js.map +1 -0
- package/dist/web/fetch/tools/pi.d.ts +84 -0
- package/dist/web/fetch/tools/pi.js +88 -0
- package/dist/web/fetch/tools/pi.js.map +1 -0
- package/dist/web/fetch/tools/tanstack-ai.d.ts +78 -0
- package/dist/web/fetch/tools/tanstack-ai.js +45 -0
- package/dist/web/fetch/tools/tanstack-ai.js.map +1 -0
- package/dist/web/search/index.d.ts +58 -0
- package/dist/web/search/index.js +2 -0
- package/dist/web/search/tools/ai-sdk.d.ts +77 -0
- package/dist/web/search/tools/ai-sdk.js +46 -0
- package/dist/web/search/tools/ai-sdk.js.map +1 -0
- package/dist/web/search/tools/pi.d.ts +82 -0
- package/dist/web/search/tools/pi.js +89 -0
- package/dist/web/search/tools/pi.js.map +1 -0
- package/dist/web/search/tools/tanstack-ai.d.ts +71 -0
- package/dist/web/search/tools/tanstack-ai.js +46 -0
- package/dist/web/search/tools/tanstack-ai.js.map +1 -0
- package/dist/websockets/index.d.ts +12 -296
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-Ci-LZFHH.js → websockets-C3zy8YR0.js} +20 -8
- package/dist/websockets-C3zy8YR0.js.map +1 -0
- package/dist/{wire-types-CrjKvDyi.d.ts → wire-types-Cv0iwjk5.d.ts} +3 -51
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/workflows.js +1 -1
- package/docs/browse-the-web.md +29 -1
- package/docs/fetch-the-web.md +276 -0
- package/docs/harnesses/pi.md +25 -0
- package/docs/harnesses/think.md +215 -0
- package/docs/index.md +99 -75
- package/docs/lifecycle.md +42 -3
- package/docs/queue.md +2 -3
- package/docs/scheduling.md +2 -6
- package/docs/search-the-web.md +135 -0
- package/package.json +148 -44
- package/dist/ai-fm7xx1BK.js +0 -312
- package/dist/ai-fm7xx1BK.js.map +0 -1
- package/dist/browser/ai-sdk.js.map +0 -1
- package/dist/browser/index.js.map +0 -1
- package/dist/browser/tanstack-ai.js.map +0 -1
- package/dist/browser-tool-CQ10e6Kj.js.map +0 -1
- package/dist/capability-B4WbF81e.js.map +0 -1
- package/dist/channel-Bnm4S7T2.d.ts +0 -491
- package/dist/channels/ai-sdk.d.ts +0 -46
- package/dist/channels/ai-sdk.js +0 -120
- package/dist/channels/ai-sdk.js.map +0 -1
- package/dist/channels/email.js.map +0 -1
- package/dist/channels/index.d.ts +0 -233
- package/dist/channels/index.js +0 -608
- package/dist/channels/index.js.map +0 -1
- package/dist/channels/slack.js +0 -614
- package/dist/channels/slack.js.map +0 -1
- package/dist/channels/tanstack-ai.d.ts +0 -39
- package/dist/channels/tanstack-ai.js +0 -17
- package/dist/channels/tanstack-ai.js.map +0 -1
- package/dist/channels/telegram.js +0 -427
- package/dist/channels/telegram.js.map +0 -1
- package/dist/channels/voice.d.ts +0 -45
- package/dist/channels/voice.js +0 -122
- package/dist/channels/voice.js.map +0 -1
- package/dist/client-fyQrLGkD.js.map +0 -1
- package/dist/connector-58XDGvc3.js.map +0 -1
- package/dist/images-iiTDSyRu.js.map +0 -1
- package/dist/index-BB0kqhIz.d.ts +0 -101
- package/dist/ingress-BfetZbMO.js +0 -83
- package/dist/ingress-BfetZbMO.js.map +0 -1
- package/dist/internal-CYlgHl1l.js +0 -59
- package/dist/internal-CYlgHl1l.js.map +0 -1
- package/dist/lifecycle-CFu6OV03.js.map +0 -1
- package/dist/models/ai-sdk/index.js.map +0 -1
- package/dist/protocol-kHsr-f0X.js.map +0 -1
- package/dist/scheduler-DZ3xQfeK.js.map +0 -1
- package/dist/sessions/index.js.map +0 -1
- package/dist/src-BZeu-SCD.js.map +0 -1
- package/dist/streams-DW-UCOUc.js.map +0 -1
- package/dist/surface-bZZJqBka.js +0 -17
- package/dist/surface-bZZJqBka.js.map +0 -1
- package/dist/tasks-68DESxf0.js.map +0 -1
- package/dist/tool-schema-CBjGPrsQ.js +0 -31
- package/dist/tool-schema-CBjGPrsQ.js.map +0 -1
- package/dist/websockets-Ci-LZFHH.js.map +0 -1
- package/docs/channels.md +0 -323
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"streams-lsHMJhRW.js","names":[],"sources":["../src/streams/errors.ts","../src/streams/streams.ts"],"sourcesContent":["/**\n * Error classes for the Streams capability. Each carries a stable `name` so\n * hosts and tests can classify failures without depending on message text.\n */\n\n/**\n * Thrown when `open()` targets a terminal stream, or an append reaches a\n * stream that settled (or was deleted) after the writer was created.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class StreamClosedError extends Error {\n /** The stream that no longer accepts writes. */\n readonly streamId: string;\n\n constructor(streamId: string, detail: string) {\n super(`Stream \"${streamId}\" is closed: ${detail}`);\n this.name = \"StreamClosedError\";\n this.streamId = streamId;\n }\n}\n\n/**\n * Thrown when `read()` targets a stream that was never opened (or was\n * deleted). `status()` returns `null` instead, for existence probes.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class StreamNotFoundError extends Error {\n readonly streamId: string;\n\n constructor(streamId: string) {\n super(\n `Stream \"${streamId}\" does not exist. Open it before reading, or use ` +\n `status() to probe for existence.`\n );\n this.name = \"StreamNotFoundError\";\n this.streamId = streamId;\n }\n}\n\n/**\n * Thrown when a chunk or metadata value is not JSON-serializable or exceeds\n * the configured size limit.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class StreamSerializationError extends Error {\n constructor(context: string, detail: string) {\n super(`Cannot serialize ${context}: ${detail}`);\n this.name = \"StreamSerializationError\";\n }\n}\n","/**\n * Durable incremental output for Lifecycle Objects. `Streams` owns the\n * `cf_agents_streams` and `cf_agents_stream_blocks` tables: an ordered,\n * durable chunk log per stream with a monotonic cursor, replay-then-tail\n * reads, and terminal status that doubles as recovery evidence for the\n * Tasks capability (which composes through checkpointed cursors, never\n * imports).\n *\n * Streams consumes only the standard capability services — storage and\n * events. It needs no alarm, so it also works on facets. Live fanout is\n * in-isolate: a Durable Object executes in one isolate at a time, so every\n * concurrent reader shares the producer's isolate; readers that outlive an\n * isolate replay from their cursor on reconnect.\n */\n\nimport { LifecycleCapability } from \"../lifecycle/capability\";\nimport { SqlError } from \"../sql-error\";\nimport {\n StreamClosedError,\n StreamNotFoundError,\n StreamSerializationError\n} from \"./errors\";\nimport type {\n StreamChunk,\n StreamChunkRow,\n StreamJson,\n StreamListOptions,\n StreamOpenOptions,\n StreamReadBatchesOptions,\n StreamReadOptions,\n StreamRow,\n StreamSettleOptions,\n StreamState,\n StreamStatus,\n StreamWriter\n} from \"./types\";\n\nconst STREAM_SCHEMA_VERSION_KEY = \"cf_agents:streams_schema_version\";\nconst CURRENT_STREAM_SCHEMA_VERSION = 2;\n\n/**\n * A block row grows by UPDATE until its body reaches this many characters,\n * then the next append opens a new block. Sized well under the 2 MiB row\n * limit so a 1 MiB chunk always fits in a fresh block, and small enough\n * that a replay page parses one block at a time.\n */\nconst BLOCK_MAX_CHARS = 256 * 1024;\n/** Rows read per page while folding one stream's v1 chunk rows into blocks. */\nconst LEGACY_FOLD_PAGE_ROWS = 500;\n\n/** Default ceiling for one serialized chunk (1 MiB). */\nexport const DEFAULT_MAX_CHUNK_BYTES = 1_048_576;\n\nconst MAX_STREAM_ID_LENGTH = 256;\nconst READ_BATCH_SIZE = 100;\nconst DEFAULT_LIST_LIMIT = 100;\n\nconst utf8 = new TextEncoder();\n\n/**\n * Policy for a Streams capability.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport interface StreamsOptions {\n /** Ceiling for one serialized chunk. Default: 1 MiB. */\n readonly maxChunkBytes?: number;\n}\n\n/**\n * @internal Synchronous operations returned by\n * {@link Streams.__DO_NOT_USE_WILL_BREAK__sync}. For same-isolate first-party\n * machinery only (the chat `ResumableStream` adapter); every method bypasses\n * `lifecycle.ready()`, so the caller owns startup ordering.\n */\nexport interface StreamsSyncInternal {\n /** Idempotent DDL — safe to call before the Lifecycle starts. */\n ensureTables(): void;\n getStream(streamId: string): StreamRow | undefined;\n /** Insert a live stream row (no idempotency — caller checks first). */\n insertStream(\n streamId: string,\n tag: string | null,\n metadata: Record<string, StreamJson> | undefined\n ): void;\n /** Replace a stream row's metadata, whatever its state. */\n setMetadata(streamId: string, metadata: Record<string, StreamJson>): void;\n /** The read-fenced append: one chunk insert at the log tail, reader wakeup. */\n append(streamId: string, chunk: StreamJson): number;\n /**\n * The newest chunk's timestamp, or null for an empty log. One PK-served\n * read — the per-append liveness signal retention sweeps verify against\n * (a live row's `updated_at` is set at open and not bumped by appends).\n */\n lastChunkAt(streamId: string): number | null;\n /**\n * Segments durably appended so far: the chunk log's tail, read in the\n * calling synchronous block. Zero for an unknown stream.\n */\n cursor(streamId: string): number;\n /**\n * Observe every deletion of a stream's rows — the public `delete()`, the\n * aperture's own deletes, and a cutover's discard — with the row and its\n * cursor as they were just before removal, in the same synchronous block\n * (and, for a cutover, the same transaction). Hooks must be synchronous\n * and must not await: the cutover runs them inside `transactionSync`.\n * The chat adapter uses this to keep its recovery progress marker exact\n * however a chat row leaves the table. Returns the unsubscribe: an owner\n * constructed again (a host whose startup retried) must drop its earlier\n * hook, or a deletion is observed once per construction.\n */\n onDelete(hook: (row: StreamRow, cursor: number) => void): () => void;\n /**\n * Idempotent settlement with events and reader wakeup. With `options`,\n * the settle, the caller's `commit` writes and the log discard run in\n * one SQLite transaction (see {@link StreamSettleOptions}). Returns\n * whether the stream transitioned; on a repeat or a deleted stream the\n * `commit` callback does not run.\n */\n settle(\n streamId: string,\n state: \"completed\" | \"errored\",\n reason: string | null,\n options?: StreamSettleOptions\n ): boolean;\n /** Delete a stream and its chunks regardless of state. */\n deleteUnchecked(streamId: string): void;\n /** Delete many streams and their chunks regardless of state, silently. */\n deleteMany(streamIds: string[]): void;\n /**\n * One page of a stream's chunk log from `fromSeq` (inclusive), ordered by\n * seq. Paged rather than read-it-all so replaying a large stream holds\n * one page of segment bodies in memory, not the whole turn.\n */\n readChunks(\n streamId: string,\n fromSeq: number,\n limit: number\n ): StreamChunkRow[];\n /** Every stream row, newest first (created_at, then insertion order). */\n listRows(): StreamRow[];\n /**\n * Every row carrying a tag, newest first, optionally narrowed to one\n * state. Tags are non-unique and the table is shared across producers,\n * so callers apply their own ownership filter (e.g. chat's metadata\n * marker) rather than trusting the newest row.\n */\n rowsByTag(tag: string, state?: StreamState): StreamRow[];\n /**\n * Import one historical stream row verbatim (migrations, test seeding):\n * explicit timestamps and count, no events, no wakeups.\n */\n importStream(row: {\n streamId: string;\n state: StreamState;\n tag: string | null;\n metadata: Record<string, StreamJson> | undefined;\n chunkCount: number;\n createdAt: number;\n updatedAt: number;\n closedAt: number | null;\n }): void;\n /**\n * Import one historical chunk at the log's tail: one INSERT, nothing else.\n * The stream row is not touched — importers pass the final `chunkCount`\n * and `updatedAt` to {@link importStream}, so the row is exact at rest\n * without a per-chunk row write.\n */\n importChunk(streamId: string, chunk: StreamJson, createdAt: number): void;\n}\n\n/**\n * Durable incremental output for a Lifecycle Object.\n *\n * `open()` a stream, `append()` chunks (synchronous durable writes that wake\n * live readers), and settle it with `close()` or `error()`. `read()` replays\n * persisted chunks from a cursor and then tails live appends; `status()`\n * reports the state and cursor — the recovery evidence a Task's `recover`\n * callback consults after its producer was interrupted.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Streams extends LifecycleCapability {\n readonly #maxChunkBytes: number;\n /** Wakeup callbacks for readers tailing a live stream, per stream. */\n readonly #wakeups = new Map<string, Set<() => void>>();\n /**\n * Whether the schema v1 `cf_agents_stream_chunks` table still exists.\n * Its rows are folded into blocks one stream at a time, on first touch\n * (see {@link #foldLegacyChunks}); the table is dropped once empty.\n */\n #legacyChunkTable = false;\n\n constructor(options: StreamsOptions = {}) {\n super(\"streams\");\n this.#maxChunkBytes = options.maxChunkBytes ?? DEFAULT_MAX_CHUNK_BYTES;\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate stream storage during Lifecycle startup. */\n async onStart(): Promise<void> {\n const storage = this.lifecycle.storage;\n const version = (await storage.get<number>(STREAM_SCHEMA_VERSION_KEY)) ?? 0;\n if (version < CURRENT_STREAM_SCHEMA_VERSION) {\n this.#ensureTables();\n await storage.put(\n STREAM_SCHEMA_VERSION_KEY,\n CURRENT_STREAM_SCHEMA_VERSION\n );\n }\n if (version >= 1) this.#legacyChunkTable = this.#hasLegacyChunkTable();\n }\n\n // ── Producer surface ─────────────────────────────────────────────────────\n\n /**\n * Open a stream for writing. Idempotent on the id: reopening a live stream\n * returns a writer positioned at its current cursor; reopening a terminal\n * stream throws {@link StreamClosedError}.\n */\n async open(\n streamId: string,\n options: StreamOpenOptions = {}\n ): Promise<StreamWriter> {\n await this.lifecycle.ready();\n this.#validateStreamId(streamId);\n\n const existing = this.#getStream(streamId);\n if (existing) {\n if (existing.state !== \"streaming\") {\n throw new StreamClosedError(\n streamId,\n `already settled as ${existing.state}`\n );\n }\n // The tag is part of the stream's identity, fixed at creation: a\n // reopen naming a different tag is a config conflict, not a resume.\n if (\n options.tag !== undefined &&\n options.tag !== (existing.tag ?? undefined)\n ) {\n throw new Error(\n `Stream \"${streamId}\" is already open with tag ${JSON.stringify(existing.tag)}; refusing reopen with tag ${JSON.stringify(options.tag)}`\n );\n }\n return this.#writer(streamId);\n }\n\n const metadataJson = this.#serialize(\n options.metadata,\n `metadata for stream \"${streamId}\"`\n );\n const now = Date.now();\n this.#sql`\n INSERT INTO cf_agents_streams\n (stream_id, state, tag, metadata, chunk_count, created_at, updated_at)\n VALUES\n (${streamId}, 'streaming', ${options.tag ?? null}, ${metadataJson}, 0, ${now}, ${now})\n `;\n this.#emit(\"stream:opened\", { streamId });\n return this.#writer(streamId);\n }\n\n // ── Consumer surface ─────────────────────────────────────────────────────\n\n /**\n * Replay persisted chunks from `from` (inclusive), then tail live appends\n * until the stream settles. Ends when the stream reaches a terminal state\n * and every durable chunk has been yielded; a read of an `errored` stream\n * still yields its chunks and then simply ends — consult {@link status}\n * for the terminal outcome. Aborting `options.signal` throws its reason.\n */\n async *read(\n streamId: string,\n options: StreamReadOptions = {}\n ): AsyncGenerator<StreamChunk, void, undefined> {\n const signal = options.signal;\n for await (const batch of this.readBatches(streamId, options)) {\n for (const item of batch) {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Read aborted\");\n yield item;\n }\n }\n }\n\n /**\n * Batched form of {@link read}: yields non-empty arrays of consecutive\n * chunks instead of one chunk at a time. Replay yields up to\n * `options.batchSize` chunks per array; a live tail yields everything\n * that accumulated since the last wakeup as one array — so a consumer\n * paying per write (an SSE flush, an RPC hop, a history append) pays\n * once per backlog, not once per chunk. Same lifecycle as {@link read}:\n * ends when the stream settles and every durable chunk has been\n * yielded; aborting `options.signal` throws its reason.\n */\n async *readBatches(\n streamId: string,\n options: StreamReadBatchesOptions = {}\n ): AsyncGenerator<StreamChunk[], void, undefined> {\n await this.lifecycle.ready();\n const signal = options.signal;\n const batchSize = Math.max(\n 1,\n Math.floor(options.batchSize ?? READ_BATCH_SIZE)\n );\n let next = Math.max(0, options.from ?? 0);\n let signaledUpToDate = false;\n\n if (this.#state(streamId) === undefined) {\n throw new StreamNotFoundError(streamId);\n }\n\n for (;;) {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Read aborted\");\n\n const rows = this.#readChunks(streamId, next, batchSize);\n if (rows.length > 0) {\n next = rows[rows.length - 1].seq + 1;\n yield rows.map((row) => ({\n seq: row.seq,\n chunk: JSON.parse(row.chunk) as StreamJson\n }));\n }\n if (rows.length === batchSize) continue;\n\n // A short batch means every durable chunk up to this instant has been\n // yielded — the reader has reached the tail (caught up ≠ ended: a live\n // stream keeps tailing from here).\n if (!signaledUpToDate) {\n signaledUpToDate = true;\n options.onUpToDate?.();\n // The callback is application code and can synchronously append to\n // this same stream — a wake that would fire before any waiter is\n // registered. Re-poll instead of sleeping so that append is never a\n // lost wakeup; everything from the next query to waiter\n // registration is synchronous, so no other append can slip past.\n continue;\n }\n\n const state = this.#state(streamId);\n if (state === undefined) return; // deleted mid-read: nothing further\n if (state !== \"streaming\") {\n // Terminal. Appends happen-before settlement (the append fence\n // rejects a settled stream), so a poll that returned zero rows in\n // this same synchronous block proves every durable chunk has been\n // yielded; a non-empty short batch yielded (a suspension point),\n // so re-poll to drain the remainder first.\n if (rows.length === 0) return;\n continue;\n }\n\n // The yield above was a suspension point: appends made while the\n // consumer held the batch woke no waiter, so re-poll before sleeping.\n if (rows.length > 0) continue;\n\n // Live tail: wait for the next append or settlement, then re-poll.\n // Wakeups carry no data, so there is nothing to buffer or dedupe.\n await this.#waitForWakeup(streamId, signal);\n }\n }\n\n /** Read one stream's state and cursor, or null when it does not exist. */\n async status(streamId: string): Promise<StreamStatus | null> {\n await this.lifecycle.ready();\n const row = this.#getStream(streamId);\n return row ? this.#rowToStatus(row) : null;\n }\n\n /** List streams, newest first. */\n async list(options: StreamListOptions = {}): Promise<StreamStatus[]> {\n await this.lifecycle.ready();\n const states = Array.isArray(options.state)\n ? options.state\n : options.state !== undefined\n ? [options.state]\n : [];\n let query = \"SELECT * FROM cf_agents_streams WHERE 1 = 1\";\n const params: (string | number)[] = [];\n if (states.length > 0) {\n query += ` AND state IN (${states.map(() => \"?\").join(\", \")})`;\n params.push(...states);\n }\n if (options.tag !== undefined) {\n query += \" AND tag = ?\";\n params.push(options.tag);\n }\n query += \" ORDER BY created_at DESC, stream_id DESC LIMIT ?\";\n params.push(options.limit ?? DEFAULT_LIST_LIMIT);\n let rows: unknown[];\n try {\n rows = this.lifecycle.storage.sql.exec(query, ...params).toArray();\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n // SAFETY: the query selects * from Streams' own schema.\n return (rows as StreamRow[]).map((row) => this.#rowToStatus(row));\n }\n\n /**\n * Delete one terminal stream and its chunk log.\n *\n * @returns True when a terminal stream was deleted; false when none\n * exists. Throws on a live stream — settle it first.\n */\n async delete(streamId: string): Promise<boolean> {\n await this.lifecycle.ready();\n const row = this.#getStream(streamId);\n if (!row) return false;\n if (row.state === \"streaming\") {\n throw new Error(\n `Cannot delete live stream \"${streamId}\"; close() or error() it first`\n );\n }\n this.#deleteRows(streamId);\n this.#emit(\"stream:deleted\", { streamId });\n return true;\n }\n\n // ── Internal sync aperture ───────────────────────────────────────────────\n\n /**\n * @internal Synchronous storage operations for same-isolate first-party\n * machinery — today the chat `ResumableStream` adapter, whose whole public\n * surface is synchronous and constructed before the Lifecycle starts.\n * Bypasses `lifecycle.ready()`: the caller owns startup ordering. The\n * invariant-bearing writes (append fence, settlement, wakeups, events) go\n * through the same private methods as the public API, so live readers and\n * diagnostics observe aperture writes exactly like capability writes. Will\n * break without notice; never use from application code.\n */\n __DO_NOT_USE_WILL_BREAK__sync(): StreamsSyncInternal {\n return {\n ensureTables: () => this.#ensureTables(),\n getStream: (streamId) => this.#getStream(streamId),\n insertStream: (streamId, tag, metadata) => {\n this.#validateStreamId(streamId);\n const metadataJson = this.#serialize(\n metadata,\n `metadata for stream \"${streamId}\"`\n );\n const now = Date.now();\n this.#sql`\n INSERT INTO cf_agents_streams\n (stream_id, state, tag, metadata, chunk_count, created_at, updated_at)\n VALUES\n (${streamId}, 'streaming', ${tag}, ${metadataJson}, 0, ${now}, ${now})\n `;\n this.#emit(\"stream:opened\", { streamId });\n },\n setMetadata: (streamId, metadata) => {\n const metadataJson = this.#serialize(\n metadata,\n `metadata for stream \"${streamId}\"`\n );\n this.#sql`\n UPDATE cf_agents_streams SET metadata = ${metadataJson}\n WHERE stream_id = ${streamId}\n `;\n },\n append: (streamId, chunk) => this.#append(streamId, chunk),\n lastChunkAt: (streamId) => this.#tail(streamId).lastChunkAt,\n cursor: (streamId) => this.#tail(streamId).nextSeq,\n onDelete: (hook) => {\n this.#deleteHooks.push(hook);\n return () => {\n const index = this.#deleteHooks.indexOf(hook);\n if (index !== -1) this.#deleteHooks.splice(index, 1);\n };\n },\n settle: (streamId, state, reason, options) =>\n this.#settle(streamId, state, reason, options),\n deleteUnchecked: (streamId) => {\n const removed = this.#deleteRows(streamId);\n if (removed > 0) this.#emit(\"stream:deleted\", { streamId });\n // Unchecked deletes can remove a live stream: wake tailing readers\n // so they observe the deletion instead of pending forever.\n this.#wake(streamId);\n },\n deleteMany: (streamIds) => {\n for (const streamId of streamIds) {\n this.#deleteRows(streamId);\n this.#wake(streamId);\n }\n },\n readChunks: (streamId, fromSeq, limit) =>\n this.#readChunks(streamId, fromSeq, limit),\n listRows: () => this.#sql<StreamRow>`\n SELECT * FROM cf_agents_streams ORDER BY created_at DESC, rowid DESC\n `,\n rowsByTag: (tag, state) =>\n state\n ? this.#sql<StreamRow>`\n SELECT * FROM cf_agents_streams\n WHERE tag = ${tag} AND state = ${state}\n ORDER BY created_at DESC, rowid DESC\n `\n : this.#sql<StreamRow>`\n SELECT * FROM cf_agents_streams\n WHERE tag = ${tag}\n ORDER BY created_at DESC, rowid DESC\n `,\n importStream: (row) => {\n this.#validateStreamId(row.streamId);\n const metadataJson = this.#serialize(\n row.metadata,\n `metadata for stream \"${row.streamId}\"`\n );\n this.#sql`\n INSERT INTO cf_agents_streams\n (stream_id, state, tag, metadata, chunk_count,\n created_at, updated_at, closed_at)\n VALUES\n (${row.streamId}, ${row.state}, ${row.tag}, ${metadataJson},\n ${row.chunkCount}, ${row.createdAt}, ${row.updatedAt},\n ${row.closedAt})\n `;\n },\n importChunk: (streamId, chunk, createdAt) => {\n const chunkJson = this.#serialize(\n chunk,\n `chunk for stream \"${streamId}\"`\n );\n if (chunkJson === null) return;\n this.#writeChunk(streamId, chunkJson, createdAt);\n }\n };\n }\n\n // ── Writer ───────────────────────────────────────────────────────────────\n\n #writer(streamId: string): StreamWriter {\n const capability = this;\n return {\n streamId,\n get cursor(): number {\n return capability.#tail(streamId).nextSeq;\n },\n append: (chunk) => this.#append(streamId, chunk),\n close: (options) => this.#settle(streamId, \"completed\", null, options),\n error: (reason, options) =>\n this.#settle(streamId, \"errored\", reason ?? null, options)\n };\n }\n\n #append(streamId: string, chunk: StreamJson): number {\n // Serialization runs BEFORE the fence read: JSON.stringify can execute\n // user toJSON() methods, which may synchronously re-enter this stream.\n const chunkJson = this.#serialize(chunk, `chunk for stream \"${streamId}\"`);\n if (chunkJson === null) {\n throw new StreamSerializationError(\n `chunk for stream \"${streamId}\"`,\n \"chunks must not be undefined\"\n );\n }\n // The fence is a read, and its atomicity lives in the isolate's\n // threading model: a Durable Object executes one synchronous block at\n // a time, so the state check, tail read, and block write below cannot\n // interleave with a settle, delete, or another append. Nothing between\n // here and the write may await or call user code — either would\n // reintroduce the lost-update races the old guarded-UPDATE fence\n // prevented, at the cost of one stream-row write per append.\n const state = this.#state(streamId);\n if (state !== \"streaming\") {\n throw new StreamClosedError(\n streamId,\n state !== undefined ? `already settled as ${state}` : \"it was deleted\"\n );\n }\n const seq = this.#writeChunk(streamId, chunkJson, Date.now());\n this.#wake(streamId);\n return seq;\n }\n\n /**\n * Append one serialized chunk to the stream's open block, or open a new\n * block when the current one is full. Either way it is one billed row:\n * an UPDATE that grows the block body, or the INSERT of the next block.\n * Blocks are what make cleanup cheap — a stream of thousands of chunks\n * is a handful of rows to delete at cutover, not thousands.\n */\n #writeChunk(streamId: string, chunkJson: string, at: number): number {\n const tail = this.#blockTail(streamId);\n const seq = tail?.seq_to ?? 0;\n if (tail && tail.len + chunkJson.length + 1 <= BLOCK_MAX_CHARS) {\n this.#sql`\n UPDATE cf_agents_stream_blocks\n SET body = body || ',' || ${chunkJson}, seq_to = ${seq + 1}, updated_at = ${at}\n WHERE stream_id = ${streamId} AND block = ${tail.block}\n `;\n } else {\n this.#sql`\n INSERT INTO cf_agents_stream_blocks\n (stream_id, block, seq_from, seq_to, body, created_at, updated_at)\n VALUES\n (${streamId}, ${(tail?.block ?? -1) + 1}, ${seq}, ${seq + 1}, ${chunkJson}, ${at}, ${at})\n `;\n }\n return seq;\n }\n\n /**\n * One page of chunks from `fromSeq`, in seq order, parsing one block at\n * a time. A block body is the chunks' JSON texts joined by commas, so\n * `[${body}]` parses straight back into the chunk values.\n */\n #readChunks(\n streamId: string,\n fromSeq: number,\n limit: number\n ): StreamChunkRow[] {\n this.#foldLegacyChunks(streamId);\n const rows: StreamChunkRow[] = [];\n let block = -1;\n while (rows.length < limit) {\n const next = this.#sql<{\n block: number;\n seq_from: number;\n seq_to: number;\n body: string;\n updated_at: number;\n }>`\n SELECT block, seq_from, seq_to, body, updated_at\n FROM cf_agents_stream_blocks\n WHERE stream_id = ${streamId} AND block > ${block} AND seq_to > ${fromSeq}\n ORDER BY block ASC\n LIMIT 1\n `[0];\n if (!next) break;\n block = next.block;\n const chunks = JSON.parse(`[${next.body}]`) as StreamJson[];\n for (\n let seq = Math.max(fromSeq, next.seq_from);\n seq < next.seq_to && rows.length < limit;\n seq++\n ) {\n rows.push({\n stream_id: streamId,\n seq,\n chunk: JSON.stringify(chunks[seq - next.seq_from]),\n created_at: next.updated_at\n });\n }\n }\n return rows;\n }\n\n /** Delete a stream's blocks and row. Returns rows removed from the row table. */\n readonly #deleteHooks: Array<(row: StreamRow, cursor: number) => void> = [];\n\n /**\n * Remove a stream's row and log. Deletion hooks see the row and its\n * cursor first, so an owner can account for the segments before they are\n * gone; this is the single point every delete path passes through.\n */\n #deleteRows(streamId: string): number {\n if (this.#deleteHooks.length > 0) {\n const row = this.#getStream(streamId);\n if (row) {\n const cursor = this.#tail(streamId).nextSeq;\n for (const hook of this.#deleteHooks) hook(row, cursor);\n }\n }\n if (this.#legacyTableLive()) {\n // Unfolded v1 rows die with the stream; no point folding them first.\n this.#sql`DELETE FROM cf_agents_stream_chunks WHERE stream_id = ${streamId}`;\n this.#dropLegacyChunkTableIfEmpty();\n }\n this.#sql`DELETE FROM cf_agents_stream_blocks WHERE stream_id = ${streamId}`;\n return this.#sqlWrite(\"DELETE FROM cf_agents_streams WHERE stream_id = ?\", [\n streamId\n ]);\n }\n\n /**\n * @returns Whether this call transitioned the stream (a repeat, or a\n * deleted stream, is a no-op and returns false: the caller's `commit`\n * does not run and nothing is discarded).\n */\n #settle(\n streamId: string,\n state: Extract<StreamState, \"completed\" | \"errored\">,\n reason: string | null,\n options?: StreamSettleOptions\n ): boolean {\n if (!options?.commit && !options?.discard) {\n const settled = this.#settleRow(streamId, state, reason);\n if (settled) this.#emitSettled(streamId, state, reason);\n // Idempotent for recovery callers; readers re-poll and observe the\n // terminal state either way.\n this.#wake(streamId);\n return settled;\n }\n // The cutover: settle, the caller's writes (a session message), and\n // the discard of this stream's rows commit together or not at all. A\n // throwing `commit` rolls everything back and leaves the stream live.\n // Events and wakeups are side effects outside SQLite, so they fire only\n // once the transaction has returned.\n let settled = false;\n let deleted = false;\n const hadLegacy = this.#legacyChunkTable;\n try {\n this.lifecycle.storage.transactionSync(() => {\n settled = this.#settleRow(streamId, state, reason);\n if (!settled) return;\n options.commit?.();\n if (options.discard) deleted = this.#deleteRows(streamId) > 0;\n });\n } finally {\n // The settle's tail read may have folded this stream's v1 rows and,\n // if they were the last, dropped the legacy table and cleared the\n // flag — inside the transaction. A rollback restores the table but\n // not the flag, so re-derive it from the schema rather than trust a\n // bit written by a transaction that may not have committed.\n if (hadLegacy && !this.#legacyChunkTable) {\n this.#legacyChunkTable = this.#hasLegacyChunkTable();\n }\n }\n if (settled) this.#emitSettled(streamId, state, reason);\n if (deleted) this.#emit(\"stream:deleted\", { streamId });\n this.#wake(streamId);\n return settled;\n }\n\n /**\n * The one guarded UPDATE that ends a stream. Settlement is the moment\n * the stream row becomes exact at rest: the same write stamps the final\n * cursor, read from the chunk log's tail in the same synchronous block.\n * While the stream was live, appends wrote only the chunk log — the\n * row's chunk_count and updated_at were not maintained per append.\n * @returns Whether the row transitioned from `streaming`.\n */\n #settleRow(\n streamId: string,\n state: Extract<StreamState, \"completed\" | \"errored\">,\n reason: string | null\n ): boolean {\n const finalCursor = this.#tail(streamId).nextSeq;\n const settled = this.#sqlWrite(\n `UPDATE cf_agents_streams\n SET state = ?, error_message = ?, closed_at = ?, updated_at = ?,\n chunk_count = ?\n WHERE stream_id = ? AND state = 'streaming'`,\n [state, reason, Date.now(), Date.now(), finalCursor, streamId]\n );\n return settled > 0;\n }\n\n #emitSettled(\n streamId: string,\n state: Extract<StreamState, \"completed\" | \"errored\">,\n reason: string | null\n ): void {\n this.#emit(state === \"completed\" ? \"stream:closed\" : \"stream:errored\", {\n streamId,\n ...(reason !== null ? { reason } : {})\n });\n }\n\n // ── Live fanout ──────────────────────────────────────────────────────────\n\n #wake(streamId: string): void {\n const waiters = this.#wakeups.get(streamId);\n if (!waiters) return;\n this.#wakeups.delete(streamId);\n for (const wake of waiters) wake();\n }\n\n #waitForWakeup(streamId: string, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n const waiters = this.#wakeups.get(streamId) ?? new Set();\n this.#wakeups.set(streamId, waiters);\n const wake = () => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n };\n const onAbort = () => {\n waiters.delete(wake);\n // The last aborted waiter removes the map entry too, so abandoned\n // streams do not accumulate empty sets for the isolate's lifetime.\n if (waiters.size === 0 && this.#wakeups.get(streamId) === waiters) {\n this.#wakeups.delete(streamId);\n }\n // Resolve rather than reject: the read loop re-checks the signal\n // first and throws its reason from generator context.\n resolve();\n };\n waiters.add(wake);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n // ── Storage ──────────────────────────────────────────────────────────────\n\n #validateStreamId(streamId: string): void {\n if (typeof streamId !== \"string\" || streamId.length === 0) {\n throw new Error(\"Stream ids must be non-empty strings\");\n }\n if (streamId.length > MAX_STREAM_ID_LENGTH) {\n throw new Error(`Stream id exceeds ${MAX_STREAM_ID_LENGTH} characters`);\n }\n }\n\n #serialize(value: unknown, context: string): string | null {\n if (value === undefined) return null;\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch (error) {\n throw new StreamSerializationError(\n context,\n error instanceof Error ? error.message : String(error)\n );\n }\n if (json === undefined) {\n throw new StreamSerializationError(\n context,\n `value of type ${typeof value} has no JSON representation`\n );\n }\n const bytes = utf8.encode(json).byteLength;\n if (bytes > this.#maxChunkBytes) {\n throw new StreamSerializationError(\n context,\n `serialized size ${bytes} bytes exceeds the ${this.#maxChunkBytes}-byte limit`\n );\n }\n return json;\n }\n\n #sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ): T[] {\n const query = strings.reduce(\n (result, part, index) =>\n result + part + (index < values.length ? \"?\" : \"\"),\n \"\"\n );\n try {\n // SAFETY: Streams queries select from its own schema; T describes the\n // projected columns of the accompanying query text.\n return [...this.lifecycle.storage.sql.exec(query, ...values)] as T[];\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n #sqlWrite(query: string, params: (string | number | null)[]): number {\n try {\n return this.lifecycle.storage.sql.exec(query, ...params).rowsWritten;\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n #getStream(streamId: string): StreamRow | undefined {\n const rows = this.#sql<StreamRow>`\n SELECT * FROM cf_agents_streams WHERE stream_id = ${streamId}\n `;\n return rows[0];\n }\n\n /**\n * One stream's state alone — the narrow read for the append fence and the\n * reader loop's liveness checks, which need neither the metadata column\n * nor the (live-stale) counters of the full row.\n */\n #state(streamId: string): StreamState | undefined {\n const rows = this.#sql<{ state: StreamState }>`\n SELECT state FROM cf_agents_streams WHERE stream_id = ${streamId}\n `;\n return rows[0]?.state;\n }\n\n /**\n * The chunk log's tail: the next append sequence and the newest chunk's\n * timestamp. One PK-served read (`ORDER BY seq DESC LIMIT 1`), and the\n * single derivation point for every cursor and per-append-liveness\n * consumer — while a stream is live, the chunk log is authoritative and\n * the stream row's `chunk_count`/`updated_at` are not maintained.\n */\n #tail(streamId: string): { nextSeq: number; lastChunkAt: number | null } {\n const tail = this.#blockTail(streamId);\n return tail\n ? { nextSeq: tail.seq_to, lastChunkAt: tail.updated_at }\n : { nextSeq: 0, lastChunkAt: null };\n }\n\n /** The open block: one PK-served read (`ORDER BY block DESC LIMIT 1`). */\n #blockTail(streamId: string) {\n this.#foldLegacyChunks(streamId);\n return this.#sql<{\n block: number;\n seq_to: number;\n updated_at: number;\n len: number;\n }>`\n SELECT block, seq_to, updated_at, length(body) AS len\n FROM cf_agents_stream_blocks\n WHERE stream_id = ${streamId}\n ORDER BY block DESC\n LIMIT 1\n `[0];\n }\n\n /**\n * Schema v1 → v2 is lazy: the per-chunk `cf_agents_stream_chunks` rows of\n * ONE stream are folded into blocks the first time that stream is\n * touched (a tail read before an append or settle, a replay, a delete).\n * Startup never pays for the whole legacy log, so an object that let a\n * large log accumulate still boots within its memory budget; each fold\n * pages through its stream's rows and writes whole blocks, not one row\n * per chunk. The table is dropped once the last stream's rows are gone.\n */\n #foldLegacyChunks(streamId: string): void {\n if (!this.#legacyTableLive()) return;\n this.lifecycle.storage.transactionSync(() => {\n const tail = this.#sql<{ block: number; seq_to: number }>`\n SELECT block, seq_to FROM cf_agents_stream_blocks\n WHERE stream_id = ${streamId}\n ORDER BY block DESC\n LIMIT 1\n `[0];\n let block = (tail?.block ?? -1) + 1;\n let seq = tail?.seq_to ?? 0;\n let body = \"\";\n let seqFrom = seq;\n let createdAt = 0;\n let updatedAt = 0;\n const flush = () => {\n if (body === \"\") return;\n this.#sql`\n INSERT INTO cf_agents_stream_blocks\n (stream_id, block, seq_from, seq_to, body, created_at, updated_at)\n VALUES\n (${streamId}, ${block}, ${seqFrom}, ${seq}, ${body}, ${createdAt}, ${updatedAt})\n `;\n block += 1;\n body = \"\";\n seqFrom = seq;\n };\n let after = -1;\n for (;;) {\n const rows = this.#sql<{\n seq: number;\n chunk: string;\n created_at: number;\n }>`\n SELECT seq, chunk, created_at FROM cf_agents_stream_chunks\n WHERE stream_id = ${streamId} AND seq > ${after}\n ORDER BY seq ASC\n LIMIT ${LEGACY_FOLD_PAGE_ROWS}\n `;\n for (const row of rows) {\n if (\n body !== \"\" &&\n body.length + row.chunk.length + 1 > BLOCK_MAX_CHARS\n ) {\n flush();\n }\n if (body === \"\") createdAt = row.created_at;\n body = body === \"\" ? row.chunk : `${body},${row.chunk}`;\n updatedAt = row.created_at;\n seq += 1;\n after = row.seq;\n }\n if (rows.length < LEGACY_FOLD_PAGE_ROWS) break;\n }\n flush();\n if (after >= 0) {\n this.#sql`DELETE FROM cf_agents_stream_chunks WHERE stream_id = ${streamId}`;\n }\n this.#dropLegacyChunkTableIfEmpty();\n });\n }\n\n /**\n * Whether the v1 chunk table is still there. The flag is per instance,\n * but the table is per object: another Streams instance on the same\n * storage (a host's own, beside a harness's) may have folded the last v1\n * rows and dropped it. Recheck before use while the flag says it exists.\n */\n #legacyTableLive(): boolean {\n if (!this.#legacyChunkTable) return false;\n if (this.#hasLegacyChunkTable()) return true;\n this.#legacyChunkTable = false;\n return false;\n }\n\n #hasLegacyChunkTable(): boolean {\n return (\n this.#sql<{ name: string }>`\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name = 'cf_agents_stream_chunks'\n `.length > 0\n );\n }\n\n #dropLegacyChunkTableIfEmpty(): void {\n const remaining = this.#sql<{ n: number }>`\n SELECT COUNT(*) AS n FROM (SELECT 1 FROM cf_agents_stream_chunks LIMIT 1)\n `[0].n;\n if (remaining > 0) return;\n this.#sqlWrite(\"DROP TABLE cf_agents_stream_chunks\", []);\n this.#legacyChunkTable = false;\n }\n\n #rowToStatus(row: StreamRow): StreamStatus {\n // A live row's stored counters are stale by design (appends write only\n // the chunk log), so cursor and updatedAt are derived from the tail;\n // terminal rows were stamped exact at settle and read straight through.\n let cursor = row.chunk_count;\n let updatedAt = row.updated_at;\n if (row.state === \"streaming\") {\n const tail = this.#tail(row.stream_id);\n cursor = tail.nextSeq;\n if (tail.lastChunkAt !== null && tail.lastChunkAt > updatedAt) {\n updatedAt = tail.lastChunkAt;\n }\n }\n return {\n streamId: row.stream_id,\n state: row.state,\n cursor,\n ...(row.tag !== null ? { tag: row.tag } : {}),\n ...(row.metadata !== null\n ? {\n metadata: JSON.parse(row.metadata) as Record<string, StreamJson>\n }\n : {}),\n ...(row.error_message !== null ? { error: row.error_message } : {}),\n createdAt: row.created_at,\n updatedAt,\n ...(row.closed_at !== null ? { closedAt: row.closed_at } : {})\n };\n }\n\n #ensureTables(): void {\n const rawSql = (query: string) => {\n try {\n this.lifecycle.storage.sql.exec(query);\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n };\n // The chunk table is WITHOUT ROWID: Cloudflare bills index maintenance\n // as rows written, and an ordinary rowid table maintains a hidden\n // UNIQUE index for its PRIMARY KEY — one extra billed row on every\n // INSERT and DELETE. WITHOUT ROWID makes the PK the table itself, so a\n // chunk append bills exactly one row (see the write-accounting test).\n // The stream metadata table deliberately stays a rowid table: rowid is\n // the insertion-order tiebreak that keeps \"newest first\" deterministic\n // when rows share a created_at millisecond (stream ids are random),\n // and it costs one billed row per stream open — per turn, never per\n // chunk.\n rawSql(`\n CREATE TABLE IF NOT EXISTS cf_agents_streams (\n stream_id TEXT PRIMARY KEY,\n state TEXT NOT NULL CHECK (state IN (\n 'streaming', 'completed', 'errored'\n )),\n tag TEXT,\n metadata TEXT,\n error_message TEXT,\n chunk_count INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n closed_at INTEGER\n )`);\n rawSql(`\n CREATE INDEX IF NOT EXISTS idx_cf_agents_streams_tag\n ON cf_agents_streams(tag, created_at)\n `);\n rawSql(`\n CREATE TABLE IF NOT EXISTS cf_agents_stream_blocks (\n stream_id TEXT NOT NULL,\n block INTEGER NOT NULL,\n seq_from INTEGER NOT NULL,\n seq_to INTEGER NOT NULL,\n body TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (stream_id, block)\n ) WITHOUT ROWID`);\n }\n\n #emit(type: string, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,IAAa,oBAAb,cAAuC,MAAM;CAI3C,YAAY,UAAkB,QAAgB;EAC5C,MAAM,WAAW,SAAS,eAAe,QAAQ;EACjD,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;;;;;;AAQA,IAAa,sBAAb,cAAy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,SAAA,gBAAsB;CACpB,MAAM,UAAU,UAAkB;EAChC,IAAI;GACF,KAAK,UAAU,QAAQ,IAAI,KAAK,KAAK;EACvC,SAAS,OAAO;GACd,MAAM,IAAI,SAAS,OAAO,KAAK;EACjC;CACF;CAWA,OAAO;;;;;;;;;;;;;QAaH;CACJ,OAAO;;;KAGN;CACD,OAAO;;;;;;;;;;sBAUW;AACpB;AAEA,SAAA,MAAM,MAAc,SAAwC;CAC1D,KAAK,UAAU,OAAO,KAAK,MAAM,OAAO;AAC1C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as LifecycleCapability } from "./capability-runner-
|
|
1
|
+
import { s as LifecycleCapability } from "./capability-runner-BiVUtjqC.js";
|
|
2
2
|
|
|
3
3
|
//#region src/streams/types.d.ts
|
|
4
4
|
/**
|
|
@@ -369,4 +369,4 @@ export {
|
|
|
369
369
|
DEFAULT_MAX_CHUNK_BYTES as t,
|
|
370
370
|
StreamSettleOptions as u
|
|
371
371
|
};
|
|
372
|
-
//# sourceMappingURL=streams-
|
|
372
|
+
//# sourceMappingURL=streams-vrCtbUIn.d.ts.map
|
package/dist/sub-routing.d.ts
CHANGED
package/dist/tasks/index.d.ts
CHANGED
package/dist/tasks/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as DuplicateTaskStepError, c as TaskReplayDivergedError, i as MAX_SERIALIZED_BYTES, l as TaskSerializationError, o as MissingTaskDefinitionError, s as NonRetryableError, t as Tasks } from "../tasks-
|
|
1
|
+
import { a as DuplicateTaskStepError, c as TaskReplayDivergedError, i as MAX_SERIALIZED_BYTES, l as TaskSerializationError, o as MissingTaskDefinitionError, s as NonRetryableError, t as Tasks } from "../tasks-BN_5AWqI.js";
|
|
2
2
|
export { DuplicateTaskStepError, MAX_SERIALIZED_BYTES, MissingTaskDefinitionError, NonRetryableError, TaskReplayDivergedError, TaskSerializationError, Tasks };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
|
|
2
2
|
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
|
|
3
|
-
import { t as LifecycleCapability } from "./capability-
|
|
3
|
+
import { t as LifecycleCapability } from "./capability-DBAKc6UZ.js";
|
|
4
4
|
import { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isPlatformFailure } from "./retries.js";
|
|
5
5
|
import { SqlError } from "./sql-error.js";
|
|
6
6
|
import { nanoid } from "nanoid";
|
|
@@ -930,6 +930,7 @@ var Tasks = class extends LifecycleCapability {
|
|
|
930
930
|
this.lifecycle.trackAlarmWork(call);
|
|
931
931
|
return;
|
|
932
932
|
}
|
|
933
|
+
if (winner.outcome === false) return void 0;
|
|
933
934
|
return winner.outcome;
|
|
934
935
|
} catch (error) {
|
|
935
936
|
if (isPlatformFailure(error)) throw error;
|
|
@@ -1653,4 +1654,4 @@ function _emit(type, payload) {
|
|
|
1653
1654
|
//#endregion
|
|
1654
1655
|
export { DuplicateTaskStepError as a, TaskReplayDivergedError as c, MAX_SERIALIZED_BYTES as i, TaskSerializationError as l, setTaskDefinitionResolver as n, MissingTaskDefinitionError as o, setTaskRoutedMemoryLimitHandler as r, NonRetryableError as s, Tasks as t };
|
|
1655
1656
|
|
|
1656
|
-
//# sourceMappingURL=tasks-
|
|
1657
|
+
//# sourceMappingURL=tasks-BN_5AWqI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tasks-BN_5AWqI.js","names":[],"sources":["../src/tasks/errors.ts","../src/tasks/serialization.ts","../src/tasks/store.ts","../src/tasks/duration.ts","../src/tasks/replay.ts","../src/tasks/engine-port.ts","../src/tasks/tasks.ts"],"sourcesContent":["/**\n * Error classes for the Tasks capability. Each carries a stable `name` so\n * hosts and tests can classify failures without depending on message text.\n */\n\n/**\n * Thrown by a step callback to fail its run immediately, skipping any\n * remaining retry attempts.\n *\n * Errors named `\"NonRetryableError\"` from other sources (for example\n * `cloudflare:workflows`) are honored the same way.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class NonRetryableError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"NonRetryableError\";\n }\n}\n\n/** True when an error should skip remaining step retry attempts. */\nexport function isNonRetryableError(error: unknown): boolean {\n return (\n error instanceof NonRetryableError ||\n (error instanceof Error && error.name === \"NonRetryableError\")\n );\n}\n\n/**\n * Thrown before executing user code when one replay uses the same step name\n * twice. Step names are durable journal keys and must be unique within a run.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class DuplicateTaskStepError extends Error {\n /** The step name used more than once. */\n readonly stepName: string;\n\n constructor(stepName: string) {\n super(\n `Step name \"${stepName}\" was already used in this run. Step names are ` +\n `durable journal keys; suffix loop steps with a stable index, e.g. ` +\n `\"${stepName}:0\".`\n );\n this.name = \"DuplicateTaskStepError\";\n this.stepName = stepName;\n }\n}\n\n/**\n * Thrown when a replay observes a journal that this handler code cannot have\n * written — a known step under a different kind, for example. The run fails\n * rather than guessing; changing a definition's step layout for in-flight\n * runs requires versioning the definition name.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class TaskReplayDivergedError extends Error {\n /** The step name where replay diverged from the journal. */\n readonly stepName: string;\n\n constructor(stepName: string, detail: string) {\n super(\n `Replay diverged from the journal at step \"${stepName}\": ${detail}. ` +\n `Version the definition name (e.g. \"name@v2\") instead of changing ` +\n `the step layout of in-flight runs.`\n );\n this.name = \"TaskReplayDivergedError\";\n this.stepName = stepName;\n }\n}\n\n/**\n * Recorded against a run whose persisted definition name is no longer\n * registered after a deployment. The run fails visibly; it is never silently\n * deleted and never replayed against a different handler.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class MissingTaskDefinitionError extends Error {\n /** The persisted definition name that no longer resolves. */\n readonly definition: string;\n\n constructor(definition: string) {\n super(\n `No Task definition named \"${definition}\" is registered. A deployment ` +\n `removed or renamed it while this run was active. Re-register the ` +\n `definition (or a versioned successor with the same name) to let the ` +\n `run finish.`\n );\n this.name = \"MissingTaskDefinitionError\";\n this.definition = definition;\n }\n}\n\n/**\n * Thrown when a Task input, step result, metadata value, or final result is\n * not JSON-serializable or exceeds the serialized size limit.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class TaskSerializationError extends Error {\n constructor(context: string, detail: string) {\n super(`Cannot serialize ${context}: ${detail}`);\n this.name = \"TaskSerializationError\";\n }\n}\n","/**\n * Value serialization for the Tasks capability.\n *\n * Task inputs, step results, metadata, and final results persist as JSON\n * text in SQLite. `undefined` (and a `void` handler result) is represented\n * as SQL `NULL` rather than a JSON envelope, so the JSON column space stays\n * plain: `\"null\"` is JSON `null`, column `NULL` is `undefined`.\n */\n\nimport { TaskSerializationError } from \"./errors\";\n\n/** Default ceiling for one serialized value (1 MiB). */\nexport const MAX_SERIALIZED_BYTES = 1_048_576;\n\nconst utf8 = new TextEncoder();\n\n/**\n * Serialize one Task value for storage.\n *\n * @param value - The value to persist.\n * @param context - What is being serialized, for error messages\n * (e.g. `input for definition \"report\"`, `result of step \"fetch\"`).\n * @returns JSON text, or `null` when the value is `undefined`.\n * @throws TaskSerializationError when the value is not JSON-serializable or\n * its serialized form exceeds {@link MAX_SERIALIZED_BYTES}.\n */\nexport function serializeTaskValue(\n value: unknown,\n context: string\n): string | null {\n if (value === undefined) return null;\n\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch (error) {\n throw new TaskSerializationError(\n context,\n error instanceof Error ? error.message : String(error)\n );\n }\n if (json === undefined) {\n throw new TaskSerializationError(\n context,\n `value of type ${typeof value} has no JSON representation`\n );\n }\n\n const bytes = utf8.encode(json).byteLength;\n if (bytes > MAX_SERIALIZED_BYTES) {\n throw new TaskSerializationError(\n context,\n `serialized size ${bytes} bytes exceeds the ${MAX_SERIALIZED_BYTES}-byte limit`\n );\n }\n return json;\n}\n\n/**\n * Restore a value serialized by {@link serializeTaskValue}.\n *\n * @param stored - The stored column value.\n * @returns The original value; column `NULL` restores `undefined`.\n */\nexport function deserializeTaskValue(stored: string | null): unknown {\n if (stored === null) return undefined;\n return JSON.parse(stored);\n}\n","/**\n * Storage layer for the Tasks capability: owns the `cf_agents_task_runs` and\n * `cf_agents_task_steps` tables — DDL, row access, generation-fenced writes,\n * and the snapshot projection. The engine in `tasks.ts` holds the state\n * machine; every byte that touches SQLite goes through here.\n */\n\nimport { SqlError } from \"../sql-error\";\nimport { deserializeTaskValue } from \"./serialization\";\nimport type { TaskJson, TaskRunRow, TaskRunSnapshot, TaskValue } from \"./types\";\n\n/** @internal SQL-backed store for one Tasks capability instance. */\nexport class TaskStore {\n readonly #storage: DurableObjectStorage;\n\n constructor(storage: DurableObjectStorage) {\n this.#storage = storage;\n }\n\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ): T[] {\n const query = strings.reduce(\n (result, part, index) =>\n result + part + (index < values.length ? \"?\" : \"\"),\n \"\"\n );\n try {\n // SAFETY: Tasks queries select from its own schema; T describes the\n // projected columns of the accompanying query text.\n return [...this.#storage.sql.exec(query, ...values)] as T[];\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n write(query: string, params: (string | number | null)[]): number {\n try {\n return this.#storage.sql.exec(query, ...params).rowsWritten;\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n /**\n * Run one generation-fenced run mutation. Returns false when the fence\n * rejected it because another attempt superseded this one.\n */\n fencedWrite(\n runId: string,\n generation: string,\n query: string,\n leadingParams: (string | number | null)[]\n ): boolean {\n try {\n const cursor = this.#storage.sql.exec(\n query,\n ...leadingParams,\n runId,\n generation\n );\n return cursor.rowsWritten > 0;\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n getRun(runId: string): TaskRunRow | undefined {\n const rows = this.sql<TaskRunRow>`\n SELECT * FROM cf_agents_task_runs WHERE run_id = ${runId}\n `;\n return rows[0];\n }\n\n getRunByKey(idempotencyKey: string): TaskRunRow | undefined {\n const rows = this.sql<TaskRunRow>`\n SELECT * FROM cf_agents_task_runs WHERE idempotency_key = ${idempotencyKey}\n `;\n return rows[0];\n }\n\n deleteRun(runId: string): void {\n this.sql`DELETE FROM cf_agents_task_steps WHERE run_id = ${runId}`;\n this.sql`DELETE FROM cf_agents_task_runs WHERE run_id = ${runId}`;\n }\n\n ensureTables(): void {\n const rawSql = (query: string) => {\n try {\n this.#storage.sql.exec(query);\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n };\n rawSql(`\n CREATE TABLE IF NOT EXISTS cf_agents_task_runs (\n run_id TEXT PRIMARY KEY,\n definition TEXT NOT NULL,\n input TEXT,\n state TEXT NOT NULL CHECK (state IN (\n 'pending', 'running', 'waiting',\n 'completed', 'failed', 'cancelled'\n )),\n result TEXT,\n error_name TEXT,\n error_message TEXT,\n status_message TEXT,\n metadata TEXT,\n idempotency_key TEXT UNIQUE,\n retain INTEGER NOT NULL DEFAULT 1,\n attempt INTEGER NOT NULL DEFAULT 0,\n generation TEXT,\n next_at INTEGER,\n wait_reason TEXT,\n cancel_requested INTEGER NOT NULL DEFAULT 0,\n cancel_reason TEXT,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n updated_at INTEGER NOT NULL,\n settled_at INTEGER\n ) WITHOUT ROWID`);\n // No (state, next_at) index: every claim, refresh, and settle rewrites\n // next_at, and Cloudflare bills each touched index as a row written —\n // a per-write tax on the hottest run mutations, paid to accelerate the\n // startup reconcile's one scan of a retention-bounded table. The\n // definition index stays: list-by-definition reads scale with retained\n // runs, and definition/created_at never change after insert.\n rawSql(`\n CREATE INDEX IF NOT EXISTS cf_agents_task_runs_definition\n ON cf_agents_task_runs (definition, created_at)\n `);\n rawSql(`\n CREATE TABLE IF NOT EXISTS cf_agents_task_steps (\n run_id TEXT NOT NULL,\n step_name TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('do', 'sleep')),\n state TEXT NOT NULL CHECK (state IN (\n 'running', 'waiting', 'completed', 'failed'\n )),\n result TEXT,\n error_name TEXT,\n error_message TEXT,\n attempt INTEGER NOT NULL DEFAULT 0,\n next_at INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n updated_at INTEGER NOT NULL,\n completed_at INTEGER,\n PRIMARY KEY (run_id, step_name)\n ) WITHOUT ROWID`);\n }\n\n rowToSnapshot<Output extends TaskValue>(\n row: TaskRunRow\n ): TaskRunSnapshot<Output> {\n const metadata =\n row.metadata !== null\n ? (JSON.parse(row.metadata) as Record<string, TaskJson>)\n : undefined;\n const base = {\n runId: row.run_id,\n definition: row.definition,\n createdAt: row.created_at,\n ...(metadata !== undefined ? { metadata } : {})\n };\n switch (row.state) {\n case \"pending\":\n return { ...base, state: \"pending\" };\n case \"running\":\n return {\n ...base,\n state: \"running\",\n attempt: row.attempt,\n startedAt: row.started_at ?? row.created_at,\n ...(row.status_message !== null\n ? { statusMessage: row.status_message }\n : {})\n };\n case \"waiting\":\n return {\n ...base,\n state: \"waiting\",\n reason: row.wait_reason ?? \"sleep\",\n wakeAt: row.next_at ?? row.updated_at,\n ...(row.status_message !== null\n ? { statusMessage: row.status_message }\n : {})\n };\n case \"completed\":\n return {\n ...base,\n state: \"completed\",\n result: deserializeTaskValue(row.result) as Output,\n settledAt: row.settled_at ?? row.updated_at\n };\n case \"failed\":\n return {\n ...base,\n state: \"failed\",\n error: {\n name: row.error_name ?? \"Error\",\n message: row.error_message ?? \"Task run failed\"\n },\n settledAt: row.settled_at ?? row.updated_at\n };\n case \"cancelled\":\n return {\n ...base,\n state: \"cancelled\",\n ...(row.cancel_reason !== null ? { reason: row.cancel_reason } : {}),\n settledAt: row.settled_at ?? row.updated_at\n };\n }\n }\n}\n","/**\n * Duration parsing for the Tasks capability. Durations appear in step\n * retry delays, per-attempt timeouts, and durable sleeps.\n */\n\n/** Units accepted in a {@link TaskDurationString}. */\nexport type TaskDurationUnit = \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\";\n\n/**\n * A human-readable duration such as `\"10 seconds\"` or `\"1 day\"`.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport type TaskDurationString = `${number} ${TaskDurationUnit}${\"\" | \"s\"}`;\n\nconst UNIT_MILLISECONDS: Record<TaskDurationUnit, number> = {\n second: 1000,\n minute: 60 * 1000,\n hour: 60 * 60 * 1000,\n day: 24 * 60 * 60 * 1000,\n week: 7 * 24 * 60 * 60 * 1000\n};\n\nconst DURATION_PATTERN = /^(\\d+(?:\\.\\d+)?)\\s+(second|minute|hour|day|week)s?$/;\n\n/**\n * Parse a duration into whole milliseconds.\n *\n * @param duration - Milliseconds, or a duration string such as `\"10 seconds\"`.\n * @param context - Name of the option being parsed, used in error messages.\n * @returns The duration in milliseconds, floored to an integer.\n * @throws Error when the duration is negative, not finite, or unparseable.\n */\nexport function parseTaskDuration(\n duration: number | TaskDurationString,\n context: string\n): number {\n if (typeof duration === \"number\") {\n if (!Number.isFinite(duration) || duration < 0) {\n throw new Error(\n `Invalid ${context}: expected a non-negative number of milliseconds, got ${duration}`\n );\n }\n return Math.floor(duration);\n }\n const match = DURATION_PATTERN.exec(duration.trim());\n if (!match) {\n throw new Error(\n `Invalid ${context}: expected milliseconds or a duration like \"10 seconds\", got ${JSON.stringify(duration)}`\n );\n }\n const amount = Number(match[1]);\n const unit = match[2] as TaskDurationUnit;\n return Math.floor(amount * UNIT_MILLISECONDS[unit]);\n}\n","/**\n * Replay step engine for the Tasks capability.\n *\n * `ReplayStep` implements the `TaskStep` surface one handler attempt\n * receives. It owns replay semantics — journal hits, journal misses, retry\n * policy, durable sleeps, the status live gate, and duplicate/divergence\n * detection — while all SQL stays behind the narrow {@link TaskStepEngine}\n * port implemented by the `Tasks` capability, the single owner of the\n * schema.\n */\n\nimport {\n isDurableObjectCodeUpdateReset,\n isDurableObjectMemoryLimitReset,\n isPlatformFailure\n} from \"../retries\";\nimport { parseTaskDuration, type TaskDurationString } from \"./duration\";\nimport {\n DuplicateTaskStepError,\n TaskReplayDivergedError,\n TaskSerializationError,\n isNonRetryableError\n} from \"./errors\";\nimport { deserializeTaskValue } from \"./serialization\";\nimport type {\n TaskStep,\n TaskStepAttempt,\n TaskStepConfig,\n TaskStepRow,\n TaskValue,\n TaskWaitReason\n} from \"./types\";\n\n/** Resolved per-step retry and timeout policy. */\nexport type ResolvedStepPolicy = {\n readonly retryLimit: number;\n readonly retryDelayMs: number;\n readonly backoff: \"constant\" | \"linear\" | \"exponential\";\n readonly timeoutMs: number;\n};\n\n/** Longest computed retry delay: backoff growth never exceeds one day. */\nconst MAX_RETRY_DELAY_MS = 24 * 60 * 60 * 1000;\n\n/** Steps per run ceiling; crossing it fails the run instead of degrading. */\nexport const MAX_STEPS_PER_RUN = 10_000;\n\n/** Longest accepted step name. Step names are durable journal keys. */\nexport const MAX_STEP_NAME_LENGTH = 256;\n\n/**\n * Thrown by the engine to end one execution attempt while its run waits for\n * a durable deadline (sleep or retry). Not an `Error` subclass so a step\n * callback's `catch (error)` around unrelated work is less likely to swallow\n * it; the capability re-checks with {@link isTaskSuspension}.\n */\nexport class TaskSuspension {\n readonly wakeAt: number;\n readonly reason: TaskWaitReason;\n\n constructor(wakeAt: number, reason: TaskWaitReason) {\n this.wakeAt = wakeAt;\n this.reason = reason;\n }\n}\n\n/** True when a thrown value is the engine's suspension signal. */\nexport function isTaskSuspension(value: unknown): value is TaskSuspension {\n return value instanceof TaskSuspension;\n}\n\n/**\n * Thrown by the engine when a step boundary observes the run's cancellation\n * request. The capability settles the run as cancelled.\n */\nexport class TaskCancellation {\n readonly reason: string | undefined;\n\n constructor(reason: string | undefined) {\n this.reason = reason;\n }\n}\n\n/** True when a thrown value is the engine's cancellation signal. */\nexport function isTaskCancellation(value: unknown): value is TaskCancellation {\n return value instanceof TaskCancellation;\n}\n\n/**\n * Thrown by engine writes when another execution attempt has superseded this\n * one. The stale attempt unwinds without settling anything; every durable\n * write it might still try is generation-fenced.\n */\nexport class AttemptSupersededError extends Error {\n constructor(runId: string) {\n super(\n `Task attempt superseded: run \"${runId}\" is no longer claimed by this ` +\n `execution attempt`\n );\n this.name = \"AttemptSupersededError\";\n }\n}\n\n/**\n * Storage and policy port the `Tasks` capability supplies to one attempt's\n * `ReplayStep`. Every mutation is fenced by the attempt's generation on the\n * capability side.\n */\nexport interface TaskStepEngine {\n /** Read one step row of this run, or undefined for a journal miss. */\n readStep(name: string): TaskStepRow | undefined;\n\n /** Number of step rows this run has journaled. */\n countSteps(): number;\n\n /** Insert a new step row claimed at attempt 1. */\n insertStep(name: string, kind: \"do\" | \"sleep\", wakeAt: number | null): void;\n\n /** Journal an already-elapsed sleep born-completed, in one row write. */\n insertCompletedSleep(name: string): void;\n\n /** Claim the next attempt of an existing step. Returns the new attempt. */\n claimStepAttempt(name: string): number;\n\n /** Persist a completed step. Serializes and validates the result. */\n completeStep(name: string, result: unknown): void;\n\n /** Persist a terminally failed step. */\n failStep(name: string, error: { name: string; message: string }): void;\n\n /** Move a step into its retry wait. */\n waitStep(name: string, wakeAt: number): void;\n\n /** Extend the run's claim deadline while a step attempt executes. */\n refreshClaim(): void;\n\n /** Persist the run's observable status message. */\n writeStatus(message: string): void;\n\n /** The cancellation reason when this run was asked to cancel, else null. */\n cancellationRequested(): { reason: string | undefined } | null;\n\n /** Abort signal for the whole attempt (cancellation or supersession). */\n readonly attemptSignal: AbortSignal;\n\n /** Emit one capability event. */\n emit(type: string, payload: Record<string, unknown>): void;\n\n /** Stable external deduplication key for one named step. */\n stepIdempotencyKey(name: string): string;\n\n /** Default policy applied where a step config leaves fields unset. */\n readonly defaults: ResolvedStepPolicy;\n}\n\n/** Compute the delay before the next attempt after `failedAttempt` failed. */\nexport function computeRetryDelayMs(\n policy: ResolvedStepPolicy,\n failedAttempt: number\n): number {\n const base = policy.retryDelayMs;\n let delay: number;\n switch (policy.backoff) {\n case \"constant\":\n delay = base;\n break;\n case \"linear\":\n delay = base * failedAttempt;\n break;\n case \"exponential\":\n delay = base * 2 ** (failedAttempt - 1);\n break;\n }\n return Math.min(delay, MAX_RETRY_DELAY_MS);\n}\n\n/** Resolve one `step.do()` config against the capability defaults. */\nexport function resolveStepPolicy(\n defaults: ResolvedStepPolicy,\n config: TaskStepConfig | undefined\n): ResolvedStepPolicy {\n const limit = config?.retries?.limit ?? defaults.retryLimit;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error(\n `Invalid step retries.limit: expected an integer >= 1, got ${limit}`\n );\n }\n return {\n retryLimit: limit,\n retryDelayMs:\n config?.retries?.delay !== undefined\n ? parseTaskDuration(config.retries.delay, \"step retries.delay\")\n : defaults.retryDelayMs,\n backoff: config?.retries?.backoff ?? defaults.backoff,\n timeoutMs:\n config?.timeout !== undefined\n ? parseTaskDuration(config.timeout, \"step timeout\")\n : defaults.timeoutMs\n };\n}\n\n/**\n * The `TaskStep` implementation for one execution attempt.\n *\n * Attempt 1 starts live. A later attempt starts silent and becomes live at\n * the frontier of new ground — the first journal miss, or a step still\n * waiting or running — so replayed `status()` calls from completed ground\n * are suppressed instead of re-published as new progress.\n */\nexport class ReplayStep implements TaskStep {\n readonly #engine: TaskStepEngine;\n readonly #usedNames = new Set<string>();\n #live: boolean;\n readonly interrupted: {\n readonly name: string;\n readonly attempt: number;\n } | null;\n\n constructor(\n engine: TaskStepEngine,\n options: {\n startsLive: boolean;\n interrupted?: { name: string; attempt: number } | null;\n }\n ) {\n this.#engine = engine;\n this.#live = options.startsLive;\n this.interrupted = options.interrupted ?? null;\n }\n\n do<T extends TaskValue>(\n name: string,\n callback: (attempt: TaskStepAttempt) => T | Promise<T>\n ): Promise<T>;\n do<T extends TaskValue>(\n name: string,\n config: TaskStepConfig,\n callback: (attempt: TaskStepAttempt) => T | Promise<T>\n ): Promise<T>;\n async do<T extends TaskValue>(\n name: string,\n configOrCallback:\n | TaskStepConfig\n | ((attempt: TaskStepAttempt) => T | Promise<T>),\n maybeCallback?: (attempt: TaskStepAttempt) => T | Promise<T>\n ): Promise<T> {\n const config =\n typeof configOrCallback === \"function\" ? undefined : configOrCallback;\n const callback =\n typeof configOrCallback === \"function\" ? configOrCallback : maybeCallback;\n if (typeof callback !== \"function\") {\n throw new Error(`step.do(\"${name}\") requires a callback`);\n }\n const policy = resolveStepPolicy(this.#engine.defaults, config);\n this.#enterStep(name);\n\n const row = this.#engine.readStep(name);\n if (row === undefined) {\n this.#live = true;\n if (this.#engine.countSteps() >= MAX_STEPS_PER_RUN) {\n throw new Error(\n `Run exceeded ${MAX_STEPS_PER_RUN} steps; split the work across ` +\n `multiple Task runs`\n );\n }\n this.#engine.insertStep(name, \"do\", null);\n return this.#executeAttempt(name, 1, policy, callback);\n }\n\n if (row.kind !== \"do\") {\n throw new TaskReplayDivergedError(\n name,\n `journaled as a ${row.kind} step but replayed as a do step`\n );\n }\n\n switch (row.state) {\n case \"completed\":\n return deserializeTaskValue(row.result) as T;\n case \"failed\":\n // Defensive: a failed step fails its run, so replay should not reach\n // it. Surface the persisted terminal error rather than re-executing.\n throw restoreStepError(row);\n case \"waiting\": {\n // The frontier: a retry deadline from a previous attempt.\n this.#live = true;\n const wakeAt = row.next_at ?? Date.now();\n if (Date.now() < wakeAt) throw new TaskSuspension(wakeAt, \"retry\");\n const attempt = this.#engine.claimStepAttempt(name);\n this.#engine.emit(\"task:step:retry\", { step: name, attempt });\n return this.#executeAttempt(name, attempt, policy, callback);\n }\n case \"running\": {\n // A previous attempt was interrupted mid-step. Default replay\n // semantics: run it again under a fresh claim.\n this.#live = true;\n const attempt = this.#engine.claimStepAttempt(name);\n return this.#executeAttempt(name, attempt, policy, callback);\n }\n }\n }\n\n async sleep(\n name: string,\n duration: number | TaskDurationString\n ): Promise<void> {\n const durationMs = parseTaskDuration(duration, \"sleep duration\");\n return this.#sleepAt(name, () => Date.now() + durationMs);\n }\n\n async sleepUntil(name: string, when: number | Date): Promise<void> {\n const wakeAt = when instanceof Date ? when.getTime() : when;\n if (!Number.isFinite(wakeAt)) {\n throw new Error(\n `Invalid sleepUntil time for step \"${name}\": ${String(when)}`\n );\n }\n return this.#sleepAt(name, () => wakeAt);\n }\n\n async status(message: string): Promise<void> {\n if (!this.#live) return;\n this.#engine.writeStatus(String(message));\n }\n\n idempotencyKey(name: string): string {\n return this.#engine.stepIdempotencyKey(name);\n }\n\n // ── Internal ─────────────────────────────────────────────────────────────\n\n /** Validate a step boundary: name rules, duplicates, cancellation. */\n #enterStep(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"Step names must be non-empty strings\");\n }\n if (name.length > MAX_STEP_NAME_LENGTH) {\n throw new Error(\n `Step name exceeds ${MAX_STEP_NAME_LENGTH} characters: \"${name.slice(0, 40)}…\"`\n );\n }\n if (name.startsWith(\"__cf\")) {\n throw new Error(`Step names must not use the reserved \"__cf\" prefix`);\n }\n if (this.#usedNames.has(name)) {\n throw new DuplicateTaskStepError(name);\n }\n this.#usedNames.add(name);\n\n const cancellation = this.#engine.cancellationRequested();\n if (cancellation) throw new TaskCancellation(cancellation.reason);\n }\n\n /** First persist wins: the recorded wake time is authoritative. */\n async #sleepAt(name: string, wakeTime: () => number): Promise<void> {\n this.#enterStep(name);\n\n const row = this.#engine.readStep(name);\n if (row === undefined) {\n this.#live = true;\n const wakeAt = wakeTime();\n if (wakeAt <= Date.now()) {\n this.#engine.insertCompletedSleep(name);\n return;\n }\n this.#engine.insertStep(name, \"sleep\", wakeAt);\n throw new TaskSuspension(wakeAt, \"sleep\");\n }\n\n if (row.kind !== \"sleep\") {\n throw new TaskReplayDivergedError(\n name,\n `journaled as a ${row.kind} step but replayed as a sleep step`\n );\n }\n if (row.state === \"completed\") return;\n\n // The frontier: an unfinished sleep is the first unfinished step.\n this.#live = true;\n const wakeAt = row.next_at ?? 0;\n if (Date.now() < wakeAt) throw new TaskSuspension(wakeAt, \"sleep\");\n this.#engine.completeStep(name, undefined);\n }\n\n /** Execute one claimed attempt of a `do` step under timeout and retries. */\n async #executeAttempt<T extends TaskValue>(\n name: string,\n attempt: number,\n policy: ResolvedStepPolicy,\n callback: (attempt: TaskStepAttempt) => T | Promise<T>\n ): Promise<T> {\n this.#engine.refreshClaim();\n this.#engine.emit(\"task:step:started\", { step: name, attempt });\n\n const timeout = new AbortController();\n const onRunAbort = () => timeout.abort(this.#engine.attemptSignal.reason);\n this.#engine.attemptSignal.addEventListener(\"abort\", onRunAbort, {\n once: true\n });\n const timer = setTimeout(() => {\n timeout.abort(\n new Error(\n `Step \"${name}\" attempt ${attempt} timed out after ${policy.timeoutMs}ms`\n )\n );\n }, policy.timeoutMs);\n\n try {\n const result = await this.#raceTimeout<T>(\n Promise.resolve(\n callback({\n attempt,\n idempotencyKey: this.#engine.stepIdempotencyKey(name),\n signal: timeout.signal\n })\n ),\n timeout.signal\n );\n this.#engine.completeStep(name, result);\n this.#engine.emit(\"task:step:completed\", { step: name, attempt });\n return result;\n } catch (error) {\n if (error instanceof AttemptSupersededError) throw error;\n const cancellation = this.#engine.cancellationRequested();\n if (cancellation) throw new TaskCancellation(cancellation.reason);\n // A condemned isolate cannot recover in-process. Leave the journal row\n // running and let the whole Task reach the alarm boundary, where a code\n // update defers to fresh code and a memory reset enters the breaker.\n // Other platform transients (notably \"Network connection lost\") retain\n // the ordinary short step retry budget before the run defers.\n if (\n isDurableObjectCodeUpdateReset(error) ||\n isDurableObjectMemoryLimitReset(error)\n ) {\n throw error;\n }\n // Transient platform errors use the configured durable retry budget.\n // Once that budget is spent they still are not application failures:\n // keep the step claimed and defer the whole run to a later invocation.\n if (isPlatformFailure(error) && attempt >= policy.retryLimit) throw error;\n if (\n isNonRetryableError(error) ||\n error instanceof TaskSerializationError ||\n attempt >= policy.retryLimit\n ) {\n this.#engine.failStep(name, toErrorSummary(error));\n throw error;\n }\n const wakeAt = Date.now() + computeRetryDelayMs(policy, attempt);\n this.#engine.waitStep(name, wakeAt);\n throw new TaskSuspension(wakeAt, \"retry\");\n } finally {\n clearTimeout(timer);\n this.#engine.attemptSignal.removeEventListener(\"abort\", onRunAbort);\n }\n }\n\n /**\n * Settle with the callback or its timeout, whichever finishes first. A\n * callback that ignores its abort signal cannot wedge the attempt; its\n * late settlement is discarded and generation fencing rejects late writes.\n */\n #raceTimeout<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n }\n}\n\n/** Rebuild a persisted terminal step error for rethrow. */\nfunction restoreStepError(row: TaskStepRow): Error {\n const error = new Error(row.error_message ?? \"Step failed\");\n error.name = row.error_name ?? \"Error\";\n return error;\n}\n\n/** Safe name/message projection of an arbitrary thrown value. */\nexport function toErrorSummary(error: unknown): {\n name: string;\n message: string;\n} {\n if (error instanceof Error) {\n return { name: error.name, message: error.message };\n }\n return { name: \"Error\", message: String(error) };\n}\n","/**\n * The step-engine port: the storage-side operations `ReplayStep` drives —\n * journal reads and writes, generation fencing, claim refresh, progress —\n * bound to one claimed attempt. `tasks.ts` owns the state machine; this\n * module owns nothing but the port's construction.\n */\n\nimport {\n AttemptSupersededError,\n type TaskStepEngine,\n type ResolvedStepPolicy\n} from \"./replay\";\nimport { serializeTaskValue } from \"./serialization\";\nimport type { TaskStepRow } from \"./types\";\nimport type { TaskStore } from \"./store\";\n\n/** @internal What one step engine needs from its owning capability. */\nexport type TaskStepEngineDeps = {\n store: TaskStore;\n runId: string;\n generation: string;\n signal: AbortSignal;\n claimTimeoutMs: () => number;\n /** When the attempt's claim write persisted its `next_at` backstop. */\n claimedAtMs: number;\n /**\n * Minimum wall time between claim writes. Sized to half the claim slack:\n * every claim write lands `step timeout + slack` ahead, so a refresh\n * skipped this recently still leaves a full step timeout plus half the\n * slack of headroom — no policy-respecting step can outlive the claim,\n * and a burst of fast steps pays zero claim-refresh row writes.\n */\n claimRefreshAfterMs: number;\n defaults: ResolvedStepPolicy;\n emit: (type: string, payload: Record<string, unknown>) => void;\n};\n\n/** @internal Build the engine port for one claimed attempt. */\nexport function createTaskStepEngine(deps: TaskStepEngineDeps): TaskStepEngine {\n const { runId, generation } = deps;\n // The newest claim deadline known durable. The queue's own backstop push\n // (a due wake observing the live attempt) only ever moves `next_at`\n // forward, so this stays a conservative lower bound.\n let lastClaimWriteAt = deps.claimedAtMs;\n // The last status message known durable — persisting an identical one\n // again would be a pure row-write duplicate.\n let lastStatusMessage: string | undefined;\n const assertCurrent = (): void => {\n const row = deps.store.getRun(runId);\n if (!row || row.generation !== generation) {\n throw new AttemptSupersededError(runId);\n }\n };\n return {\n readStep: (name) => {\n const rows = deps.store.sql<TaskStepRow>`\n SELECT * FROM cf_agents_task_steps\n WHERE run_id = ${runId} AND step_name = ${name}\n `;\n return rows[0];\n },\n countSteps: () => {\n const rows = deps.store.sql<{ count: number }>`\n SELECT COUNT(*) AS count FROM cf_agents_task_steps WHERE run_id = ${runId}\n `;\n return rows[0]?.count ?? 0;\n },\n insertStep: (name, kind, wakeAt) => {\n assertCurrent();\n const now = Date.now();\n deps.store.sql`\n INSERT INTO cf_agents_task_steps\n (run_id, step_name, kind, state, attempt, next_at, created_at,\n started_at, updated_at)\n VALUES\n (${runId}, ${name}, ${kind},\n ${kind === \"do\" ? \"running\" : wakeAt === null ? \"running\" : \"waiting\"},\n ${kind === \"do\" ? 1 : 0}, ${wakeAt},\n ${now}, ${kind === \"do\" ? now : null}, ${now})\n `;\n },\n insertCompletedSleep: (name) => {\n assertCurrent();\n const now = Date.now();\n // An already-elapsed sleep is journaled born-completed: one INSERT,\n // where insert-then-complete would write the same row twice in the\n // same synchronous block (one durable commit either way, so the\n // split bought no crash evidence).\n deps.store.sql`\n INSERT INTO cf_agents_task_steps\n (run_id, step_name, kind, state, attempt, next_at, created_at,\n completed_at, updated_at)\n VALUES\n (${runId}, ${name}, 'sleep', 'completed', 0, NULL, ${now},\n ${now}, ${now})\n `;\n },\n claimStepAttempt: (name) => {\n assertCurrent();\n const now = Date.now();\n deps.store.sql`\n UPDATE cf_agents_task_steps\n SET state = 'running', attempt = attempt + 1, next_at = NULL,\n started_at = ${now}, updated_at = ${now}\n WHERE run_id = ${runId} AND step_name = ${name}\n `;\n const rows = deps.store.sql<{ attempt: number }>`\n SELECT attempt FROM cf_agents_task_steps\n WHERE run_id = ${runId} AND step_name = ${name}\n `;\n return rows[0]?.attempt ?? 1;\n },\n completeStep: (name, result) => {\n assertCurrent();\n const resultJson = serializeTaskValue(\n result,\n `result of step \"${name}\" in run \"${runId}\"`\n );\n const now = Date.now();\n deps.store.sql`\n UPDATE cf_agents_task_steps\n SET state = 'completed', result = ${resultJson}, next_at = NULL,\n completed_at = ${now}, updated_at = ${now}\n WHERE run_id = ${runId} AND step_name = ${name}\n `;\n },\n failStep: (name, error) => {\n assertCurrent();\n const now = Date.now();\n deps.store.sql`\n UPDATE cf_agents_task_steps\n SET state = 'failed', error_name = ${error.name},\n error_message = ${error.message}, next_at = NULL, updated_at = ${now}\n WHERE run_id = ${runId} AND step_name = ${name}\n `;\n },\n waitStep: (name, wakeAt) => {\n assertCurrent();\n const now = Date.now();\n deps.store.sql`\n UPDATE cf_agents_task_steps\n SET state = 'waiting', next_at = ${wakeAt}, updated_at = ${now}\n WHERE run_id = ${runId} AND step_name = ${name}\n `;\n },\n refreshClaim: () => {\n const now = Date.now();\n if (now - lastClaimWriteAt < deps.claimRefreshAfterMs) return;\n const written = deps.store.fencedWrite(\n runId,\n generation,\n `UPDATE cf_agents_task_runs SET next_at = ?, updated_at = ?\n WHERE run_id = ? AND generation = ? AND state = 'running'`,\n [now + deps.claimTimeoutMs(), now]\n );\n if (written) lastClaimWriteAt = now;\n },\n writeStatus: (message) => {\n if (message === lastStatusMessage) return;\n const written = deps.store.fencedWrite(\n runId,\n generation,\n `UPDATE cf_agents_task_runs SET status_message = ?, updated_at = ?\n WHERE run_id = ? AND generation = ? AND state = 'running'`,\n [message, Date.now()]\n );\n if (written) lastStatusMessage = message;\n },\n cancellationRequested: () => {\n const row = deps.store.getRun(runId);\n if (!row || row.cancel_requested !== 1) return null;\n return { reason: row.cancel_reason ?? undefined };\n },\n attemptSignal: deps.signal,\n emit: deps.emit,\n stepIdempotencyKey: (name) => `${runId}:${name}`,\n defaults: deps.defaults\n };\n}\n","/**\n * Durable replayable execution for Lifecycle Objects. `Tasks` owns the\n * `cf_agents_task_runs` and `cf_agents_task_steps` tables, the definitions registry, run\n * acceptance, generation-fenced claiming, and due-run processing.\n *\n * Tasks consumes only the standard capability services: storage, the job\n * queue, the host invocation boundary, events, and routing. A run's storage\n * and step journal always live where it was accepted; only its deadline\n * mirrors as one Lifecycle queue job, routed to the root Lifecycle when\n * accepted on a routed sub-agent, since only the root owns the physical\n * alarm. Definition handlers run through Lifecycle's host invocation\n * boundary. Interrupted work replays: completed steps return journaled\n * results and handlers resume from durable evidence.\n */\n\nimport { nanoid } from \"nanoid\";\nimport { LifecycleCapability } from \"../lifecycle/capability\";\nimport type {\n LifecycleRouteAddress,\n LifecycleRouteContext\n} from \"../lifecycle/capability\";\nimport type { MemoryLimitContext } from \"../lifecycle/capability-runner\";\nimport type {\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"../lifecycle/job-queue\";\nimport { isPlatformFailure } from \"../retries\";\nimport { SqlError } from \"../sql-error\";\nimport { TaskStore } from \"./store\";\nimport { createTaskStepEngine } from \"./engine-port\";\nimport { parseTaskDuration } from \"./duration\";\nimport { MissingTaskDefinitionError } from \"./errors\";\nimport type { TaskEventType, TasksOptions } from \"./options\";\nimport {\n AttemptSupersededError,\n TaskCancellation,\n isTaskCancellation,\n isTaskSuspension,\n ReplayStep,\n toErrorSummary,\n type TaskStepEngine,\n type ResolvedStepPolicy\n} from \"./replay\";\nimport { deserializeTaskValue, serializeTaskValue } from \"./serialization\";\nimport type {\n Task,\n TaskCallbacks,\n TaskHandlers,\n TaskInput,\n TaskOutput,\n TaskReceipt,\n TaskRunOptions,\n TaskRunRow,\n TaskRunSnapshot,\n TaskRunState,\n TaskValue\n} from \"./types\";\n\n/**\n * A composition-root fallback for definition names outside the declared\n * map. The value type is the input-erased handler form (`TaskCallbacks`),\n * so a host resolving concretely-typed definitions casts once, here, and\n * nowhere else.\n */\nexport type TaskDefinitionResolver = (\n name: string\n) => TaskCallbacks[string] | undefined;\n\nconst taskDefinitionResolvers = new WeakMap<object, TaskDefinitionResolver>();\n\n/**\n * @internal Supply a composition-root fallback for definition names outside\n * the declared map. Frameworks use this to attach internal definitions (for\n * example a future Agent compatibility layer) without occupying the host's\n * constructor map; resolved handlers still run inside the Lifecycle host\n * boundary. The resolver must return the same definition for a name on\n * every Durable Object wake, or that name's in-flight runs cannot resume.\n */\nexport function setTaskDefinitionResolver(\n tasks: Tasks<never>,\n resolver: TaskDefinitionResolver\n): void {\n taskDefinitionResolvers.set(tasks, resolver);\n}\n\nconst taskRoutedMemoryLimitHandlers = new WeakMap<\n object,\n (context: MemoryLimitContext) => void | Promise<void>\n>();\n\n/**\n * @internal Supply a composition-root bridge from a routed run's sealed\n * strike to the owning host's own `onAlarmMemoryLimit` hook. A root's own\n * local runs already reach that hook through Lifecycle's alarm dispatch on\n * the same Durable Object; a routed run's owner is a different instance,\n * whose Lifecycle never observes the root's alarm directly.\n */\nexport function setTaskRoutedMemoryLimitHandler(\n tasks: Tasks<never>,\n handler: (context: MemoryLimitContext) => void | Promise<void>\n): void {\n taskRoutedMemoryLimitHandlers.set(tasks, handler);\n}\n\nconst FIBER_SCHEMA_VERSION_KEY = \"cf_agents:tasks_schema_version\";\nconst CURRENT_FIBER_SCHEMA_VERSION = 1;\n\nconst DEFAULT_STEP_POLICY: ResolvedStepPolicy = {\n retryLimit: 5,\n retryDelayMs: 1000,\n backoff: \"exponential\",\n timeoutMs: 5 * 60 * 1000\n};\n\n/**\n * Slack added to the default step timeout to form the claim deadline — the\n * durable recovery backstop that wakes the object when a claimed attempt's\n * isolate disappears.\n */\nconst CLAIM_SLACK_MS = 30_000;\n\nconst DEFAULT_LIST_LIMIT = 100;\nconst MAX_DEFINITION_NAME_LENGTH = 256;\n/**\n * Queue-job id prefix for run wakes. Run IDs are caller-selectable, so the\n * job id namespaces them instead of exposing them verbatim to the shared\n * job id space.\n */\nconst WAKE_JOB_PREFIX = \"task:\";\n/** Normal Task deadline dispatch. */\nconst WAKE_JOB_FN = \"wake\";\n/**\n * A platform failure that escapes an attempt (ReplayStep rethrows once the\n * step's own retry budget is spent) leaves the run claimed with a future\n * `next_at`. An in-driver retry would not re-run the step — `#executeRun`\n * returns at its claim guard — it would only read the claim back as a clean\n * `{ rescheduleAt }`, hiding the failure from the alarm boundary. One\n * attempt keeps JobDriver's platform-failure contract: the wake rejects, the\n * job row is preserved, and the platform re-runs the alarm on a fresh\n * invocation while the claim deadline stays the durable wake.\n */\nconst WAKE_JOB_RETRY = { maxAttempts: 1 } as const;\n/**\n * How long one queue-driven attempt may hold the serial dispatch loop\n * before detaching. Correctness never depends on the inline await — the\n * claim backstop owns the durable wake — so this only trades a prompt\n * inline settle for queue liveness.\n */\nconst DISPATCH_BUDGET_MS = 5_000;\n\nconst TERMINAL_STATES: ReadonlySet<TaskRunState> = new Set([\n \"completed\",\n \"failed\",\n \"cancelled\"\n]);\n\n/**\n * A wake job's payload. Owner fields are set only for a routed run's mirror\n * on the root Lifecycle — the run row and step journal stay on the owning\n * facet, which is where `dispatch` and `memoryLimit` route back to.\n */\ntype TaskWakeJobPayload = {\n readonly runId: string;\n readonly owner_path?: string | null;\n readonly owner_path_key?: string | null;\n};\n\nfunction isTaskWakeJobPayload(value: unknown): value is TaskWakeJobPayload {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as TaskWakeJobPayload).runId === \"string\"\n );\n}\n\n/** Tasks protocol messages routed between a facet and the root Lifecycle. */\ntype TaskRouteMessage =\n | {\n readonly type: \"syncWake\";\n readonly runId: string;\n readonly next: number | null;\n }\n | { readonly type: \"dispatch\"; readonly runId: string }\n | {\n readonly type: \"memoryLimit\";\n readonly runId: string;\n readonly context: MemoryLimitContext;\n };\n\n/**\n * Who drives an accepted run's first attempt: `warm` starts it detached in\n * the caller's invocation (the public `run()` behaviour), `queued` leaves it\n * to the durable wake, and `attached` lets the caller drive and await it.\n */\ntype TaskStartMode = \"warm\" | \"queued\" | \"attached\";\n\n/** One live execution attempt in this isolate. */\ntype ActiveAttempt = {\n readonly generation: string;\n readonly controller: AbortController;\n readonly promise: Promise<void>;\n};\n\n/** Filters accepted by {@link Tasks.list}. */\nexport type TaskListOptions = {\n definition?: string;\n status?: TaskRunState | TaskRunState[];\n limit?: number;\n};\n\n/** Filters accepted by {@link Tasks.delete}. */\nexport type TaskDeleteOptions = {\n status?: Array<\"completed\" | \"failed\" | \"cancelled\">;\n settledBefore?: Date;\n limit?: number;\n};\n\n/**\n * Durable replayable execution for a Lifecycle Object.\n *\n * Declare named definitions in the constructor and install the instance with\n * `Lifecycle.use()`. The constructor map is the registry: it is rebuilt on\n * every Durable Object wake, so in-flight runs always resolve their\n * persisted definition names. Each definition's handler replays from the\n * beginning on every execution attempt; completed steps return journaled\n * results, sleeps consult persisted deadlines, and interrupted work\n * continues from the first unfinished step after process loss.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Tasks<\n Handlers extends TaskHandlers = TaskCallbacks\n> extends LifecycleCapability {\n readonly #definitions: TaskHandlers;\n readonly #registered = new Map<string, TaskCallbacks[string]>();\n readonly #active = new Map<string, ActiveAttempt>();\n #storeInstance: TaskStore | undefined;\n readonly #stepDefaults: ResolvedStepPolicy;\n readonly #onError: ((error: unknown) => void | Promise<void>) | undefined;\n\n /**\n * Create a Tasks capability.\n *\n * @param options - Named definitions plus default step retry/timeout\n * policy and alarm batching. Declaring `definitions` types {@link run} and\n * {@link handle} against the map — names and inputs are checked where the\n * handlers are declared and where runs start. Names outside the map are\n * rejected unless a composition-root resolver supplies them.\n */\n constructor(options: TasksOptions<Handlers> = {}) {\n super(\"tasks\");\n this.#definitions = options.definitions ?? {};\n this.#stepDefaults = {\n retryLimit: options.retries?.limit ?? DEFAULT_STEP_POLICY.retryLimit,\n retryDelayMs:\n options.retries?.delay !== undefined\n ? parseTaskDuration(options.retries.delay, \"retries.delay\")\n : DEFAULT_STEP_POLICY.retryDelayMs,\n backoff: options.retries?.backoff ?? DEFAULT_STEP_POLICY.backoff,\n timeoutMs:\n options.stepTimeout !== undefined\n ? parseTaskDuration(options.stepTimeout, \"stepTimeout\")\n : DEFAULT_STEP_POLICY.timeoutMs\n };\n this.#onError = options.onError;\n }\n\n #claimTimeoutMs(): number {\n return this.#stepDefaults.timeoutMs + CLAIM_SLACK_MS;\n }\n\n /** The SQL store over this Lifecycle's storage (see `store.ts`). */\n get #store(): TaskStore {\n this.#storeInstance ??= new TaskStore(this.lifecycle.storage);\n return this.#storeInstance;\n }\n\n // ── Definitions ──────────────────────────────────────────────────────────\n\n /** Resolve a name to its declared or composition-root-supplied handler. */\n #resolveDefinition(name: string): TaskCallbacks[string] | undefined {\n // SAFETY: declared definitions are constrained with `never` parameters\n // so concrete definition types satisfy the map under contravariance; the\n // values passed at dispatch were parsed from rows this definition's name\n // was persisted with.\n return (this.#definitions[name] ??\n this.#registered.get(name) ??\n taskDefinitionResolvers.get(this)?.(name)) as\n | TaskCallbacks[string]\n | undefined;\n }\n\n /** True when a name resolves to a runnable definition. */\n #hasDefinition(name: string): boolean {\n return this.#resolveDefinition(name) !== undefined;\n }\n\n #validateDefinitionName(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"Task definition names must be non-empty strings\");\n }\n if (name.length > MAX_DEFINITION_NAME_LENGTH) {\n throw new Error(\n `Task definition name exceeds ${MAX_DEFINITION_NAME_LENGTH} characters`\n );\n }\n if (name.startsWith(\"__cf\")) {\n throw new Error(\n `Task definition names must not use the reserved \"__cf\" prefix`\n );\n }\n if (!this.#hasDefinition(name)) {\n throw new Error(\n `Unknown Task definition \"${name}\": not declared on this Tasks`\n );\n }\n }\n\n /**\n * @internal Framework aperture: register one reserved (`__cf`-prefixed)\n * Task definition directly on this instance, bypassing the constructor's\n * `definitions` map so a host's own subclass layers can each declare their\n * own `definitions` / `taskDefinitions` field without colliding with — or\n * being silently clobbered by — a framework's internal names. Call once per\n * name from the owning host's own constructor, unconditionally, so the\n * definition is rebuilt identically on every Durable Object wake: an\n * in-flight run resolves the same handler for its persisted definition name\n * every time, or it cannot resume.\n *\n * Throws if `name` does not carry the reserved `__cf` prefix — this is not\n * a general-purpose registration path; declare ordinary definitions in the\n * constructor's `definitions` map instead — or if `name` is already\n * registered, which is always a real conflict: this method runs exactly\n * once per name per Tasks construction.\n */\n register(name: string, definition: TaskCallbacks[string]): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"Task definition names must be non-empty strings\");\n }\n if (name.length > MAX_DEFINITION_NAME_LENGTH) {\n throw new Error(\n `Task definition name exceeds ${MAX_DEFINITION_NAME_LENGTH} characters`\n );\n }\n if (!name.startsWith(\"__cf\")) {\n throw new Error(\n `register() requires a \"__cf\"-prefixed reserved definition name, got \"${name}\"`\n );\n }\n if (Object.hasOwn(this.#definitions, name) || this.#registered.has(name)) {\n throw new Error(\n `Task definition \"${name}\" is already registered on this Tasks capability`\n );\n }\n this.#registered.set(name, definition);\n }\n\n // ── Starting runs ────────────────────────────────────────────────────────\n\n /**\n * Durably accept one run of a declared definition and return a receipt\n * without waiting for terminal state. The same `idempotencyKey` or `runId`\n * joins the existing run (`accepted: false`) instead of creating a second.\n */\n async run<Name extends keyof Handlers & string>(\n definition: Name,\n input?: TaskInput<Handlers[Name]>,\n options?: TaskRunOptions\n ): Promise<TaskReceipt> {\n this.#validateDefinitionName(definition);\n return this.#accept(definition, input, options);\n }\n\n /**\n * A typed handle scoped to one declared definition: its `run`, `get`,\n * `getByIdempotencyKey`, and `cancel` see only that definition's runs. The\n * handle is a pure lens over this capability — it holds no state and may\n * be created at any time.\n */\n handle<Name extends keyof Handlers & string>(\n definition: Name\n ): Task<TaskInput<Handlers[Name]>, TaskOutput<Handlers[Name]>> {\n this.#validateDefinitionName(definition);\n return {\n name: definition,\n run: (input, options) => this.run(definition, input, options),\n get: (runId) => this.#snapshot(runId, definition),\n getByIdempotencyKey: (idempotencyKey) =>\n this.#snapshotByKey(idempotencyKey, definition),\n cancel: (runId, reason) => this.#cancelScoped(runId, definition, reason)\n };\n }\n\n /** Cancel through a handle: another definition's run is not visible. */\n async #cancelScoped(\n runId: string,\n definition: string,\n reason?: string\n ): Promise<boolean> {\n await this.lifecycle.ready();\n const row = this.#store.getRun(runId);\n if (!row || row.definition !== definition) return false;\n return this.cancel(runId, reason);\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate storage and reconcile run deadlines during Lifecycle startup. */\n async onStart(): Promise<void> {\n const storage = this.lifecycle.storage;\n const version = (await storage.get<number>(FIBER_SCHEMA_VERSION_KEY)) ?? 0;\n if (version < CURRENT_FIBER_SCHEMA_VERSION) {\n this.#store.ensureTables();\n await storage.put(FIBER_SCHEMA_VERSION_KEY, CURRENT_FIBER_SCHEMA_VERSION);\n }\n this.#reconcile();\n await this.#syncAllWakes();\n }\n\n /** Drive one due run's wake dispatched by the Lifecycle event loop. */\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n const timing = isTaskWakeJobPayload(context.job.payload)\n ? context.job.payload\n : undefined;\n const runId = timing?.runId ?? context.job.id.slice(WAKE_JOB_PREFIX.length);\n\n if (timing?.owner_path) {\n // This root mirrors a routed facet's wake; the run and its step\n // journal live on the owning facet, so dispatch routes back there.\n // The facet fully awaits its own dispatch — no local budget to race,\n // since this root now races its own await of the call and, on\n // budget, keeps the still-pending call tracked against this alarm's\n // memory-limit breaker domain instead of discarding it. Verified\n // against a deployed repro: a callee's real memory-limit reset mid\n // RPC rejects the caller's pending call with the platform's own\n // \"exceeded its memory limit\" text, exactly what the breaker already\n // matches on — so a late failure on the facet is attributed here\n // just like a local detached attempt would be.\n const target = {\n key: timing.owner_path_key ?? timing.owner_path,\n data: timing.owner_path\n };\n const call = this.lifecycle.routes.to(target, {\n type: \"dispatch\",\n runId\n } satisfies TaskRouteMessage);\n let budgetTimer: ReturnType<typeof setTimeout> | undefined;\n const budget = new Promise<\"budget\">((resolve) => {\n budgetTimer = setTimeout(() => resolve(\"budget\"), DISPATCH_BUDGET_MS);\n });\n try {\n const winner = await Promise.race([\n call.then((outcome) => ({ outcome })),\n budget\n ]);\n if (winner === \"budget\") {\n this.lifecycle.trackAlarmWork(call);\n // The facet's own routed #syncWake, made whenever it eventually\n // settles, supersedes whatever this returns (newer pushes win\n // over drive results), same as the local path below.\n return undefined;\n }\n // `false` means the owner facet is gone: the route already cleaned\n // up its prefix, so drop this mirrored wake instead of handing the\n // queue an outcome it rejects.\n if (winner.outcome === false) return undefined;\n return winner.outcome as LifecycleJobOutcome;\n } catch (error) {\n if (isPlatformFailure(error)) throw error;\n console.error(`error dispatching routed Task run \"${runId}\"`, error);\n return \"yield\";\n } finally {\n clearTimeout(budgetTimer);\n }\n }\n\n return this.#dispatchRun(runId);\n }\n\n /** Push a live attempt's durable claim deadline forward one claim window. */\n #refreshClaim(runId: string): void {\n this.#store.sql`\n UPDATE cf_agents_task_runs\n SET next_at = ${Date.now() + this.#claimTimeoutMs()}, updated_at = ${Date.now()}\n WHERE run_id = ${runId} AND state = 'running'\n `;\n }\n\n /**\n * Drive one local due run to its next durable boundary, bounded by the\n * dispatch budget, and return the wake outcome for this capability's own\n * queue job.\n */\n async #dispatchRun(runId: string): Promise<LifecycleJobOutcome> {\n const active = this.#active.get(runId);\n if (active) {\n // A live attempt in this isolate; push the claim backstop forward so\n // the due job does not hot-loop the alarm while it works.\n this.#refreshClaim(runId);\n this.lifecycle.trackAlarmWork(active.promise);\n return this.#wakeOutcome(runId);\n }\n // Dispatch is bounded: the queue drives jobs serially, so this attempt\n // may not hold the loop for its full step budget. Short attempts (the\n // common case — memoized replays, quick steps) settle inline; a longer\n // one detaches at the budget and keeps executing while this isolate\n // lives. Durability does not depend on the await: the claim backstop in\n // the run row is the wake that survives isolate death, and a detached\n // settle re-syncs the wake mirror, superseding the outcome returned\n // below (newer pushes win over drive results).\n let budgetTimer: ReturnType<typeof setTimeout> | undefined;\n const budget = new Promise<\"budget\">((resolve) => {\n budgetTimer = setTimeout(() => resolve(\"budget\"), DISPATCH_BUDGET_MS);\n });\n const runAttempt = this.#executeRun(runId);\n const attempt = runAttempt.then(() => \"settled\" as const);\n try {\n // A platform failure inside the budget rejects the race and re-enters\n // the driver's deferral path unchanged.\n const winner = await Promise.race([attempt, budget]);\n if (winner === \"budget\") {\n // Hand off the attempt's canonical promise — the one a later\n // claim-backstop wake finds in #active — so re-tracking is the\n // driver's documented no-op. The wrapper only unwinds it.\n this.lifecycle.trackAlarmWork(\n this.#active.get(runId)?.promise ?? runAttempt\n );\n return this.#wakeOutcome(runId);\n }\n } finally {\n clearTimeout(budgetTimer);\n }\n return this.#wakeOutcome(runId);\n }\n\n /**\n * Drive one routed dispatch to completion on this owning facet. There is\n * no local budget to race here: the root that sent this message races\n * its own await of the call instead, so a full await is safe regardless\n * of how long the attempt takes — the call keeps running on this facet\n * either way. An already-active attempt only needs its claim refreshed:\n * it is already tracked against whichever alarm's breaker domain\n * originally dispatched it (a root's pending routed call, or this\n * facet's own local alarm).\n */\n async #dispatchRoutedRun(runId: string): Promise<LifecycleJobOutcome> {\n const active = this.#active.get(runId);\n if (active) {\n this.#refreshClaim(runId);\n return this.#wakeOutcome(runId);\n }\n await this.#executeRun(runId);\n return this.#wakeOutcome(runId);\n }\n\n /**\n * Alarm memory-limit breaker policy (#1825) for the run whose wake struck.\n *\n * The run row is the durable source of truth: startup reconciliation\n * re-derives due-now wakes from it, so the breaker's queue-row backoff\n * and purge alone cannot contain a run whose attempt deterministically\n * exhausts memory — a fresh isolate would resurrect it immediately. On a\n * strike the run's claim is stripped and its deadline pushed to the\n * backoff wake: the row keeps its state, so a struck `running` row still\n * reads as an interrupted attempt (`step.interrupted`) when it is\n * reclaimed, while reconciliation leaves the claimless row alone instead\n * of flooring its deadline to now. When the breaker seals, the run\n * terminally fails with an observable `task:failed` outcome.\n */\n async onMemoryLimit(context: MemoryLimitContext): Promise<void> {\n const job = context.executing;\n if (job?.capability !== this.capabilityId) return;\n const timing = isTaskWakeJobPayload(job.payload) ? job.payload : undefined;\n const runId = timing?.runId ?? job.id.slice(WAKE_JOB_PREFIX.length);\n\n if (timing?.owner_path) {\n // The struck job was this root's mirror of a routed facet's wake; the\n // run row and its claim live on the facet, so the strike is forwarded\n // there to apply the same policy locally — clearing the claim and\n // backing off (or terminally failing, when sealed). Forwarding a\n // non-sealed strike too matters: this root's own mirror job backs off\n // on its own, but the facet's run row would otherwise keep its old\n // claim, and any facet startup before the backoff elapses would read\n // that claim as an interrupted attempt and reconcile it due again now\n // — resurrecting the run through the breaker.\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 { type: \"memoryLimit\", runId, context } satisfies TaskRouteMessage\n );\n } catch (error) {\n console.error(\n `Failed to route memory-limit policy for Task run \"${runId}\"`,\n error\n );\n }\n return;\n }\n await this.#applyMemoryLimit(runId, context);\n }\n\n /**\n * Apply the alarm memory-limit breaker policy (#1825) to one run, local to\n * whichever Lifecycle owns its storage — the root for an unrouted run, or\n * the owning facet when {@link onMemoryLimit} forwarded a routed strike.\n */\n async #applyMemoryLimit(\n runId: string,\n context: MemoryLimitContext\n ): Promise<void> {\n if (context.sealed) {\n await this.#settleFailed(runId, null, {\n name: \"TaskMemoryLimitSealed\",\n message:\n \"Sealed by the alarm memory-limit circuit breaker (#1825) after \" +\n \"consecutive Durable Object memory-limit resets.\"\n });\n return;\n }\n if (context.nextTime === undefined) return;\n const now = Date.now();\n this.#store.write(\n `UPDATE cf_agents_task_runs\n SET generation = NULL,\n next_at = CASE\n WHEN next_at IS NULL OR next_at < ? THEN ?\n ELSE next_at\n END,\n updated_at = ?\n WHERE run_id = ?\n AND state IN ('pending', 'waiting', 'running')`,\n [context.nextTime, context.nextTime, now, runId]\n );\n await this.#syncWake(runId);\n }\n\n /**\n * @internal Framework aperture: durably accept one run — reserved\n * (`__cf`-prefixed) definition names included, which the public `run()`\n * refuses so users cannot start framework runs — and drive its first\n * attempt in the caller's invocation, resolving when that attempt reaches\n * its next durable boundary. The receipt's run may already be terminal\n * when this resolves; callers that need the outcome read it from their own\n * channel (the run handler settles it) or from the snapshot.\n */\n async __DO_NOT_USE_WILL_BREAK__runAttached(\n definition: string,\n input: unknown,\n options?: TaskRunOptions\n ): Promise<TaskReceipt> {\n const receipt = await this.#acceptReserved(\n definition,\n input,\n options,\n \"attached\"\n );\n if (receipt.accepted) await this.#executeRun(receipt.runId);\n return receipt;\n }\n\n /**\n * @internal Framework aperture: durably accept one run — reserved names\n * included — and leave its first attempt to the durable queue wake instead\n * of warm-starting it in the caller's invocation. Chat recovery uses this\n * so a continuation always runs under an alarm, where `trackAlarmWork`\n * keeps its model turn inside the memory-limit breaker domain.\n */\n async __DO_NOT_USE_WILL_BREAK__enqueue(\n definition: string,\n input: unknown,\n options?: TaskRunOptions\n ): Promise<TaskReceipt> {\n return this.#acceptReserved(definition, input, options, \"queued\");\n }\n\n /** Accept a run of any resolvable definition, reserved names included. */\n async #acceptReserved(\n definition: string,\n input: unknown,\n options: TaskRunOptions | undefined,\n startMode: TaskStartMode\n ): Promise<TaskReceipt> {\n if (!this.#hasDefinition(definition)) {\n throw new Error(\n `Unknown Task definition \"${definition}\": not declared on this Tasks`\n );\n }\n return this.#accept(definition, input, options, startMode);\n }\n\n /**\n * The queue outcome for one run's wake job, derived from the run row's\n * authoritative `next_at` after dispatch. A same-id `#syncWake` push made\n * mid-drive supersedes this return at the queue (newer pushes win over\n * drive results), but both are computed from the same row, so the row is\n * the single source of truth for whether — and when — the run wakes\n * again either way.\n */\n #wakeOutcome(runId: string): LifecycleJobOutcome {\n const rows = this.#store.sql<{ next_at: number | null }>`\n SELECT next_at FROM cf_agents_task_runs\n WHERE run_id = ${runId}\n AND state IN ('pending', 'waiting', 'running')\n `;\n const next = rows[0]?.next_at;\n return typeof next === \"number\" ? { rescheduleAt: next } : undefined;\n }\n\n /**\n * Mirror one run's authoritative deadline into the Lifecycle job queue:\n * a non-terminal run with a `next_at` gets one job (id = `task:` plus the\n * run id, so a retime is a same-id replace); anything else cancels the\n * mirror. The prefix keeps caller-selected run IDs inside Tasks' own job\n * namespace. Every durable mutation of a run's deadline or state funnels\n * through here.\n *\n * @returns False when the queue already carried exactly this wake and\n * nothing was written — a same-values upsert is still a billed row write.\n */\n async #syncWake(runId: string): Promise<boolean> {\n const rows = this.#store.sql<{ next_at: number | null }>`\n SELECT next_at FROM cf_agents_task_runs\n WHERE run_id = ${runId}\n AND state IN ('pending', 'waiting', 'running')\n `;\n const next = rows[0]?.next_at ?? null;\n\n if (this.lifecycle.routes.source) {\n // The run row stays here; only its deadline mirrors to the root that\n // owns the physical alarm.\n return (await this.lifecycle.routes.toRoot({\n type: \"syncWake\",\n runId,\n next\n } satisfies TaskRouteMessage)) as boolean;\n }\n\n const jobId = `${WAKE_JOB_PREFIX}${runId}`;\n if (next === null) {\n await this.lifecycle.jobs.cancel(jobId);\n return true;\n }\n const existing = this.lifecycle.jobs.get(jobId);\n if (\n existing?.fn === WAKE_JOB_FN &&\n existing.time === next &&\n existing.retry?.maxAttempts === WAKE_JOB_RETRY.maxAttempts\n ) {\n return false;\n }\n await this.lifecycle.jobs.push({\n id: jobId,\n fn: WAKE_JOB_FN,\n time: next,\n payload: { runId } satisfies TaskWakeJobPayload,\n retry: WAKE_JOB_RETRY\n });\n return true;\n }\n\n /** Handle Tasks protocol messages routed by another Lifecycle. */\n async onRoute(context: LifecycleRouteContext): Promise<unknown> {\n const message = context.payload as TaskRouteMessage;\n switch (message.type) {\n case \"syncWake\": {\n const owner = context.source;\n if (!owner) throw new Error(\"Routed Tasks message missing source\");\n return this.#syncRoutedWake(owner, message.runId, message.next);\n }\n case \"dispatch\":\n return this.#dispatchRoutedRun(message.runId);\n case \"memoryLimit\": {\n await this.#applyMemoryLimit(message.runId, message.context);\n // The owner's own Lifecycle never observes the root's alarm; this\n // is its only path to the same `onAlarmMemoryLimit` host hook a\n // root's own local strike reaches through Lifecycle's alarm\n // dispatch.\n const handler = taskRoutedMemoryLimitHandlers.get(this);\n if (handler) {\n await this.lifecycle.runInHostContext(() => handler(message.context));\n }\n return true;\n }\n default:\n throw new Error(\"Unknown routed Tasks message\");\n }\n }\n\n /** Mirror a routed facet's run deadline into this root's job queue. */\n async #syncRoutedWake(\n owner: LifecycleRouteAddress,\n runId: string,\n next: number | null\n ): Promise<boolean> {\n const jobId = `${WAKE_JOB_PREFIX}${owner.key}:${runId}`;\n if (next === null) {\n await this.lifecycle.jobs.cancel(jobId);\n return true;\n }\n const existing = this.lifecycle.jobs.get(jobId);\n if (\n existing?.fn === WAKE_JOB_FN &&\n existing.time === next &&\n existing.retry?.maxAttempts === WAKE_JOB_RETRY.maxAttempts\n ) {\n return false;\n }\n await this.lifecycle.jobs.push({\n id: jobId,\n fn: WAKE_JOB_FN,\n time: next,\n payload: {\n runId,\n owner_path: owner.data,\n owner_path_key: owner.key\n } satisfies TaskWakeJobPayload,\n retry: WAKE_JOB_RETRY\n });\n return true;\n }\n\n /**\n * @internal Framework aperture: bulk-cancel this root's routed wake\n * mirrors for every run owned by a deleted facet subtree. The runs and\n * their step journals live on the deleted facets' own storage and are\n * wiped with them; only this root's mirror job needs an explicit cancel,\n * or it stays due forever, retrying a dispatch to a facet that is gone.\n */\n async __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(\n prefix: string\n ): Promise<void> {\n for (const job of this.lifecycle.jobs.list()) {\n const timing = isTaskWakeJobPayload(job.payload)\n ? job.payload\n : undefined;\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 await this.lifecycle.jobs.cancel(job.id);\n }\n }\n\n /** Mirror every non-terminal run into the queue (startup reconcile). */\n async #syncAllWakes(): Promise<void> {\n const rows = this.#store.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agents_task_runs\n WHERE state IN ('pending', 'waiting', 'running')\n AND next_at IS NOT NULL\n `;\n // On restart the mirror usually survived alongside the run row (same\n // storage), so most rows write nothing; wakes from before the one-attempt\n // policy are rewritten once.\n let pushed = false;\n for (const { run_id } of rows) {\n if (await this.#syncWake(run_id)) pushed = true;\n }\n // Pushes re-arm the physical alarm as a side effect; a reconcile that\n // wrote nothing must recover a lost alarm explicitly.\n if (rows.length > 0 && !pushed) await this.lifecycle.jobs.rearm();\n }\n\n // ── Inspection and control ───────────────────────────────────────────────\n\n /** Read one run by ID across all definitions. */\n async get(runId: string): Promise<TaskRunSnapshot<TaskValue> | null> {\n return this.#snapshot(runId);\n }\n\n /** Read one run by idempotency key across all definitions. */\n async getByIdempotencyKey(\n idempotencyKey: string\n ): Promise<TaskRunSnapshot<TaskValue> | null> {\n return this.#snapshotByKey(idempotencyKey);\n }\n\n /** List runs, newest first. */\n async list(\n options: TaskListOptions = {}\n ): Promise<TaskRunSnapshot<TaskValue>[]> {\n await this.lifecycle.ready();\n let query = \"SELECT * FROM cf_agents_task_runs WHERE 1 = 1\";\n const params: (string | number)[] = [];\n if (options.definition !== undefined) {\n query += \" AND definition = ?\";\n params.push(options.definition);\n }\n const states = Array.isArray(options.status)\n ? options.status\n : options.status !== undefined\n ? [options.status]\n : [];\n if (states.length > 0) {\n query += ` AND state IN (${states.map(() => \"?\").join(\", \")})`;\n params.push(...states);\n }\n query += \" ORDER BY created_at DESC, run_id DESC LIMIT ?\";\n params.push(options.limit ?? DEFAULT_LIST_LIMIT);\n let rows: unknown[];\n try {\n rows = this.lifecycle.storage.sql.exec(query, ...params).toArray();\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n // SAFETY: the query selects * from Tasks' own schema.\n return (rows as TaskRunRow[]).map((row) => this.#store.rowToSnapshot(row));\n }\n\n /**\n * Request cooperative cancellation of one run.\n *\n * A live attempt is aborted and settles as cancelled at its next step\n * boundary; a parked run settles immediately.\n *\n * @returns True when a non-terminal run accepted the request.\n */\n async cancel(runId: string, reason?: string): Promise<boolean> {\n await this.lifecycle.ready();\n const row = this.#store.getRun(runId);\n if (!row || TERMINAL_STATES.has(row.state)) return false;\n\n const active = this.#active.get(runId);\n if (active) {\n const now = Date.now();\n this.#store.sql`\n UPDATE cf_agents_task_runs\n SET cancel_requested = 1, cancel_reason = ${reason ?? null},\n next_at = ${now}, updated_at = ${now}\n WHERE run_id = ${runId}\n `;\n active.controller.abort(new TaskCancellation(reason));\n await this.#syncWake(runId);\n return true;\n }\n // A parked run settles in one write: #settleCancelled's UPDATE records\n // the request bits itself, so a separate request write would touch the\n // same row twice in the same synchronous block (one durable commit\n // either way — the split bought no crash evidence).\n await this.#settleCancelled(runId, null, reason);\n return true;\n }\n\n /**\n * Delete retained terminal runs and their step journals.\n *\n * @returns The number of runs deleted.\n */\n async delete(options: TaskDeleteOptions = {}): Promise<number> {\n await this.lifecycle.ready();\n const states = options.status ?? [\"completed\", \"failed\", \"cancelled\"];\n if (states.length === 0) return 0;\n let query = `SELECT run_id, definition FROM cf_agents_task_runs WHERE state IN (${states.map(() => \"?\").join(\", \")})`;\n const params: (string | number)[] = [...states];\n if (options.settledBefore) {\n query += \" AND settled_at < ?\";\n params.push(options.settledBefore.getTime());\n }\n query += \" ORDER BY settled_at ASC LIMIT ?\";\n params.push(options.limit ?? DEFAULT_LIST_LIMIT);\n let rows: unknown[];\n try {\n rows = this.lifecycle.storage.sql.exec(query, ...params).toArray();\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n for (const row of rows as Array<{ run_id: string; definition: string }>) {\n this.#store.deleteRun(row.run_id);\n this.#emit(\"task:deleted\", {\n runId: row.run_id,\n definition: row.definition\n });\n }\n return rows.length;\n }\n\n // ── Acceptance ───────────────────────────────────────────────────────────\n\n async #accept(\n definition: string,\n input: unknown,\n options: TaskRunOptions = {},\n startMode: TaskStartMode = \"warm\"\n ): Promise<TaskReceipt> {\n await this.lifecycle.ready();\n if (options.runId !== undefined && options.runId.length === 0) {\n throw new Error(\"runId must be a non-empty string when provided\");\n }\n if (\n options.idempotencyKey !== undefined &&\n options.idempotencyKey.length === 0\n ) {\n throw new Error(\n \"idempotencyKey must be a non-empty string when provided\"\n );\n }\n\n const inputJson = serializeTaskValue(\n input,\n `input for Task definition \"${definition}\"`\n );\n const metadataJson = serializeTaskValue(\n options.metadata,\n `metadata for Task definition \"${definition}\"`\n );\n\n const existing =\n (options.runId !== undefined\n ? this.#store.getRun(options.runId)\n : undefined) ??\n (options.idempotencyKey !== undefined\n ? this.#store.getRunByKey(options.idempotencyKey)\n : undefined);\n if (existing) {\n if (existing.definition !== definition) {\n throw new Error(\n `Task run \"${existing.run_id}\" already belongs to definition ` +\n `\"${existing.definition}\"; refusing to reuse its ` +\n `${options.runId !== undefined ? \"run ID\" : \"idempotency key\"} for ` +\n `\"${definition}\"`\n );\n }\n // The idempotency key is the deduplication authority: a run matched\n // by its key joins even when the caller requested a different (still\n // unused) runId — the receipt carries the real id. The reverse is a\n // conflict: a run matched by ID whose stored key differs from the\n // provided one would silently bind the caller's key to nothing.\n if (\n options.idempotencyKey !== undefined &&\n existing.idempotency_key !== options.idempotencyKey\n ) {\n throw new Error(\n `Task run \"${existing.run_id}\" carries idempotency key ` +\n `${existing.idempotency_key === null ? \"none\" : `\"${existing.idempotency_key}\"`}; ` +\n `refusing to join it with conflicting key \"${options.idempotencyKey}\"`\n );\n }\n // A prior accept can throw after already durably inserting this row —\n // most likely here, on the wake mirror, rather than on the insert\n // itself — so a caller retrying the same runId or idempotencyKey\n // after a failure needs this join to repair a missing or stale\n // mirror, not just report accepted:false against a row nothing will\n // ever wake.\n // A prior accept can throw after already durably inserting this row —\n // most likely here, on the wake mirror, rather than on the insert\n // itself — so a caller retrying the same runId or idempotencyKey\n // after a failure needs this join to repair a missing or stale\n // mirror, not just report accepted:false against a row nothing will\n // ever wake.\n await this.#syncWake(existing.run_id);\n return {\n runId: existing.run_id,\n definition,\n accepted: false,\n state: existing.state,\n createdAt: existing.created_at\n };\n }\n\n const runId = options.runId ?? `task_${nanoid()}`;\n const now = Date.now();\n this.#store.sql`\n INSERT INTO cf_agents_task_runs\n (run_id, definition, input, state, metadata, idempotency_key, retain,\n attempt, next_at, cancel_requested, created_at, updated_at)\n VALUES\n (${runId}, ${definition}, ${inputJson}, 'pending', ${metadataJson},\n ${options.idempotencyKey ?? null}, ${options.retain === false ? 0 : 1},\n 0, ${now}, 0, ${now}, ${now})\n `;\n await this.#syncWake(runId);\n this.#emit(\"task:accepted\", { runId, definition, accepted: true });\n\n // Warm path: begin the first attempt immediately when the host is past\n // startup. The durable deadline above is authoritative either way.\n if (startMode === \"warm\" && this.lifecycle.status() !== \"starting\") {\n void this.#executeRun(runId).catch(() => {});\n }\n\n return {\n runId,\n definition,\n accepted: true,\n state: \"pending\",\n createdAt: now\n };\n }\n\n // ── Execution ────────────────────────────────────────────────────────────\n\n /** Claim and drive one due run to its next durable boundary. */\n async #executeRun(runId: string): Promise<void> {\n if (this.#active.has(runId)) return;\n const row = this.#store.getRun(runId);\n if (!row || TERMINAL_STATES.has(row.state)) return;\n\n const now = Date.now();\n if (row.cancel_requested === 1) {\n await this.#settleCancelled(runId, null, row.cancel_reason ?? undefined);\n return;\n }\n if (row.next_at !== null && row.next_at > now) return;\n\n const handler = this.#resolveDefinition(row.definition);\n if (!handler) {\n const error = new MissingTaskDefinitionError(row.definition);\n console.error(error.message);\n await this.#settleFailed(runId, null, toErrorSummary(error));\n await this.#observeError(error);\n return;\n }\n\n // Unclean interruption: the previous attempt's isolate is gone. The\n // claim below replays the handler; completed steps return journaled\n // results, and the interrupted step rides `step.interrupted` as the\n // durable evidence the handler branches on.\n const interrupted =\n row.state === \"running\" ? this.#interruptedStep(runId) : null;\n if (row.state === \"running\") {\n this.#emit(\"task:attempt:interrupted\", {\n runId,\n definition: row.definition,\n attempt: row.attempt,\n step: interrupted?.name ?? null\n });\n }\n\n const generation = nanoid();\n const attempt = row.attempt + 1;\n this.#store.sql`\n UPDATE cf_agents_task_runs\n SET state = 'running', attempt = ${attempt}, generation = ${generation},\n started_at = coalesce(started_at, ${now}),\n next_at = ${now + this.#claimTimeoutMs()}, wait_reason = NULL,\n updated_at = ${now}\n WHERE run_id = ${runId}\n AND state IN ('pending', 'waiting', 'running')\n `;\n // Mirror the claim deadline before the handler runs, not after: a\n // routed run's root has no other way to learn it, and a push here\n // clears the queue row's in-flight marker, so it durably wins over a\n // root dispatch that later returns a stale outcome past its own\n // budget (job-queue's own \"newer pushes win\" guard on that marker).\n await this.#syncWake(runId);\n\n const controller = new AbortController();\n // Emitted before the handler starts: invocation is synchronous up to the\n // first await, so the first step event would otherwise precede this one.\n this.#emit(\"task:attempt:started\", {\n runId,\n definition: row.definition,\n attempt\n });\n const promise = this.#runAttempt(\n row,\n handler,\n generation,\n attempt,\n controller,\n interrupted,\n now\n );\n this.#active.set(runId, { generation, controller, promise });\n try {\n await promise;\n } finally {\n this.#active.delete(runId);\n }\n }\n\n /** Run one claimed attempt and persist its outcome, generation-fenced. */\n async #runAttempt(\n row: TaskRunRow,\n handler: TaskCallbacks[string],\n generation: string,\n attempt: number,\n controller: AbortController,\n interrupted: { name: string; attempt: number } | null,\n claimedAtMs: number\n ): Promise<void> {\n const runId = row.run_id;\n const input = deserializeTaskValue(row.input);\n const engine = this.#createEngine(\n runId,\n row.definition,\n generation,\n controller,\n claimedAtMs\n );\n const step = new ReplayStep(engine, {\n startsLive: attempt === 1,\n interrupted\n });\n\n try {\n const output = await this.lifecycle.runInHostContext(() =>\n handler(input, step)\n );\n const resultJson = serializeTaskValue(\n output,\n `result of Task definition \"${row.definition}\"`\n );\n const settled = this.#store.fencedWrite(\n runId,\n generation,\n `UPDATE cf_agents_task_runs\n SET state = 'completed', result = ?, generation = NULL, next_at = NULL,\n settled_at = ?, updated_at = ?\n WHERE run_id = ? AND generation = ? AND state = 'running'`,\n [resultJson, Date.now(), Date.now()]\n );\n if (settled) {\n this.#emit(\"task:completed\", { runId, definition: row.definition });\n await this.#finishTerminalSettlement(runId, row);\n }\n // Fence rejected: a newer generation owns the run, and every deadline\n // mutation it makes funnels through its own #syncWake — a push here\n // would be a redundant job-row write.\n } catch (thrown) {\n await this.#settleThrown(row, generation, thrown);\n }\n }\n\n /** Persist a non-completed attempt outcome. */\n async #settleThrown(\n row: TaskRunRow,\n generation: string,\n thrown: unknown\n ): Promise<void> {\n const runId = row.run_id;\n\n if (thrown instanceof AttemptSupersededError) {\n // A newer attempt owns the run; this one unwinds without settling.\n return;\n }\n\n if (isPlatformFailure(thrown)) {\n // Platform-class failure (superseded isolate, memory-limit reset,\n // storage transient): not an application outcome, so the run must not\n // settle. Unwind and rethrow — the claim backstop written at claim\n // time is the durable wake, and the next invocation reclaims and\n // replays the run; a queue-driven dispatch defers through the\n // driver's platform-failure path.\n throw thrown;\n }\n\n if (isTaskCancellation(thrown)) {\n await this.#settleCancelled(runId, generation, thrown.reason);\n return;\n }\n\n if (isTaskSuspension(thrown)) {\n // A cancel requested mid-attempt wins over parking the run.\n const current = this.#store.getRun(runId);\n if (current?.cancel_requested === 1) {\n await this.#settleCancelled(\n runId,\n generation,\n current.cancel_reason ?? undefined\n );\n return;\n }\n const suspended = this.#store.fencedWrite(\n runId,\n generation,\n `UPDATE cf_agents_task_runs\n SET state = 'waiting', wait_reason = ?, next_at = ?, generation = NULL,\n updated_at = ?\n WHERE run_id = ? AND generation = ? AND state = 'running'`,\n [thrown.reason, thrown.wakeAt, Date.now()]\n );\n if (suspended) {\n this.#emit(\"task:waiting\", {\n runId,\n definition: row.definition,\n reason: thrown.reason,\n wakeAt: thrown.wakeAt\n });\n await this.#syncWake(runId);\n }\n return;\n }\n\n const summary = toErrorSummary(thrown);\n const failed = await this.#settleFailed(runId, generation, summary);\n if (failed) {\n console.error(\n `Task run \"${runId}\" (definition \"${row.definition}\") failed: ${summary.name}: ${summary.message}`\n );\n }\n await this.#observeError(thrown);\n }\n\n async #observeError(error: unknown): Promise<void> {\n if (!this.#onError) return;\n try {\n // Observing terminal failures is host-facing user code: run it inside\n // the host invocation boundary, like definition handlers.\n await this.lifecycle.runInHostContext(() => this.#onError?.(error));\n } catch {\n // swallow onError errors\n }\n }\n\n // ── Step engine port ─────────────────────────────────────────────────────\n\n #createEngine(\n runId: string,\n definition: string,\n generation: string,\n controller: AbortController,\n claimedAtMs: number\n ): TaskStepEngine {\n return createTaskStepEngine({\n store: this.#store,\n runId,\n generation,\n signal: controller.signal,\n claimTimeoutMs: () => this.#claimTimeoutMs(),\n claimedAtMs,\n claimRefreshAfterMs: CLAIM_SLACK_MS / 2,\n defaults: this.#stepDefaults,\n emit: (type, payload) =>\n this.#emit(type as TaskEventType, { runId, definition, ...payload })\n });\n }\n\n /** The step a lost attempt left mid-execution — replay-entry evidence. */\n #interruptedStep(runId: string): { name: string; attempt: number } | null {\n const rows = this.#store.sql<{ step_name: string; attempt: number }>`\n SELECT step_name, attempt FROM cf_agents_task_steps\n WHERE run_id = ${runId} AND state = 'running'\n ORDER BY started_at DESC\n LIMIT 1\n `;\n return rows[0]\n ? { name: rows[0].step_name, attempt: rows[0].attempt }\n : null;\n }\n\n /**\n * Settle one run as cancelled and sync its queue mirror. Fenced when a\n * generation is supplied.\n */\n async #settleCancelled(\n runId: string,\n generation: string | null,\n reason: string | undefined\n ): Promise<void> {\n const now = Date.now();\n let settled: boolean;\n if (generation !== null) {\n settled = this.#store.fencedWrite(\n runId,\n generation,\n `UPDATE cf_agents_task_runs\n SET state = 'cancelled', cancel_requested = 1, cancel_reason = ?,\n generation = NULL, next_at = NULL, settled_at = ?, updated_at = ?\n WHERE run_id = ? AND generation = ?\n AND state = 'running'`,\n [reason ?? null, now, now]\n );\n } else {\n const written = this.#store.write(\n `UPDATE cf_agents_task_runs\n SET state = 'cancelled', cancel_requested = 1, cancel_reason = ?,\n generation = NULL, next_at = NULL, settled_at = ?, updated_at = ?\n WHERE run_id = ?\n AND state IN ('pending', 'waiting', 'running')`,\n [reason ?? null, now, now, runId]\n );\n settled = written > 0;\n }\n const row = settled ? this.#store.getRun(runId) : undefined;\n if (row) {\n this.#emit(\"task:cancelled\", {\n runId,\n definition: row.definition,\n reason: reason ?? null\n });\n await this.#finishTerminalSettlement(runId, row);\n }\n }\n\n /**\n * Settle one run as failed and sync its queue mirror. Fenced when a\n * generation is supplied.\n */\n async #settleFailed(\n runId: string,\n generation: string | null,\n error: { name: string; message: string }\n ): Promise<boolean> {\n const now = Date.now();\n let settled: boolean;\n if (generation !== null) {\n settled = this.#store.fencedWrite(\n runId,\n generation,\n `UPDATE cf_agents_task_runs\n SET state = 'failed', error_name = ?, error_message = ?,\n generation = NULL, next_at = NULL, settled_at = ?, updated_at = ?\n WHERE run_id = ? AND generation = ?\n AND state = 'running'`,\n [error.name, error.message, now, now]\n );\n } else {\n const written = this.#store.write(\n `UPDATE cf_agents_task_runs\n SET state = 'failed', error_name = ?, error_message = ?,\n generation = NULL, next_at = NULL, settled_at = ?, updated_at = ?\n WHERE run_id = ?\n AND state IN ('pending', 'waiting', 'running')`,\n [error.name, error.message, now, now, runId]\n );\n settled = written > 0;\n }\n const row = settled ? this.#store.getRun(runId) : undefined;\n if (row) {\n this.#emit(\"task:failed\", {\n runId,\n definition: row.definition,\n error: error.name\n });\n await this.#finishTerminalSettlement(runId, row);\n }\n return settled;\n }\n\n /** Apply terminal retention policy, then remove the run's wake mirror. */\n async #finishTerminalSettlement(\n runId: string,\n row: TaskRunRow | undefined\n ): Promise<void> {\n if (row?.retain === 0) this.#store.deleteRun(runId);\n await this.#syncWake(runId);\n }\n\n /** Make deadlines sane after a fresh isolate: interrupted work wakes now. */\n #reconcile(): void {\n const now = Date.now();\n // A fresh isolate has no live attempts, so every claimed row is an\n // interrupted attempt: make it due immediately for reclaim and replay.\n this.#store.sql`\n UPDATE cf_agents_task_runs SET next_at = ${now}, updated_at = ${now}\n WHERE state = 'running' AND generation IS NOT NULL\n `;\n // Non-terminal rows must always carry a deadline; repair any without one.\n this.#store.sql`\n UPDATE cf_agents_task_runs SET next_at = ${now}, updated_at = ${now}\n WHERE state IN ('pending', 'waiting') AND next_at IS NULL\n `;\n }\n\n // ── Snapshots ────────────────────────────────────────────────────────────\n\n async #snapshot<Output extends TaskValue>(\n runId: string,\n definition?: string\n ): Promise<TaskRunSnapshot<Output> | null> {\n await this.lifecycle.ready();\n const row = this.#store.getRun(runId);\n if (!row) return null;\n if (definition !== undefined && row.definition !== definition) return null;\n return this.#store.rowToSnapshot<Output>(row);\n }\n\n async #snapshotByKey<Output extends TaskValue>(\n idempotencyKey: string,\n definition?: string\n ): Promise<TaskRunSnapshot<Output> | null> {\n await this.lifecycle.ready();\n const row = this.#store.getRunByKey(idempotencyKey);\n if (!row) return null;\n if (definition !== undefined && row.definition !== definition) return null;\n return this.#store.rowToSnapshot<Output>(row);\n }\n\n #emit(type: TaskEventType | string, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAcA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB,SAA+B;EAC1D,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;AAGA,SAAgB,oBAAoB,OAAyB;CAC3D,OACE,iBAAiB,qBAChB,iBAAiB,SAAS,MAAM,SAAS;AAE9C;;;;;;;AAQA,IAAa,yBAAb,cAA4C,MAAM;CAIhD,YAAY,UAAkB;EAC5B,MACE,cAAc,SAAS,oHAEjB,SAAS,KACjB;EACA,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;;;;;;;;AAUA,IAAa,0BAAb,cAA6C,MAAM;CAIjD,YAAY,UAAkB,QAAgB;EAC5C,MACE,6CAA6C,SAAS,KAAK,OAAO,sGAGpE;EACA,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;;;;;;;A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AA,kBAAA,cAAA,IAAA,CAAU,CAAC,CAAC,GAAG;iDAC8B,IAAI,iBAAiB,IAAI;;;AAGxE;AAIA,eAAA,UACE,OACA,YACyC;CACzC,MAAM,KAAK,UAAU,MAAM;CAC3B,MAAM,MAAA,WAAA,KAAA,kBAAA,cAAM,IAAA,CAAU,CAAC,CAAC,OAAO,KAAK;CACpC,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,eAAe,KAAA,KAAa,IAAI,eAAe,YAAY,OAAO;CACtE,OAAA,WAAA,KAAA,kBAAA,cAAO,IAAA,CAAU,CAAC,CAAC,cAAsB,GAAG;AAC9C;AAEA,eAAA,eACE,gBACA,YACyC;CACzC,MAAM,KAAK,UAAU,MAAM;CAC3B,MAAM,MAAA,WAAA,KAAA,kBAAA,cAAM,IAAA,CAAU,CAAC,CAAC,YAAY,cAAc;CAClD,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,eAAe,KAAA,KAAa,IAAI,eAAe,YAAY,OAAO;CACtE,OAAA,WAAA,KAAA,kBAAA,cAAO,IAAA,CAAU,CAAC,CAAC,cAAsB,GAAG;AAC9C;AAEA,SAAA,MAAM,MAA8B,SAAwC;CAC1E,KAAK,UAAU,OAAO,KAAK,MAAM,OAAO;AAC1C"}
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
o as MemoryLimitContext,
|
|
5
5
|
s as LifecycleCapability,
|
|
6
6
|
v as LifecycleJobOutcome
|
|
7
|
-
} from "./capability-runner-
|
|
7
|
+
} from "./capability-runner-BiVUtjqC.js";
|
|
8
8
|
|
|
9
9
|
//#region src/tasks/duration.d.ts
|
|
10
10
|
/**
|
|
@@ -514,4 +514,4 @@ export {
|
|
|
514
514
|
TaskWaitReason as x,
|
|
515
515
|
TaskStepConfig as y
|
|
516
516
|
};
|
|
517
|
-
//# sourceMappingURL=tasks-
|
|
517
|
+
//# sourceMappingURL=tasks-E89KdwkS.d.ts.map
|