agents 0.24.0 → 0.26.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.
Files changed (170) hide show
  1. package/dist/{agent-routing-B2XLNMxq.d.ts → agent-routing-0DR0Tk2v.d.ts} +205 -132
  2. package/dist/agent-routing.d.ts +1 -1
  3. package/dist/agent-routing.js.map +1 -1
  4. package/dist/agent-tool-types.d.ts +28 -22
  5. package/dist/agent-tool-types.js +23 -1
  6. package/dist/agent-tool-types.js.map +1 -1
  7. package/dist/{agent-tools-y7zLfw4Q.js → agent-tools-CdJC-8Dc.js} +72 -9
  8. package/dist/agent-tools-CdJC-8Dc.js.map +1 -0
  9. package/dist/{agent-tools-Dj5Mzlw7.d.ts → agent-tools-YrATZJu2.d.ts} +34 -20
  10. package/dist/agent-tools.d.ts +20 -18
  11. package/dist/agent-tools.js.map +1 -1
  12. package/dist/ai-fm7xx1BK.js +312 -0
  13. package/dist/ai-fm7xx1BK.js.map +1 -0
  14. package/dist/base64-redaction-C1Uu29t5.js +59 -0
  15. package/dist/base64-redaction-C1Uu29t5.js.map +1 -0
  16. package/dist/browser/ai-sdk.d.ts +90 -0
  17. package/dist/browser/ai-sdk.js +51 -0
  18. package/dist/browser/ai-sdk.js.map +1 -0
  19. package/dist/browser/ai.d.ts +4 -4
  20. package/dist/browser/ai.js +1 -347
  21. package/dist/browser/index.d.ts +81 -79
  22. package/dist/browser/index.js +361 -2
  23. package/dist/browser/index.js.map +1 -0
  24. package/dist/browser/tanstack-ai.d.ts +96 -1
  25. package/dist/browser/tanstack-ai.js +62 -2
  26. package/dist/browser/tanstack-ai.js.map +1 -1
  27. package/dist/browser-DE3d-RLk.d.ts +275 -0
  28. package/dist/browser-tool-CQ10e6Kj.js +480 -0
  29. package/dist/browser-tool-CQ10e6Kj.js.map +1 -0
  30. package/dist/browser-tool-DuNdlwZ9.d.ts +73 -0
  31. package/dist/capability-B4WbF81e.js.map +1 -1
  32. package/dist/{capability-runner-BUBa6Ake.d.ts → capability-runner-DBAnGr6L.d.ts} +7 -2
  33. package/dist/chat/index.d.ts +340 -234
  34. package/dist/chat/index.js +592 -66
  35. package/dist/chat/index.js.map +1 -1
  36. package/dist/chat/react.d.ts +42 -2
  37. package/dist/chat/react.js +191 -35
  38. package/dist/chat/react.js.map +1 -1
  39. package/dist/chat/transport.d.ts +1 -1
  40. package/dist/chat/transport.js +1 -1
  41. package/dist/chat-sdk/index.d.ts +17 -3
  42. package/dist/chat-sdk/index.js +28 -2
  43. package/dist/chat-sdk/index.js.map +1 -1
  44. package/dist/{client-C9DAjZIY.js → client-4OlMIJx-.js} +102 -29
  45. package/dist/client-4OlMIJx-.js.map +1 -0
  46. package/dist/{client-BxdkCuVy.d.ts → client-je3koD9Z.d.ts} +45 -10
  47. package/dist/client.d.ts +7 -5
  48. package/dist/client.js +2 -2
  49. package/dist/{connector-CptFKzRh.js → connector-58XDGvc3.js} +251 -120
  50. package/dist/connector-58XDGvc3.js.map +1 -0
  51. package/dist/{connector-CkQD4MK3.d.ts → connector-Cl-VqPmA.d.ts} +244 -146
  52. package/dist/context/index.d.ts +29 -0
  53. package/dist/context/index.js +64 -17
  54. package/dist/context/index.js.map +1 -1
  55. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  56. package/dist/{current-agent-C4w86kcN.d.ts → current-agent-vAk_5JMt.d.ts} +4 -4
  57. package/dist/{durable-object-lifecycle-ei7M7lqB.d.ts → durable-object-lifecycle-HhgOMWq9.d.ts} +15 -7
  58. package/dist/harness/pi/index.d.ts +344 -0
  59. package/dist/harness/pi/index.js +873 -0
  60. package/dist/harness/pi/index.js.map +1 -0
  61. package/dist/images-iiTDSyRu.js +1631 -0
  62. package/dist/images-iiTDSyRu.js.map +1 -0
  63. package/dist/{index-Dlgtd3Mj.d.ts → index-BreL0YrQ.d.ts} +2 -2
  64. package/dist/index-kbSUIer3.d.ts +343 -0
  65. package/dist/index.d.ts +46 -44
  66. package/dist/index.js +1 -1
  67. package/dist/internal_context.d.ts +1 -1
  68. package/dist/lifecycle/index.d.ts +3 -3
  69. package/dist/lifecycle/index.js +1 -1
  70. package/dist/{lifecycle-Mm_jQh7r.js → lifecycle-CFu6OV03.js} +39 -10
  71. package/dist/{lifecycle-Mm_jQh7r.js.map → lifecycle-CFu6OV03.js.map} +1 -1
  72. package/dist/mcp/client/index.d.ts +20 -20
  73. package/dist/mcp/client/x402.js +21 -19
  74. package/dist/mcp/client/x402.js.map +1 -1
  75. package/dist/mcp/index.d.ts +35 -35
  76. package/dist/mcp/index.js +1 -1
  77. package/dist/{message-builder-BymO4N_D.js → message-builder-DAl9AhHH.js} +89 -4
  78. package/dist/message-builder-DAl9AhHH.js.map +1 -0
  79. package/dist/models/ai-sdk/index.d.ts +353 -0
  80. package/dist/models/ai-sdk/index.js +2443 -0
  81. package/dist/models/ai-sdk/index.js.map +1 -0
  82. package/dist/models/pi-ai/index.d.ts +313 -0
  83. package/dist/models/pi-ai/index.js +1795 -0
  84. package/dist/models/pi-ai/index.js.map +1 -0
  85. package/dist/observability/ai/index.js +20 -4
  86. package/dist/observability/ai/index.js.map +1 -1
  87. package/dist/{protocol-B0nh6KNf.js → protocol-kHsr-f0X.js} +26 -12
  88. package/dist/{protocol-B0nh6KNf.js.map → protocol-kHsr-f0X.js.map} +1 -1
  89. package/dist/queue/index.d.ts +3 -3
  90. package/dist/queue/index.js +1 -1
  91. package/dist/{queue-BC9F5cUo.js → queue-BB-zfIYF.js} +2 -2
  92. package/dist/{queue-BC9F5cUo.js.map → queue-BB-zfIYF.js.map} +1 -1
  93. package/dist/react.d.ts +6 -6
  94. package/dist/react.js +160 -64
  95. package/dist/react.js.map +1 -1
  96. package/dist/{retries-D9B2UCq3.d.ts → retries-CV6AkXmQ.d.ts} +18 -9
  97. package/dist/retries.d.ts +11 -9
  98. package/dist/retries.js +11 -1
  99. package/dist/retries.js.map +1 -1
  100. package/dist/routing/index.d.ts +2 -2
  101. package/dist/routing/index.js +1 -1
  102. package/dist/{scheduler-D_KHqxBa.js → scheduler-DZ3xQfeK.js} +2 -2
  103. package/dist/{scheduler-D_KHqxBa.js.map → scheduler-DZ3xQfeK.js.map} +1 -1
  104. package/dist/{scheduler-BGq6M5Kd.d.ts → scheduler-RdACNXDP.d.ts} +3 -3
  105. package/dist/schedules/index.d.ts +1 -1
  106. package/dist/schedules/index.js +1 -1
  107. package/dist/serializable.d.ts +1 -1
  108. package/dist/sessions/index.d.ts +70 -3
  109. package/dist/sessions/index.js +276 -67
  110. package/dist/sessions/index.js.map +1 -1
  111. package/dist/skills/index.d.ts +29 -314
  112. package/dist/socket-address.d.ts +16 -0
  113. package/dist/socket-address.js +19 -0
  114. package/dist/socket-address.js.map +1 -0
  115. package/dist/{src-BNU3ZiJM.js → src-BZeu-SCD.js} +423 -115
  116. package/dist/src-BZeu-SCD.js.map +1 -0
  117. package/dist/state/index.d.ts +1 -1
  118. package/dist/state/index.js +1 -1
  119. package/dist/streams/index.d.ts +1 -1
  120. package/dist/streams/index.js +1 -1
  121. package/dist/{streams-BcE8JP2X.d.ts → streams-Cmkj9QfW.d.ts} +4 -2
  122. package/dist/{streams-CCPRV6dt.js → streams-DW-UCOUc.js} +9 -2
  123. package/dist/streams-DW-UCOUc.js.map +1 -0
  124. package/dist/sub-routing.d.ts +12 -12
  125. package/dist/tasks/index.d.ts +1 -1
  126. package/dist/tasks/index.js +1 -1
  127. package/dist/{tasks-D4nLqVSI.js → tasks-68DESxf0.js} +2 -2
  128. package/dist/{tasks-D4nLqVSI.js.map → tasks-68DESxf0.js.map} +1 -1
  129. package/dist/{tasks-V2lCT8ZV.d.ts → tasks-9YxYtByh.d.ts} +2 -2
  130. package/dist/transport-PfFnt-Ld.d.ts +525 -0
  131. package/dist/{types-DCD6BNZH.d.ts → types-BA4anrjI.d.ts} +2 -2
  132. package/dist/voice/index.d.ts +2 -2
  133. package/dist/websockets/index.d.ts +23 -6
  134. package/dist/websockets/index.js +1 -1
  135. package/dist/{websockets-D7IzWbZb.js → websockets-Ci-LZFHH.js} +45 -20
  136. package/dist/{websockets-D7IzWbZb.js.map → websockets-Ci-LZFHH.js.map} +1 -1
  137. package/dist/wire-types-CnMt6_HR.js.map +1 -1
  138. package/dist/wire-types-CrjKvDyi.d.ts +300 -0
  139. package/dist/workflow-types.d.ts +25 -25
  140. package/dist/workflows.d.ts +21 -21
  141. package/dist/workflows.js +1 -1
  142. package/dist/{ws-chat-transport-UNRIS2xl.d.ts → ws-chat-transport-BbT1A5Lc.d.ts} +51 -2
  143. package/dist/{ws-chat-transport-rWwta645.js → ws-chat-transport-cqMKq3IY.js} +143 -16
  144. package/dist/ws-chat-transport-cqMKq3IY.js.map +1 -0
  145. package/docs/agent-tools.md +29 -4
  146. package/docs/browse-the-web.md +87 -5
  147. package/docs/chat-agents.md +124 -16
  148. package/docs/context.md +27 -0
  149. package/docs/durable-execution.md +2 -0
  150. package/docs/harnesses/pi.md +173 -0
  151. package/docs/human-in-the-loop.md +4 -0
  152. package/docs/index.md +3 -0
  153. package/docs/lifecycle.md +20 -4
  154. package/docs/models-pi-ai.md +325 -0
  155. package/docs/models.md +504 -0
  156. package/docs/resumable-streaming.md +2 -0
  157. package/docs/routing.md +13 -13
  158. package/docs/sessions.md +36 -1
  159. package/docs/state.md +1 -0
  160. package/docs/sub-agents.md +9 -0
  161. package/package.json +40 -2
  162. package/dist/agent-tools-y7zLfw4Q.js.map +0 -1
  163. package/dist/browser/ai.js.map +0 -1
  164. package/dist/client-C9DAjZIY.js.map +0 -1
  165. package/dist/client-tools-aIBO0Fk7.d.ts +0 -53
  166. package/dist/connector-CptFKzRh.js.map +0 -1
  167. package/dist/message-builder-BymO4N_D.js.map +0 -1
  168. package/dist/src-BNU3ZiJM.js.map +0 -1
  169. package/dist/streams-CCPRV6dt.js.map +0 -1
  170. package/dist/ws-chat-transport-rWwta645.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { t as applyChunkToParts } from "./message-builder-BymO4N_D.js";
1
+ import { t as applyChunkToParts } from "./message-builder-DAl9AhHH.js";
2
2
  //#region src/chat/stream-accumulator.ts
3
3
  function asMetadata(value) {
4
4
  if (value != null && typeof value === "object" && !Array.isArray(value)) return value;
@@ -139,6 +139,22 @@ var StreamAccumulator = class {
139
139
  };
140
140
  //#endregion
141
141
  //#region src/chat/broadcast-state.ts
142
+ function textOf(parts) {
143
+ let text = "";
144
+ for (const part of parts) if (part.type === "text") text += part.text;
145
+ return text;
146
+ }
147
+ /**
148
+ * Whether `messages` already holds a copy of the observed message whose text
149
+ * the accumulator does not extend. A healthy live accumulator is always the
150
+ * stored copy plus more; one that diverges holds interleaved or duplicated
151
+ * chunks (#2166), so the stored copy must win or the corruption never heals.
152
+ */
153
+ function observedDivergesFrom(accumulator, messages) {
154
+ const existing = messages.find((m) => m.id === accumulator.messageId);
155
+ if (!existing) return false;
156
+ return !textOf(accumulator.parts).startsWith(textOf(existing.parts));
157
+ }
142
158
  function transition(state, event) {
143
159
  switch (event.type) {
144
160
  case "clear": return {
@@ -166,15 +182,13 @@ function transition(state, event) {
166
182
  else accumulator = state.accumulator;
167
183
  if (event.chunkData) accumulator.applyChunk(event.chunkData);
168
184
  let messagesUpdate;
169
- if (event.done) {
170
- messagesUpdate = (prev) => accumulator.mergeInto(prev);
171
- return {
172
- state: { status: "idle" },
173
- messagesUpdate,
174
- isStreaming: false
175
- };
176
- }
177
- if (event.chunkData && !event.replay) messagesUpdate = (prev) => accumulator.mergeInto(prev);
185
+ const mergeUnlessDiverged = (prev) => observedDivergesFrom(accumulator, prev) ? prev : accumulator.mergeInto(prev);
186
+ if (event.done) return {
187
+ state: { status: "idle" },
188
+ messagesUpdate: mergeUnlessDiverged,
189
+ isStreaming: false
190
+ };
191
+ if (event.chunkData && !event.replay) messagesUpdate = mergeUnlessDiverged;
178
192
  else if (event.replayComplete) messagesUpdate = (prev) => accumulator.mergeInto(prev);
179
193
  return {
180
194
  state: {
@@ -220,6 +234,6 @@ const CHAT_MESSAGE_TYPES = {
220
234
  CHAT_RECOVERING: "cf_agent_chat_recovering"
221
235
  };
222
236
  //#endregion
223
- export { StreamAccumulator as i, STREAM_RESUME_NONE_REASONS as n, transition as r, CHAT_MESSAGE_TYPES as t };
237
+ export { StreamAccumulator as a, transition as i, STREAM_RESUME_NONE_REASONS as n, observedDivergesFrom as r, CHAT_MESSAGE_TYPES as t };
224
238
 
225
- //# sourceMappingURL=protocol-B0nh6KNf.js.map
239
+ //# sourceMappingURL=protocol-kHsr-f0X.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-B0nh6KNf.js","names":[],"sources":["../src/chat/stream-accumulator.ts","../src/chat/broadcast-state.ts","../src/chat/protocol.ts"],"sourcesContent":["/**\n * StreamAccumulator — unified chunk-to-message builder.\n *\n * Used by @cloudflare/ai-chat (server + client) and @cloudflare/think\n * to incrementally build a UIMessage from stream chunks. Wraps\n * applyChunkToParts and handles the metadata chunk types (start, finish,\n * message-metadata, error) that applyChunkToParts does not cover.\n *\n * The accumulator signals domain-specific concerns (early persistence,\n * cross-message tool updates) via ChunkAction returns — callers handle\n * these according to their context.\n */\n\nimport type { UIMessage } from \"ai\";\nimport { applyChunkToParts, type StreamChunkData } from \"./message-builder\";\n\nfunction asMetadata(value: unknown): Record<string, unknown> | undefined {\n if (value != null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n return undefined;\n}\n\nexport interface StreamAccumulatorOptions {\n messageId: string;\n /** Whether chunks continue the current assistant message when merged. */\n continuation?: boolean;\n /** Eager seed; omitted continuations seed from the messages passed to `mergeInto`. */\n existingParts?: UIMessage[\"parts\"];\n existingMetadata?: Record<string, unknown>;\n}\n\nexport type ChunkAction =\n | {\n type: \"start\";\n messageId?: string;\n metadata?: Record<string, unknown>;\n }\n | {\n type: \"finish\";\n finishReason?: string;\n metadata?: Record<string, unknown>;\n }\n | { type: \"message-metadata\"; metadata: Record<string, unknown> }\n | { type: \"tool-approval-request\"; toolCallId: string }\n | {\n type: \"cross-message-tool-update\";\n updateType: \"output-available\" | \"output-error\";\n toolCallId: string;\n output?: unknown;\n errorText?: string;\n preliminary?: boolean;\n }\n | { type: \"error\"; error: string };\n\nexport interface ChunkResult {\n handled: boolean;\n action?: ChunkAction;\n}\n\nexport class StreamAccumulator {\n messageId: string;\n readonly parts: UIMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n private _isContinuation: boolean;\n // Continuation chunks wait here until mergeInto can seed from current state.\n private _pendingContinuationChunks: StreamChunkData[] | null;\n\n constructor(options: StreamAccumulatorOptions) {\n this.messageId = options.messageId;\n this._isContinuation = options.continuation ?? false;\n this.parts = options.existingParts ? [...options.existingParts] : [];\n this.metadata = options.existingMetadata\n ? { ...options.existingMetadata }\n : undefined;\n this._pendingContinuationChunks =\n this._isContinuation &&\n options.existingParts === undefined &&\n options.existingMetadata === undefined\n ? []\n : null;\n }\n\n applyChunk(chunk: StreamChunkData): ChunkResult {\n this._pendingContinuationChunks?.push(chunk);\n const handled = applyChunkToParts(this.parts, chunk);\n\n // Detect tool-approval-request for early persistence signaling\n if (chunk.type === \"tool-approval-request\" && chunk.toolCallId) {\n return {\n handled,\n action: { type: \"tool-approval-request\", toolCallId: chunk.toolCallId }\n };\n }\n\n // Detect cross-message tool output/error: applyChunkToParts returns true\n // for recognized types but silently does nothing when the toolCallId\n // doesn't exist in the current parts array.\n if (\n (chunk.type === \"tool-output-available\" ||\n chunk.type === \"tool-output-error\") &&\n chunk.toolCallId\n ) {\n const foundInParts = this.parts.some(\n (p) => \"toolCallId\" in p && p.toolCallId === chunk.toolCallId\n );\n if (!foundInParts) {\n return {\n handled,\n action: {\n type: \"cross-message-tool-update\",\n updateType:\n chunk.type === \"tool-output-available\"\n ? \"output-available\"\n : \"output-error\",\n toolCallId: chunk.toolCallId,\n output: chunk.output,\n errorText: chunk.errorText,\n preliminary: chunk.preliminary\n }\n };\n }\n }\n\n if (!handled) {\n switch (chunk.type) {\n case \"start\": {\n if (chunk.messageId != null && !this._isContinuation) {\n this.messageId = chunk.messageId;\n }\n const startMeta = asMetadata(chunk.messageMetadata);\n if (startMeta) {\n this.metadata = this.metadata\n ? { ...this.metadata, ...startMeta }\n : { ...startMeta };\n }\n return {\n handled: true,\n action: {\n type: \"start\",\n messageId: chunk.messageId,\n metadata: startMeta\n }\n };\n }\n case \"finish\": {\n const finishMeta = asMetadata(chunk.messageMetadata);\n if (finishMeta) {\n this.metadata = this.metadata\n ? { ...this.metadata, ...finishMeta }\n : { ...finishMeta };\n }\n const finishReason =\n \"finishReason\" in chunk\n ? (chunk.finishReason as string)\n : undefined;\n return {\n handled: true,\n action: {\n type: \"finish\",\n finishReason,\n metadata: finishMeta\n }\n };\n }\n case \"message-metadata\": {\n const msgMeta = asMetadata(chunk.messageMetadata);\n if (msgMeta) {\n this.metadata = this.metadata\n ? { ...this.metadata, ...msgMeta }\n : { ...msgMeta };\n }\n return {\n handled: true,\n action: {\n type: \"message-metadata\",\n metadata: msgMeta ?? {}\n }\n };\n }\n case \"finish-step\": {\n return { handled: true };\n }\n case \"error\": {\n return {\n handled: true,\n action: {\n type: \"error\",\n error: chunk.errorText ?? JSON.stringify(chunk)\n }\n };\n }\n }\n }\n\n return { handled };\n }\n\n /** Snapshot the current state as a UIMessage. */\n toMessage(): UIMessage {\n return {\n id: this.messageId,\n role: \"assistant\",\n parts: [...this.parts],\n ...(this.metadata != null && { metadata: this.metadata })\n } as UIMessage;\n }\n\n /**\n * Merge this accumulator's message into an existing message array.\n * Handles continuation (walk backward for last assistant), replacement\n * (update existing by messageId), or append (new message). An unseeded\n * continuation adopts current parts here before applying its queued chunks.\n */\n mergeInto(messages: UIMessage[]): UIMessage[] {\n let existingIdx = messages.findIndex((m) => m.id === this.messageId);\n\n if (existingIdx < 0 && this._isContinuation) {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n existingIdx = i;\n break;\n }\n }\n }\n\n if (this._pendingContinuationChunks !== null) {\n const pendingChunks = this._pendingContinuationChunks;\n this._pendingContinuationChunks = null;\n this.parts.splice(\n 0,\n this.parts.length,\n ...(existingIdx >= 0 ? messages[existingIdx].parts : [])\n );\n const currentMetadata =\n existingIdx >= 0\n ? asMetadata(messages[existingIdx].metadata)\n : undefined;\n this.metadata = currentMetadata ? { ...currentMetadata } : undefined;\n if (existingIdx >= 0) {\n this.messageId = messages[existingIdx].id;\n }\n for (const chunk of pendingChunks) {\n this.applyChunk(chunk);\n }\n }\n\n const messageId =\n existingIdx >= 0 ? messages[existingIdx].id : this.messageId;\n\n const partialMessage: UIMessage = {\n id: messageId,\n role: \"assistant\",\n parts: [...this.parts],\n ...(this.metadata != null && { metadata: this.metadata })\n } as UIMessage;\n\n if (existingIdx >= 0) {\n const updated = [...messages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...messages, partialMessage];\n }\n}\n","/**\n * Broadcast stream state machine.\n *\n * Manages the lifecycle of a StreamAccumulator for broadcast/resume\n * streams — the path where this client is *observing* a stream owned\n * by another tab or resumed after reconnect, rather than the transport-\n * owned path that feeds directly into useChat.\n *\n * The transition function is pure (no React, no WebSocket, no side\n * effects). Callers dispatch events and apply the returned state +\n * messagesUpdate. Side effects (sending ACKs, calling onData) stay\n * in the caller.\n */\n\nimport type { UIMessage } from \"ai\";\nimport { StreamAccumulator } from \"./stream-accumulator\";\nimport type { StreamChunkData } from \"./message-builder\";\n\n// ── State ──────────────────────────────────────────────────────────\n\nexport type BroadcastStreamState =\n | { status: \"idle\" }\n | {\n status: \"observing\";\n streamId: string;\n accumulator: StreamAccumulator;\n };\n\n// ── Events ─────────────────────────────────────────────────────────\n\nexport type BroadcastStreamEvent =\n | {\n type: \"response\";\n streamId: string;\n /** Fallback message ID for a new accumulator (ignored if one exists for this stream). */\n messageId: string;\n chunkData?: unknown;\n done?: boolean;\n error?: boolean;\n replay?: boolean;\n replayComplete?: boolean;\n continuation?: boolean;\n /** @deprecated Continuations now seed from current messages in `messagesUpdate`. */\n currentMessages?: UIMessage[];\n }\n | {\n type: \"resume-fallback\";\n streamId: string;\n messageId: string;\n }\n | { type: \"clear\" };\n\n// ── Result ─────────────────────────────────────────────────────────\n\nexport interface TransitionResult {\n state: BroadcastStreamState;\n messagesUpdate?: (prev: UIMessage[]) => UIMessage[];\n isStreaming: boolean;\n}\n\n// ── Transition ─────────────────────────────────────────────────────\n\nexport function transition(\n state: BroadcastStreamState,\n event: BroadcastStreamEvent\n): TransitionResult {\n switch (event.type) {\n case \"clear\":\n return { state: { status: \"idle\" }, isStreaming: false };\n\n case \"resume-fallback\": {\n const accumulator = new StreamAccumulator({\n messageId: event.messageId\n });\n return {\n state: {\n status: \"observing\",\n streamId: event.streamId,\n accumulator\n },\n isStreaming: true\n };\n }\n\n case \"response\": {\n let accumulator: StreamAccumulator;\n\n // A replayed `start` chunk means the server is re-sending the stream\n // buffer from chunk 0 (resume replay). Re-initialize the accumulator\n // instead of appending into an existing one: replaying into an\n // accumulator that already holds this stream's parts would duplicate\n // them (a second `text-start` unconditionally opens a second text\n // part — #1733). Re-initializing makes replay idempotent under any\n // number of replays, including a second replay triggered by a\n // duplicate STREAM_RESUMING → ACK cycle or a reconnect.\n const isReplayedStart =\n event.replay === true &&\n (event.chunkData as { type?: string } | null | undefined)?.type ===\n \"start\";\n\n if (\n state.status === \"idle\" ||\n state.streamId !== event.streamId ||\n isReplayedStart\n ) {\n accumulator = new StreamAccumulator({\n messageId: event.messageId,\n continuation: event.continuation\n });\n } else {\n accumulator = state.accumulator;\n }\n\n if (event.chunkData) {\n accumulator.applyChunk(event.chunkData as StreamChunkData);\n }\n\n let messagesUpdate: ((prev: UIMessage[]) => UIMessage[]) | undefined;\n\n if (event.done) {\n messagesUpdate = (prev) => accumulator.mergeInto(prev);\n return {\n state: { status: \"idle\" },\n messagesUpdate,\n isStreaming: false\n };\n }\n\n if (event.chunkData && !event.replay) {\n messagesUpdate = (prev) => accumulator.mergeInto(prev);\n } else if (event.replayComplete) {\n messagesUpdate = (prev) => accumulator.mergeInto(prev);\n }\n\n return {\n state: {\n status: \"observing\",\n streamId: event.streamId,\n accumulator\n },\n messagesUpdate,\n isStreaming: true\n };\n }\n }\n}\n","/**\n * Wire protocol message type constants for the cf_agent_chat_* protocol.\n *\n * These are the string values used on the wire between agent servers and\n * clients. Both @cloudflare/ai-chat (via its MessageType enum) and\n * @cloudflare/think use these values.\n */\nexport const STREAM_RESUME_NONE_REASONS = {\n /** No active, pending, or terminal stream exists for this agent. */\n IDLE: \"idle\",\n /** An active tool continuation is owned by another live connection. */\n CONTINUATION_OWNED: \"continuation-owned\"\n} as const;\n\nexport type StreamResumeNoneReason =\n (typeof STREAM_RESUME_NONE_REASONS)[keyof typeof STREAM_RESUME_NONE_REASONS];\n\nexport const CHAT_MESSAGE_TYPES = {\n CHAT_MESSAGES: \"cf_agent_chat_messages\",\n USE_CHAT_REQUEST: \"cf_agent_use_chat_request\",\n USE_CHAT_RESPONSE: \"cf_agent_use_chat_response\",\n CHAT_CLEAR: \"cf_agent_chat_clear\",\n CHAT_REQUEST_CANCEL: \"cf_agent_chat_request_cancel\",\n STREAM_RESUMING: \"cf_agent_stream_resuming\",\n STREAM_RESUME_ACK: \"cf_agent_stream_resume_ack\",\n STREAM_RESUME_REQUEST: \"cf_agent_stream_resume_request\",\n STREAM_RESUME_NONE: \"cf_agent_stream_resume_none\",\n // Server→client: a turn has been accepted but its resumable stream has not\n // started yet (queued, debouncing, waiting on MCP setup, or running async\n // work in `onChatMessage`). Sent in response to a resume request (or on\n // connect) so a reconnecting/re-mounting client keeps its expectation instead\n // of resolving its resume probe to \"no stream\" and then false-timing-out the\n // turn. Resolved by a later `STREAM_RESUMING` (stream started) or\n // `STREAM_RESUME_NONE` (turn settled without streaming). Backward-compatible —\n // clients that don't understand it ignore it. See issue #1784.\n STREAM_PENDING: \"cf_agent_stream_pending\",\n TOOL_RESULT: \"cf_agent_tool_result\",\n TOOL_APPROVAL: \"cf_agent_tool_approval\",\n MESSAGE_UPDATED: \"cf_agent_message_updated\",\n // Server→client: a durable chat turn is being recovered (interrupted by a\n // deploy/eviction or a stream-stall watchdog abort and now resuming). Sent\n // when a recovery continuation is scheduled and cleared on every terminal\n // outcome; `@cloudflare/think` also replays it on connect so a client that\n // joins mid-recovery learns it. Purely a progress hint — backward-compatible\n // (clients that don't understand it ignore it). See issue #1620.\n CHAT_RECOVERING: \"cf_agent_chat_recovering\"\n} as const;\n"],"mappings":";;AAgBA,SAAS,WAAW,OAAqD;CACvE,IAAI,SAAS,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,GACpE,OAAO;AAGX;AAuCA,IAAa,oBAAb,MAA+B;CAQ7B,YAAY,SAAmC;EAC7C,KAAK,YAAY,QAAQ;EACzB,KAAK,kBAAkB,QAAQ,gBAAgB;EAC/C,KAAK,QAAQ,QAAQ,gBAAgB,CAAC,GAAG,QAAQ,aAAa,IAAI,CAAC;EACnE,KAAK,WAAW,QAAQ,mBACpB,EAAE,GAAG,QAAQ,iBAAiB,IAC9B,KAAA;EACJ,KAAK,6BACH,KAAK,mBACL,QAAQ,kBAAkB,KAAA,KAC1B,QAAQ,qBAAqB,KAAA,IACzB,CAAC,IACD;CACR;CAEA,WAAW,OAAqC;EAC9C,KAAK,4BAA4B,KAAK,KAAK;EAC3C,MAAM,UAAU,kBAAkB,KAAK,OAAO,KAAK;EAGnD,IAAI,MAAM,SAAS,2BAA2B,MAAM,YAClD,OAAO;GACL;GACA,QAAQ;IAAE,MAAM;IAAyB,YAAY,MAAM;GAAW;EACxE;EAMF,KACG,MAAM,SAAS,2BACd,MAAM,SAAS,wBACjB,MAAM;OAKF,CAHiB,KAAK,MAAM,MAC7B,MAAM,gBAAgB,KAAK,EAAE,eAAe,MAAM,UAErC,GACd,OAAO;IACL;IACA,QAAQ;KACN,MAAM;KACN,YACE,MAAM,SAAS,0BACX,qBACA;KACN,YAAY,MAAM;KAClB,QAAQ,MAAM;KACd,WAAW,MAAM;KACjB,aAAa,MAAM;IACrB;GACF;EAAA;EAIJ,IAAI,CAAC,SACH,QAAQ,MAAM,MAAd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AAY;GACf,IAAI;GAUJ,MAAM,kBACJ,MAAM,WAAW,QAChB,MAAM,WAAoD,SACzD;GAEJ,IACE,MAAM,WAAW,UACjB,MAAM,aAAa,MAAM,YACzB,iBAEA,cAAc,IAAI,kBAAkB;IAClC,WAAW,MAAM;IACjB,cAAc,MAAM;GACtB,CAAC;QAED,cAAc,MAAM;GAGtB,IAAI,MAAM,WACR,YAAY,WAAW,MAAM,SAA4B;GAG3D,IAAI;GAEJ,IAAI,MAAM,MAAM;IACd,kBAAkB,SAAS,YAAY,UAAU,IAAI;IACrD,OAAO;KACL,OAAO,EAAE,QAAQ,OAAO;KACxB;KACA,aAAa;IACf;GACF;GAEA,IAAI,MAAM,aAAa,CAAC,MAAM,QAC5B,kBAAkB,SAAS,YAAY,UAAU,IAAI;QAChD,IAAI,MAAM,gBACf,kBAAkB,SAAS,YAAY,UAAU,IAAI;GAGvD,OAAO;IACL,OAAO;KACL,QAAQ;KACR,UAAU,MAAM;KAChB;IACF;IACA;IACA,aAAa;GACf;EACF;CACF;AACF;;;;;;;;;;AC1IA,MAAa,6BAA6B;;CAExC,MAAM;;CAEN,oBAAoB;AACtB;AAKA,MAAa,qBAAqB;CAChC,eAAe;CACf,kBAAkB;CAClB,mBAAmB;CACnB,YAAY;CACZ,qBAAqB;CACrB,iBAAiB;CACjB,mBAAmB;CACnB,uBAAuB;CACvB,oBAAoB;CASpB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,iBAAiB;CAOjB,iBAAiB;AACnB"}
1
+ {"version":3,"file":"protocol-kHsr-f0X.js","names":[],"sources":["../src/chat/stream-accumulator.ts","../src/chat/broadcast-state.ts","../src/chat/protocol.ts"],"sourcesContent":["/**\n * StreamAccumulator — unified chunk-to-message builder.\n *\n * Used by @cloudflare/ai-chat (server + client) and @cloudflare/think\n * to incrementally build a UIMessage from stream chunks. Wraps\n * applyChunkToParts and handles the metadata chunk types (start, finish,\n * message-metadata, error) that applyChunkToParts does not cover.\n *\n * The accumulator signals domain-specific concerns (early persistence,\n * cross-message tool updates) via ChunkAction returns — callers handle\n * these according to their context.\n */\n\nimport type { UIMessage } from \"ai\";\nimport { applyChunkToParts, type StreamChunkData } from \"./message-builder\";\n\nfunction asMetadata(value: unknown): Record<string, unknown> | undefined {\n if (value != null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n return undefined;\n}\n\nexport interface StreamAccumulatorOptions {\n messageId: string;\n /** Whether chunks continue the current assistant message when merged. */\n continuation?: boolean;\n /** Eager seed; omitted continuations seed from the messages passed to `mergeInto`. */\n existingParts?: UIMessage[\"parts\"];\n existingMetadata?: Record<string, unknown>;\n}\n\nexport type ChunkAction =\n | {\n type: \"start\";\n messageId?: string;\n metadata?: Record<string, unknown>;\n }\n | {\n type: \"finish\";\n finishReason?: string;\n metadata?: Record<string, unknown>;\n }\n | { type: \"message-metadata\"; metadata: Record<string, unknown> }\n | { type: \"tool-approval-request\"; toolCallId: string }\n | {\n type: \"cross-message-tool-update\";\n updateType: \"output-available\" | \"output-error\";\n toolCallId: string;\n output?: unknown;\n errorText?: string;\n preliminary?: boolean;\n }\n | { type: \"error\"; error: string };\n\nexport interface ChunkResult {\n handled: boolean;\n action?: ChunkAction;\n}\n\nexport class StreamAccumulator {\n messageId: string;\n readonly parts: UIMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n private _isContinuation: boolean;\n // Continuation chunks wait here until mergeInto can seed from current state.\n private _pendingContinuationChunks: StreamChunkData[] | null;\n\n constructor(options: StreamAccumulatorOptions) {\n this.messageId = options.messageId;\n this._isContinuation = options.continuation ?? false;\n this.parts = options.existingParts ? [...options.existingParts] : [];\n this.metadata = options.existingMetadata\n ? { ...options.existingMetadata }\n : undefined;\n this._pendingContinuationChunks =\n this._isContinuation &&\n options.existingParts === undefined &&\n options.existingMetadata === undefined\n ? []\n : null;\n }\n\n applyChunk(chunk: StreamChunkData): ChunkResult {\n this._pendingContinuationChunks?.push(chunk);\n const handled = applyChunkToParts(this.parts, chunk);\n\n // Detect tool-approval-request for early persistence signaling\n if (chunk.type === \"tool-approval-request\" && chunk.toolCallId) {\n return {\n handled,\n action: { type: \"tool-approval-request\", toolCallId: chunk.toolCallId }\n };\n }\n\n // Detect cross-message tool output/error: applyChunkToParts returns true\n // for recognized types but silently does nothing when the toolCallId\n // doesn't exist in the current parts array.\n if (\n (chunk.type === \"tool-output-available\" ||\n chunk.type === \"tool-output-error\") &&\n chunk.toolCallId\n ) {\n const foundInParts = this.parts.some(\n (p) => \"toolCallId\" in p && p.toolCallId === chunk.toolCallId\n );\n if (!foundInParts) {\n return {\n handled,\n action: {\n type: \"cross-message-tool-update\",\n updateType:\n chunk.type === \"tool-output-available\"\n ? \"output-available\"\n : \"output-error\",\n toolCallId: chunk.toolCallId,\n output: chunk.output,\n errorText: chunk.errorText,\n preliminary: chunk.preliminary\n }\n };\n }\n }\n\n if (!handled) {\n switch (chunk.type) {\n case \"start\": {\n if (chunk.messageId != null && !this._isContinuation) {\n this.messageId = chunk.messageId;\n }\n const startMeta = asMetadata(chunk.messageMetadata);\n if (startMeta) {\n this.metadata = this.metadata\n ? { ...this.metadata, ...startMeta }\n : { ...startMeta };\n }\n return {\n handled: true,\n action: {\n type: \"start\",\n messageId: chunk.messageId,\n metadata: startMeta\n }\n };\n }\n case \"finish\": {\n const finishMeta = asMetadata(chunk.messageMetadata);\n if (finishMeta) {\n this.metadata = this.metadata\n ? { ...this.metadata, ...finishMeta }\n : { ...finishMeta };\n }\n const finishReason =\n \"finishReason\" in chunk\n ? (chunk.finishReason as string)\n : undefined;\n return {\n handled: true,\n action: {\n type: \"finish\",\n finishReason,\n metadata: finishMeta\n }\n };\n }\n case \"message-metadata\": {\n const msgMeta = asMetadata(chunk.messageMetadata);\n if (msgMeta) {\n this.metadata = this.metadata\n ? { ...this.metadata, ...msgMeta }\n : { ...msgMeta };\n }\n return {\n handled: true,\n action: {\n type: \"message-metadata\",\n metadata: msgMeta ?? {}\n }\n };\n }\n case \"finish-step\": {\n return { handled: true };\n }\n case \"error\": {\n return {\n handled: true,\n action: {\n type: \"error\",\n error: chunk.errorText ?? JSON.stringify(chunk)\n }\n };\n }\n }\n }\n\n return { handled };\n }\n\n /** Snapshot the current state as a UIMessage. */\n toMessage(): UIMessage {\n return {\n id: this.messageId,\n role: \"assistant\",\n parts: [...this.parts],\n ...(this.metadata != null && { metadata: this.metadata })\n } as UIMessage;\n }\n\n /**\n * Merge this accumulator's message into an existing message array.\n * Handles continuation (walk backward for last assistant), replacement\n * (update existing by messageId), or append (new message). An unseeded\n * continuation adopts current parts here before applying its queued chunks.\n */\n mergeInto(messages: UIMessage[]): UIMessage[] {\n let existingIdx = messages.findIndex((m) => m.id === this.messageId);\n\n if (existingIdx < 0 && this._isContinuation) {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n existingIdx = i;\n break;\n }\n }\n }\n\n if (this._pendingContinuationChunks !== null) {\n const pendingChunks = this._pendingContinuationChunks;\n this._pendingContinuationChunks = null;\n this.parts.splice(\n 0,\n this.parts.length,\n ...(existingIdx >= 0 ? messages[existingIdx].parts : [])\n );\n const currentMetadata =\n existingIdx >= 0\n ? asMetadata(messages[existingIdx].metadata)\n : undefined;\n this.metadata = currentMetadata ? { ...currentMetadata } : undefined;\n if (existingIdx >= 0) {\n this.messageId = messages[existingIdx].id;\n }\n for (const chunk of pendingChunks) {\n this.applyChunk(chunk);\n }\n }\n\n const messageId =\n existingIdx >= 0 ? messages[existingIdx].id : this.messageId;\n\n const partialMessage: UIMessage = {\n id: messageId,\n role: \"assistant\",\n parts: [...this.parts],\n ...(this.metadata != null && { metadata: this.metadata })\n } as UIMessage;\n\n if (existingIdx >= 0) {\n const updated = [...messages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...messages, partialMessage];\n }\n}\n","/**\n * Broadcast stream state machine.\n *\n * Manages the lifecycle of a StreamAccumulator for broadcast/resume\n * streams — the path where this client is *observing* a stream owned\n * by another tab or resumed after reconnect, rather than the transport-\n * owned path that feeds directly into useChat.\n *\n * The transition function is pure (no React, no WebSocket, no side\n * effects). Callers dispatch events and apply the returned state +\n * messagesUpdate. Side effects (sending ACKs, calling onData) stay\n * in the caller.\n */\n\nimport type { UIMessage } from \"ai\";\nimport { StreamAccumulator } from \"./stream-accumulator\";\nimport type { StreamChunkData } from \"./message-builder\";\n\n// ── State ──────────────────────────────────────────────────────────\n\nexport type BroadcastStreamState =\n | { status: \"idle\" }\n | {\n status: \"observing\";\n streamId: string;\n accumulator: StreamAccumulator;\n };\n\n// ── Events ─────────────────────────────────────────────────────────\n\nexport type BroadcastStreamEvent =\n | {\n type: \"response\";\n streamId: string;\n /** Fallback message ID for a new accumulator (ignored if one exists for this stream). */\n messageId: string;\n chunkData?: unknown;\n done?: boolean;\n error?: boolean;\n replay?: boolean;\n replayComplete?: boolean;\n continuation?: boolean;\n /** @deprecated Continuations now seed from current messages in `messagesUpdate`. */\n currentMessages?: UIMessage[];\n }\n | {\n type: \"resume-fallback\";\n streamId: string;\n messageId: string;\n }\n | { type: \"clear\" };\n\n// ── Result ─────────────────────────────────────────────────────────\n\nexport interface TransitionResult {\n state: BroadcastStreamState;\n messagesUpdate?: (prev: UIMessage[]) => UIMessage[];\n isStreaming: boolean;\n}\n\n// ── Snapshot reconciliation ────────────────────────────────────────\n\nfunction textOf(parts: UIMessage[\"parts\"]): string {\n let text = \"\";\n for (const part of parts) {\n if (part.type === \"text\") text += part.text;\n }\n return text;\n}\n\n/**\n * Whether `messages` already holds a copy of the observed message whose text\n * the accumulator does not extend. A healthy live accumulator is always the\n * stored copy plus more; one that diverges holds interleaved or duplicated\n * chunks (#2166), so the stored copy must win or the corruption never heals.\n */\nexport function observedDivergesFrom(\n accumulator: StreamAccumulator,\n messages: UIMessage[]\n): boolean {\n const existing = messages.find((m) => m.id === accumulator.messageId);\n if (!existing) return false;\n return !textOf(accumulator.parts).startsWith(textOf(existing.parts));\n}\n\n// ── Transition ─────────────────────────────────────────────────────\n\nexport function transition(\n state: BroadcastStreamState,\n event: BroadcastStreamEvent\n): TransitionResult {\n switch (event.type) {\n case \"clear\":\n return { state: { status: \"idle\" }, isStreaming: false };\n\n case \"resume-fallback\": {\n const accumulator = new StreamAccumulator({\n messageId: event.messageId\n });\n return {\n state: {\n status: \"observing\",\n streamId: event.streamId,\n accumulator\n },\n isStreaming: true\n };\n }\n\n case \"response\": {\n let accumulator: StreamAccumulator;\n\n // A replayed `start` chunk means the server is re-sending the stream\n // buffer from chunk 0 (resume replay). Re-initialize the accumulator\n // instead of appending into an existing one: replaying into an\n // accumulator that already holds this stream's parts would duplicate\n // them (a second `text-start` unconditionally opens a second text\n // part — #1733). Re-initializing makes replay idempotent under any\n // number of replays, including a second replay triggered by a\n // duplicate STREAM_RESUMING → ACK cycle or a reconnect.\n const isReplayedStart =\n event.replay === true &&\n (event.chunkData as { type?: string } | null | undefined)?.type ===\n \"start\";\n\n if (\n state.status === \"idle\" ||\n state.streamId !== event.streamId ||\n isReplayedStart\n ) {\n accumulator = new StreamAccumulator({\n messageId: event.messageId,\n continuation: event.continuation\n });\n } else {\n accumulator = state.accumulator;\n }\n\n if (event.chunkData) {\n accumulator.applyChunk(event.chunkData as StreamChunkData);\n }\n\n let messagesUpdate: ((prev: UIMessage[]) => UIMessage[]) | undefined;\n\n const mergeUnlessDiverged = (prev: UIMessage[]) =>\n observedDivergesFrom(accumulator, prev)\n ? prev\n : accumulator.mergeInto(prev);\n\n if (event.done) {\n return {\n state: { status: \"idle\" },\n messagesUpdate: mergeUnlessDiverged,\n isStreaming: false\n };\n }\n\n if (event.chunkData && !event.replay) {\n messagesUpdate = mergeUnlessDiverged;\n } else if (event.replayComplete) {\n messagesUpdate = (prev) => accumulator.mergeInto(prev);\n }\n\n return {\n state: {\n status: \"observing\",\n streamId: event.streamId,\n accumulator\n },\n messagesUpdate,\n isStreaming: true\n };\n }\n }\n}\n","/**\n * Wire protocol message type constants for the cf_agent_chat_* protocol.\n *\n * These are the string values used on the wire between agent servers and\n * clients. Both @cloudflare/ai-chat (via its MessageType enum) and\n * @cloudflare/think use these values.\n */\nexport const STREAM_RESUME_NONE_REASONS = {\n /** No active, pending, or terminal stream exists for this agent. */\n IDLE: \"idle\",\n /** An active tool continuation is owned by another live connection. */\n CONTINUATION_OWNED: \"continuation-owned\"\n} as const;\n\nexport type StreamResumeNoneReason =\n (typeof STREAM_RESUME_NONE_REASONS)[keyof typeof STREAM_RESUME_NONE_REASONS];\n\nexport const CHAT_MESSAGE_TYPES = {\n CHAT_MESSAGES: \"cf_agent_chat_messages\",\n USE_CHAT_REQUEST: \"cf_agent_use_chat_request\",\n USE_CHAT_RESPONSE: \"cf_agent_use_chat_response\",\n CHAT_CLEAR: \"cf_agent_chat_clear\",\n CHAT_REQUEST_CANCEL: \"cf_agent_chat_request_cancel\",\n STREAM_RESUMING: \"cf_agent_stream_resuming\",\n STREAM_RESUME_ACK: \"cf_agent_stream_resume_ack\",\n STREAM_RESUME_REQUEST: \"cf_agent_stream_resume_request\",\n STREAM_RESUME_NONE: \"cf_agent_stream_resume_none\",\n // Server→client: a turn has been accepted but its resumable stream has not\n // started yet (queued, debouncing, waiting on MCP setup, or running async\n // work in `onChatMessage`). Sent in response to a resume request (or on\n // connect) so a reconnecting/re-mounting client keeps its expectation instead\n // of resolving its resume probe to \"no stream\" and then false-timing-out the\n // turn. Resolved by a later `STREAM_RESUMING` (stream started) or\n // `STREAM_RESUME_NONE` (turn settled without streaming). Backward-compatible —\n // clients that don't understand it ignore it. See issue #1784.\n STREAM_PENDING: \"cf_agent_stream_pending\",\n TOOL_RESULT: \"cf_agent_tool_result\",\n TOOL_APPROVAL: \"cf_agent_tool_approval\",\n MESSAGE_UPDATED: \"cf_agent_message_updated\",\n // Server→client: a durable chat turn is being recovered (interrupted by a\n // deploy/eviction or a stream-stall watchdog abort and now resuming). Sent\n // when a recovery continuation is scheduled and cleared on every terminal\n // outcome; `@cloudflare/think` also replays it on connect so a client that\n // joins mid-recovery learns it. Purely a progress hint — backward-compat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LifecycleJobOutcome
6
- } from "../capability-runner-BUBa6Ake.js";
7
- import { t as RetryOptions } from "../retries-D9B2UCq3.js";
6
+ } from "../capability-runner-DBAnGr6L.js";
7
+ import { t as RetryOptions } from "../retries-CV6AkXmQ.js";
8
8
  import {
9
9
  a as QueuePayload,
10
10
  i as QueueItem,
@@ -12,7 +12,7 @@ import {
12
12
  o as QueuePushOptions,
13
13
  r as QueueHandlers,
14
14
  t as QueueCallbacks
15
- } from "../types-DCD6BNZH.js";
15
+ } from "../types-BA4anrjI.js";
16
16
 
17
17
  //#region src/queue/options.d.ts
18
18
  /** Events emitted while a Queue creates, retries, or fails work. */
@@ -1,2 +1,2 @@
1
- import { t as Queue } from "../queue-BC9F5cUo.js";
1
+ import { t as Queue } from "../queue-BB-zfIYF.js";
2
2
  export { Queue };
@@ -1,6 +1,6 @@
1
1
  import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
2
- import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
3
2
  import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
3
+ import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
4
4
  import { isDurableObjectCodeUpdateReset, isPlatformFailure, resolveRetryConfig, tryN, validateRetryOptions } from "./retries.js";
5
5
  //#region src/queue/queue.ts
6
6
  /**
@@ -403,4 +403,4 @@ function _emit(type, payload) {
403
403
  //#endregion
404
404
  export { setQueueCallbackResolver as n, Queue as t };
405
405
 
406
- //# sourceMappingURL=queue-BC9F5cUo.js.map
406
+ //# sourceMappingURL=queue-BB-zfIYF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"queue-BC9F5cUo.js","names":[],"sources":["../src/queue/queue.ts"],"sourcesContent":["/**\n * Lifecycle background-work vocabulary. Queue validates items, resolves\n * named callbacks, and pushes jobs due immediately into the Lifecycle-owned\n * job queue; Lifecycle runs the alarm event loop, retry policy, and physical\n * alarm arming. Queue owns no storage of its own — each item is one job\n * whose `fn` is the callback name and whose payload carries the item's\n * payload and owner.\n */\n\nimport {\n LifecycleCapability,\n type LifecycleRouteAddress,\n type LifecycleRouteContext\n} from \"../lifecycle/capability\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"../lifecycle/job-queue\";\nimport {\n isDurableObjectCodeUpdateReset,\n isPlatformFailure,\n resolveRetryConfig,\n tryN,\n validateRetryOptions\n} from \"../retries\";\nimport type { RetryOptions } from \"../retries\";\nimport type { QueueEventType, QueueOptions } from \"./options\";\nimport type {\n QueueCallbacks,\n QueueCriteria,\n QueueHandlers,\n QueueItem,\n QueuePayload,\n QueuePushOptions,\n QueueStorageRow\n} from \"./types\";\n\n/** A resolved fallback handler for a callback name outside the registered map. */\ntype ResolvedQueueCallback = (\n payload: unknown,\n item: QueueItem<unknown>\n) => unknown;\n\nconst queueCallbackResolvers = new WeakMap<\n object,\n (name: string) => ResolvedQueueCallback | undefined\n>();\n\n/**\n * @internal Supply a composition-root fallback for callback names outside the\n * registered map. Agent uses this to keep its historical name-based queue\n * API (`this.queue(\"methodName\", payload)`) working: the resolver looks the\n * method up on the Agent, and the resolved handler still runs inside the\n * Lifecycle host boundary.\n */\nexport function setQueueCallbackResolver(\n queue: Queue<never>,\n resolver: (name: string) => ResolvedQueueCallback | undefined\n): void {\n queueCallbackResolvers.set(queue, resolver);\n}\n\nconst QUEUE_SCHEMA_VERSION_KEY = \"cf_agents:queue_schema_version\";\n/** Version 1: queue items live in the Lifecycle job queue. */\nconst CURRENT_QUEUE_SCHEMA_VERSION = 1;\n\nconst DEFAULT_RETRY: Required<RetryOptions> = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n};\n\n/** What a Queue job's payload carries: the item payload and its owner. */\ntype QueueJobPayload = {\n readonly payload: unknown;\n readonly owner_path: string | null;\n readonly owner_path_key: string | null;\n};\n\ntype QueueRouteMessage =\n | {\n readonly type: \"push\";\n readonly callback: string;\n readonly payload: unknown;\n readonly options?: QueuePushOptions;\n }\n | { readonly type: \"get\" | \"cancel\"; readonly id: string }\n | { readonly type: \"list\"; readonly criteria?: QueueCriteria }\n | { readonly type: \"cancelAll\"; readonly callback?: string }\n | {\n readonly type: \"dispatch\";\n readonly item: QueueItem<unknown>;\n };\n\nfunction isQueueJobPayload(value: unknown): value is QueueJobPayload {\n // `payload` is absent after a JSON round trip when the item carried none.\n return typeof value === \"object\" && value !== null && \"owner_path\" in value;\n}\n\n/**\n * Durable background work for a Lifecycle Object.\n *\n * Register callbacks in the constructor and install the instance with\n * `Lifecycle.use()`. Each pushed item becomes a job due immediately in the\n * Lifecycle job queue; Lifecycle owns the physical alarm and the alarm event\n * loop, drives items one at a time in push order, retries a throwing\n * callback per its retry policy, and Queue runs registered callbacks through\n * Lifecycle's host invocation boundary. An item that still fails after its\n * last attempt is dropped after `queue:error` and the `onError` hook.\n *\n * Items survive the Durable Object leaving memory: an isolate that dies mid\n * callback wakes again on the Lifecycle deadman alarm and resumes the queue.\n * Callbacks should therefore be idempotent.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Queue<\n Handlers extends QueueHandlers = QueueCallbacks\n> extends LifecycleCapability {\n readonly #handlers: QueueHandlers;\n readonly #retryDefaults: Required<RetryOptions>;\n readonly #onError: ((error: unknown) => void | Promise<void>) | undefined;\n /**\n * Last due time handed to a job. The Lifecycle driver dispatches due jobs\n * in due-time order, so pushes get strictly increasing times to keep push\n * order (FIFO) even within one millisecond. Seeded from the persisted\n * queue tail on first use so a fresh instance never sorts a new item ahead\n * of items an earlier instance already queued.\n */\n #lastTime: number | null = null;\n\n /**\n * Create a durable Queue.\n *\n * @param options - Registered callbacks plus optional retry and error\n * policy. Registering `callbacks` types {@link push} against the map —\n * names and payloads are checked where the handlers are declared and where\n * they are pushed. Names outside the map are rejected unless a\n * composition-root resolver supplies them — the internal aperture behind\n * `Agent`'s name-based queue API.\n */\n constructor(options: QueueOptions<Handlers> = {}) {\n super(\"queue\");\n this.#handlers = options.callbacks ?? {};\n // Retry defaults are resolved, not validated, here: invalid defaults\n // surface per execution as queue:error instead of bricking the object at\n // construction. Per-item retry overrides are validated when pushed.\n this.#retryDefaults = resolveRetryConfig(options.retry, DEFAULT_RETRY);\n this.#onError = options.onError;\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate legacy `cf_agents_queues` rows into the Lifecycle job queue. */\n async onStart(): Promise<void> {\n const storage = this.lifecycle.storage;\n const version = (await storage.get<number>(QUEUE_SCHEMA_VERSION_KEY)) ?? 0;\n if (version >= CURRENT_QUEUE_SCHEMA_VERSION) return;\n\n await this.#migrateLegacyQueueTable(storage);\n await storage.put(QUEUE_SCHEMA_VERSION_KEY, CURRENT_QUEUE_SCHEMA_VERSION);\n }\n\n /**\n * Move every `cf_agents_queues` row into the job queue and drop the\n * table. Idempotent: a missing table means a fresh object or a completed\n * migration. Rows keep their insertion order.\n *\n * TEMPORARY: one-shot upgrade path for objects that had queued items when\n * this release landed. Remove in the next minor release (with the schema\n * version bump that gates it), once every deployed object has migrated.\n */\n async #migrateLegacyQueueTable(storage: DurableObjectStorage): Promise<void> {\n const tables = storage.sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name='cf_agents_queues'\"\n )\n .toArray();\n if (tables.length === 0) return;\n\n const rows = storage.sql\n .exec(\"SELECT * FROM cf_agents_queues ORDER BY created_at ASC, rowid ASC\")\n .toArray() as unknown as QueueStorageRow[];\n for (const row of rows) {\n let payload: unknown;\n try {\n payload =\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined;\n } catch (error) {\n console.error(\n `Skipping queue item \"${row.id}\" during job-queue migration: ` +\n \"its payload is not valid JSON\",\n error\n );\n continue;\n }\n let retry: RetryOptions | undefined;\n try {\n retry =\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined;\n } catch {\n retry = undefined;\n }\n await this.lifecycle.jobs.push({\n id: row.id,\n fn: row.callback,\n time: this.#nextTime(),\n payload: {\n payload,\n owner_path: null,\n owner_path_key: null\n } satisfies QueueJobPayload,\n retry: resolveRetryConfig(retry, this.#retryDefaults)\n });\n }\n storage.sql.exec(\"DROP TABLE cf_agents_queues\");\n }\n\n /** Drive one due item dispatched by the Lifecycle event loop. */\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n const { job, attempt } = context;\n if (!isQueueJobPayload(job.payload)) {\n console.error(`Malformed queue item ${job.id}; dropping it`);\n return undefined;\n }\n const item = this.#jobToItem(job, job.payload);\n\n if (attempt > 1) {\n this.#emit(\"queue:retry\", {\n callback: job.fn,\n id: job.id,\n attempt,\n maxAttempts: resolveRetryConfig(job.retry, this.#retryDefaults)\n .maxAttempts\n });\n }\n\n if (job.payload.owner_path) {\n // A routed item executes inside its owning Lifecycle; retries run\n // there too, so this dispatch is a single routed attempt.\n try {\n await this.lifecycle.routes.to(\n {\n key: job.payload.owner_path_key ?? job.payload.owner_path,\n data: job.payload.owner_path\n },\n { type: \"dispatch\", item } satisfies QueueRouteMessage\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n // Preserve the item; Lifecycle defers platform-class failures to\n // a fresh invocation or the memory-limit breaker.\n throw error;\n }\n console.error(`error dispatching queue callback \"${job.fn}\"`, error);\n this.#emit(\"queue:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: 0\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n // Leave the item due so a later alarm cycle can retry dispatch, for\n // example once a transport can resolve its owner again.\n return \"yield\";\n }\n return undefined;\n }\n\n const handler = this.#resolveCallback(job.fn);\n if (!handler) {\n console.error(`callback ${job.fn} not found`);\n return undefined;\n }\n await this.lifecycle.runInHostContext(() => handler(item.payload, item));\n return undefined;\n }\n\n /** Observe one item's terminal application failure; the item is dropped. */\n async onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): Promise<LifecycleJobOutcome | void> {\n const { job } = context;\n const { maxAttempts } = resolveRetryConfig(job.retry, this.#retryDefaults);\n console.error(\n `queue callback \"${job.fn}\" failed after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"queue:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n return undefined;\n }\n\n /** Handle Queue protocol messages routed by another Lifecycle. */\n async onRoute(context: LifecycleRouteContext): Promise<unknown> {\n const message = context.payload as QueueRouteMessage;\n const owner = context.source ?? null;\n switch (message.type) {\n case \"push\":\n return this.#insert(\n owner,\n message.callback,\n message.payload,\n message.options\n );\n case \"get\":\n return this.#getForOwner(owner, message.id);\n case \"list\":\n return this.#listForOwner(owner, message.criteria);\n case \"cancel\":\n return this.#cancelForOwner(owner, message.id);\n case \"cancelAll\":\n return this.#cancelAllForOwner(owner, message.callback);\n case \"dispatch\":\n await this.#executeRouted(message.item);\n return true;\n default:\n throw new Error(\"Unknown routed Queue message\");\n }\n }\n\n /**\n * Execute a routed item locally with the historical retry handling. Runs\n * on the owning (facet) Queue, outside the root's event loop, so it applies\n * its own in-process retry budget. Platform-class failures re-throw so the\n * root preserves the item and the durable alarm retries on a fresh\n * invocation.\n */\n async #executeRouted(item: QueueItem<unknown>): Promise<void> {\n const handler = this.#resolveCallback(item.callback);\n if (!handler) {\n console.error(`callback ${item.callback} not found`);\n return;\n }\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n item.retry,\n this.#retryDefaults\n );\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this.#emit(\"queue:retry\", {\n callback: item.callback,\n id: item.id,\n attempt,\n maxAttempts\n });\n }\n await this.lifecycle.runInHostContext(() =>\n handler(item.payload, item)\n );\n },\n {\n baseDelayMs,\n maxDelayMs,\n shouldRetry: (error) => !isDurableObjectCodeUpdateReset(error)\n }\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n throw error;\n }\n console.error(\n `queue callback \"${item.callback}\" failed after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"queue:error\", {\n callback: item.callback,\n id: item.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n }\n }\n\n // ── Queue API ────────────────────────────────────────────────────────────\n\n /**\n * Push one item for a registered callback. The item is due immediately;\n * the Lifecycle alarm event loop runs it in push order after this call\n * returns.\n *\n * Once the Lifecycle has started (and this Queue is not routed through\n * another Lifecycle), the item row is written synchronously before this\n * method's promise is even returned, so a caller may pair a push with its\n * own writes in one synchronous block — the item then commits atomically\n * with them.\n */\n async push<Name extends keyof Handlers & string>(\n callback: Name,\n payload?: QueuePayload<Handlers[Name]>,\n options?: QueuePushOptions\n ): Promise<QueueItem<QueuePayload<Handlers[Name]>>> {\n if (this.lifecycle.status() !== \"started\") await this.lifecycle.ready();\n this.#validatePush(callback, options);\n const item = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"push\",\n callback,\n payload,\n options\n } satisfies QueueRouteMessage)) as QueueItem<\n QueuePayload<Handlers[Name]>\n >)\n : await this.#insert<QueuePayload<Handlers[Name]>>(\n null,\n callback,\n payload,\n options\n );\n this.#emit(\"queue:create\", { callback, id: item.id });\n return item;\n }\n\n /** Cancel one pending item. Returns false when no item matched. */\n async cancel(id: string): Promise<boolean> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"cancel\",\n id\n } satisfies QueueRouteMessage)) as boolean;\n }\n return this.#cancelForOwner(null, id);\n }\n\n /** Cancel every pending item, or every item for one callback. Returns the count. */\n async cancelAll(callback?: string): Promise<number> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"cancelAll\",\n callback\n } satisfies QueueRouteMessage)) as number;\n }\n return this.#cancelAllForOwner(null, callback);\n }\n\n /** Read one pending item. */\n async get<T = unknown>(id: string): Promise<QueueItem<T> | undefined> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"get\",\n id\n } satisfies QueueRouteMessage)) as QueueItem<T> | undefined;\n }\n return this.#getForOwner<T>(null, id);\n }\n\n /** List pending items in push order, optionally filtered by callback. */\n async list<T = unknown>(criteria?: QueueCriteria): Promise<QueueItem<T>[]> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"list\",\n criteria\n } satisfies QueueRouteMessage)) as QueueItem<T>[];\n }\n return this.#listForOwner<T>(null, criteria);\n }\n\n // ── Internals ────────────────────────────────────────────────────────────\n\n #validatePush(callback: string, options?: QueuePushOptions): void {\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown queue callback \"${callback}\": not registered on this Queue`\n );\n }\n if (options?.retry)\n validateRetryOptions(options.retry, this.#retryDefaults);\n if (options?.id !== undefined && options.id.trim() === \"\") {\n throw new Error(\"Queue item ids must be non-empty\");\n }\n }\n\n /** Resolve a name to its registered or composition-root-supplied handler. */\n #resolveCallback(name: string): ResolvedQueueCallback | undefined {\n const handler = this.#handlers[name];\n if (handler) {\n // SAFETY: registered handlers are constrained with `never` parameters\n // so concrete handler types satisfy the map under contravariance; the\n // payload passed at dispatch was persisted with this handler's name.\n return handler as ResolvedQueueCallback;\n }\n return queueCallbackResolvers.get(this)?.(name);\n }\n\n #hasCallback(name: string): boolean {\n return this.#resolveCallback(name) !== undefined;\n }\n\n /** The next strictly increasing due time, never before now. */\n #nextTime(): number {\n if (this.#lastTime === null) {\n this.#lastTime = this.#ownedJobs().reduce(\n (lastTime, { job }) => Math.max(lastTime, job.time),\n 0\n );\n }\n const time = Math.max(Date.now(), this.#lastTime + 1);\n this.#lastTime = time;\n return time;\n }\n\n async #insert<T>(\n owner: LifecycleRouteAddress | null,\n callback: string,\n payload: unknown,\n options?: QueuePushOptions\n ): Promise<QueueItem<T>> {\n // A stable-id push replaces the item in place: it keeps the existing\n // item's due time, and so its position in the queue.\n const existing =\n options?.id !== undefined\n ? this.lifecycle.jobs.get(options.id)\n : undefined;\n const keepTime =\n existing !== undefined &&\n this.#getForOwner(owner, existing.id) !== undefined;\n const job = await this.lifecycle.jobs.push({\n id: options?.id,\n fn: callback,\n time: keepTime ? existing.time : this.#nextTime(),\n payload: {\n payload,\n owner_path: owner?.data ?? null,\n owner_path_key: owner?.key ?? null\n } satisfies QueueJobPayload,\n retry: resolveRetryConfig(options?.retry, this.#retryDefaults)\n });\n return this.#jobToItem<T>(job, job.payload as QueueJobPayload);\n }\n\n #jobToItem<T>(job: LifecycleJob, envelope: QueueJobPayload): QueueItem<T> {\n return {\n id: job.id,\n callback: job.fn,\n payload: envelope.payload as T,\n createdAt: job.createdAt,\n retry: job.retry\n };\n }\n\n /** Every queue job this Queue owns, in push order. */\n #ownedJobs(): Array<{ job: LifecycleJob; envelope: QueueJobPayload }> {\n const owned: Array<{ job: LifecycleJob; envelope: QueueJobPayload }> = [];\n for (const job of this.lifecycle.jobs.list()) {\n if (isQueueJobPayload(job.payload)) {\n owned.push({ job, envelope: job.payload });\n }\n }\n return owned;\n }\n\n #getForOwner<T>(\n owner: LifecycleRouteAddress | null,\n id: string\n ): QueueItem<T> | undefined {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isQueueJobPayload(job.payload)) return undefined;\n if ((job.payload.owner_path_key ?? null) !== ownerKey) return undefined;\n return this.#jobToItem<T>(job, job.payload);\n }\n\n #listForOwner<T>(\n owner: LifecycleRouteAddress | null,\n criteria: QueueCriteria = {}\n ): QueueItem<T>[] {\n const ownerKey = owner?.key ?? null;\n const items: QueueItem<T>[] = [];\n for (const { job, envelope } of this.#ownedJobs()) {\n if ((envelope.owner_path_key ?? null) !== ownerKey) continue;\n if (criteria.callback && job.fn !== criteria.callback) continue;\n items.push(this.#jobToItem<T>(job, envelope));\n }\n return items;\n }\n\n async #cancelForOwner(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Promise<boolean> {\n if (!this.#getForOwner(owner, id)) return false;\n return this.lifecycle.jobs.cancel(id);\n }\n\n async #cancelAllForOwner(\n owner: LifecycleRouteAddress | null,\n callback?: string\n ): Promise<number> {\n let cancelled = 0;\n for (const item of this.#listForOwner(owner, { callback })) {\n if (await this.lifecycle.jobs.cancel(item.id)) cancelled++;\n }\n return cancelled;\n }\n\n /** @internal Remove items owned by one routed Lifecycle subtree. */\n async __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(\n prefix: string\n ): Promise<void> {\n for (const { job, envelope } of this.#ownedJobs()) {\n const ownerKey = envelope.owner_path_key ?? envelope.owner_path;\n if (!envelope.owner_path || ownerKey === null) continue;\n if (ownerKey !== prefix && !ownerKey.startsWith(`${prefix}/`)) continue;\n await this.lifecycle.jobs.cancel(job.id);\n }\n }\n\n // ── Events ───────────────────────────────────────────────────────────────\n\n #emit(type: QueueEventType, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA4CA,MAAM,yCAAyB,IAAI,QAGjC;;;;;;;;AASF,SAAgB,yBACd,OACA,UACM;CACN,uBAAuB,IAAI,OAAO,QAAQ;AAC5C;AAEA,MAAM,2BAA2B;;AAEjC,MAAM,+BAA+B;AAErC,MAAM,gBAAwC;CAC5C,aAAa;CACb,aAAa;CACb,YAAY;AACd;AAwBA,SAAS,kBAAkB,OAA0C;CAEnE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,gBAAgB;AACxE;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,QAAb,cAEU,oBAAoB;;;;;;;;;;;CAuB5B,YAAY,UAAkC,CAAC,GAAG;EAChD,MAAM,OAAO;;;;;8CAbY,IAAA;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,KAAK,IAAI,QAAQ,kBAAkB,UAAU,UAAU,OAAO,KAAA;CAC9D,OAAA,kBAAA,cAAO,MAAA,UAAA,CAAA,CAAA,KAAA,MAAmB,KAAK,IAAI,OAAO;AAC5C;AAEA,SAAA,cACE,OACA,WAA0B,CAAC,GACX;CAChB,MAAM,WAAW,OAAO,OAAO;CAC/B,MAAM,QAAwB,CAAC;CAC/B,KAAK,MAAM,EAAE,KAAK,cAAA,kBAAA,cAAc,MAAA,UAAA,CAAA,CAAA,KAAA,IAAgB,GAAG;EACjD,KAAK,SAAS,kBAAkB,UAAU,UAAU;EACpD,IAAI,SAAS,YAAY,IAAI,OAAO,SAAS,UAAU;EACvD,MAAM,KAAA,kBAAA,cAAK,MAAA,UAAA,CAAA,CAAA,KAAA,MAAmB,KAAK,QAAQ,CAAC;CAC9C;CACA,OAAO;AACT;AAEA,eAAA,gBACE,OACA,IACkB;CAClB,IAAI,CAAA,kBAAA,cAAC,MAAA,YAAA,CAAA,CAAA,KAAA,MAAkB,OAAO,EAAE,GAAG,OAAO;CAC1C,OAAO,KAAK,UAAU,KAAK,OAAO,EAAE;AACtC;AAEA,eAAA,mBACE,OACA,UACiB;CACjB,IAAI,YAAY;CAChB,KAAK,MAAM,QAAA,kBAAA,cAAQ,MAAA,aAAA,CAAA,CAAA,KAAA,MAAmB,OAAO,EAAE,SAAS,CAAC,GACvD,IAAI,MAAM,KAAK,UAAU,KAAK,OAAO,KAAK,EAAE,GAAG;CAEjD,OAAO;AACT;AAgBA,SAAA,MAAM,MAAsB,SAAwC;CAClE,KAAK,UAAU,OAAO,KAAK,MAAM,OAAO;AAC1C"}
1
+ {"version":3,"file":"queue-BB-zfIYF.js","names":[],"sources":["../src/queue/queue.ts"],"sourcesContent":["/**\n * Lifecycle background-work vocabulary. Queue validates items, resolves\n * named callbacks, and pushes jobs due immediately into the Lifecycle-owned\n * job queue; Lifecycle runs the alarm event loop, retry policy, and physical\n * alarm arming. Queue owns no storage of its own — each item is one job\n * whose `fn` is the callback name and whose payload carries the item's\n * payload and owner.\n */\n\nimport {\n LifecycleCapability,\n type LifecycleRouteAddress,\n type LifecycleRouteContext\n} from \"../lifecycle/capability\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"../lifecycle/job-queue\";\nimport {\n isDurableObjectCodeUpdateReset,\n isPlatformFailure,\n resolveRetryConfig,\n tryN,\n validateRetryOptions\n} from \"../retries\";\nimport type { RetryOptions } from \"../retries\";\nimport type { QueueEventType, QueueOptions } from \"./options\";\nimport type {\n QueueCallbacks,\n QueueCriteria,\n QueueHandlers,\n QueueItem,\n QueuePayload,\n QueuePushOptions,\n QueueStorageRow\n} from \"./types\";\n\n/** A resolved fallback handler for a callback name outside the registered map. */\ntype ResolvedQueueCallback = (\n payload: unknown,\n item: QueueItem<unknown>\n) => unknown;\n\nconst queueCallbackResolvers = new WeakMap<\n object,\n (name: string) => ResolvedQueueCallback | undefined\n>();\n\n/**\n * @internal Supply a composition-root fallback for callback names outside the\n * registered map. Agent uses this to keep its historical name-based queue\n * API (`this.queue(\"methodName\", payload)`) working: the resolver looks the\n * method up on the Agent, and the resolved handler still runs inside the\n * Lifecycle host boundary.\n */\nexport function setQueueCallbackResolver(\n queue: Queue<never>,\n resolver: (name: string) => ResolvedQueueCallback | undefined\n): void {\n queueCallbackResolvers.set(queue, resolver);\n}\n\nconst QUEUE_SCHEMA_VERSION_KEY = \"cf_agents:queue_schema_version\";\n/** Version 1: queue items live in the Lifecycle job queue. */\nconst CURRENT_QUEUE_SCHEMA_VERSION = 1;\n\nconst DEFAULT_RETRY: Required<RetryOptions> = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n};\n\n/** What a Queue job's payload carries: the item payload and its owner. */\ntype QueueJobPayload = {\n readonly payload: unknown;\n readonly owner_path: string | null;\n readonly owner_path_key: string | null;\n};\n\ntype QueueRouteMessage =\n | {\n readonly type: \"push\";\n readonly callback: string;\n readonly payload: unknown;\n readonly options?: QueuePushOptions;\n }\n | { readonly type: \"get\" | \"cancel\"; readonly id: string }\n | { readonly type: \"list\"; readonly criteria?: QueueCriteria }\n | { readonly type: \"cancelAll\"; readonly callback?: string }\n | {\n readonly type: \"dispatch\";\n readonly item: QueueItem<unknown>;\n };\n\nfunction isQueueJobPayload(value: unknown): value is QueueJobPayload {\n // `payload` is absent after a JSON round trip when the item carried none.\n return typeof value === \"object\" && value !== null && \"owner_path\" in value;\n}\n\n/**\n * Durable background work for a Lifecycle Object.\n *\n * Register callbacks in the constructor and install the instance with\n * `Lifecycle.use()`. Each pushed item becomes a job due immediately in the\n * Lifecycle job queue; Lifecycle owns the physical alarm and the alarm event\n * loop, drives items one at a time in push order, retries a throwing\n * callback per its retry policy, and Queue runs registered callbacks through\n * Lifecycle's host invocation boundary. An item that still fails after its\n * last attempt is dropped after `queue:error` and the `onError` hook.\n *\n * Items survive the Durable Object leaving memory: an isolate that dies mid\n * callback wakes again on the Lifecycle deadman alarm and resumes the queue.\n * Callbacks should therefore be idempotent.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Queue<\n Handlers extends QueueHandlers = QueueCallbacks\n> extends LifecycleCapability {\n readonly #handlers: QueueHandlers;\n readonly #retryDefaults: Required<RetryOptions>;\n readonly #onError: ((error: unknown) => void | Promise<void>) | undefined;\n /**\n * Last due time handed to a job. The Lifecycle driver dispatches due jobs\n * in due-time order, so pushes get strictly increasing times to keep push\n * order (FIFO) even within one millisecond. Seeded from the persisted\n * queue tail on first use so a fresh instance never sorts a new item ahead\n * of items an earlier instance already queued.\n */\n #lastTime: number | null = null;\n\n /**\n * Create a durable Queue.\n *\n * @param options - Registered callbacks plus optional retry and error\n * policy. Registering `callbacks` types {@link push} against the map —\n * names and payloads are checked where the handlers are declared and where\n * they are pushed. Names outside the map are rejected unless a\n * composition-root resolver supplies them — the internal aperture behind\n * `Agent`'s name-based queue API.\n */\n constructor(options: QueueOptions<Handlers> = {}) {\n super(\"queue\");\n this.#handlers = options.callbacks ?? {};\n // Retry defaults are resolved, not validated, here: invalid defaults\n // surface per execution as queue:error instead of bricking the object at\n // construction. Per-item retry overrides are validated when pushed.\n this.#retryDefaults = resolveRetryConfig(options.retry, DEFAULT_RETRY);\n this.#onError = options.onError;\n }\n\n // ── Lifecycle capability hooks ───────────────────────────────────────────\n\n /** Migrate legacy `cf_agents_queues` rows into the Lifecycle job queue. */\n async onStart(): Promise<void> {\n const storage = this.lifecycle.storage;\n const version = (await storage.get<number>(QUEUE_SCHEMA_VERSION_KEY)) ?? 0;\n if (version >= CURRENT_QUEUE_SCHEMA_VERSION) return;\n\n await this.#migrateLegacyQueueTable(storage);\n await storage.put(QUEUE_SCHEMA_VERSION_KEY, CURRENT_QUEUE_SCHEMA_VERSION);\n }\n\n /**\n * Move every `cf_agents_queues` row into the job queue and drop the\n * table. Idempotent: a missing table means a fresh object or a completed\n * migration. Rows keep their insertion order.\n *\n * TEMPORARY: one-shot upgrade path for objects that had queued items when\n * this release landed. Remove in the next minor release (with the schema\n * version bump that gates it), once every deployed object has migrated.\n */\n async #migrateLegacyQueueTable(storage: DurableObjectStorage): Promise<void> {\n const tables = storage.sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name='cf_agents_queues'\"\n )\n .toArray();\n if (tables.length === 0) return;\n\n const rows = storage.sql\n .exec(\"SELECT * FROM cf_agents_queues ORDER BY created_at ASC, rowid ASC\")\n .toArray() as unknown as QueueStorageRow[];\n for (const row of rows) {\n let payload: unknown;\n try {\n payload =\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined;\n } catch (error) {\n console.error(\n `Skipping queue item \"${row.id}\" during job-queue migration: ` +\n \"its payload is not valid JSON\",\n error\n );\n continue;\n }\n let retry: RetryOptions | undefined;\n try {\n retry =\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined;\n } catch {\n retry = undefined;\n }\n await this.lifecycle.jobs.push({\n id: row.id,\n fn: row.callback,\n time: this.#nextTime(),\n payload: {\n payload,\n owner_path: null,\n owner_path_key: null\n } satisfies QueueJobPayload,\n retry: resolveRetryConfig(retry, this.#retryDefaults)\n });\n }\n storage.sql.exec(\"DROP TABLE cf_agents_queues\");\n }\n\n /** Drive one due item dispatched by the Lifecycle event loop. */\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n const { job, attempt } = context;\n if (!isQueueJobPayload(job.payload)) {\n console.error(`Malformed queue item ${job.id}; dropping it`);\n return undefined;\n }\n const item = this.#jobToItem(job, job.payload);\n\n if (attempt > 1) {\n this.#emit(\"queue:retry\", {\n callback: job.fn,\n id: job.id,\n attempt,\n maxAttempts: resolveRetryConfig(job.retry, this.#retryDefaults)\n .maxAttempts\n });\n }\n\n if (job.payload.owner_path) {\n // A routed item executes inside its owning Lifecycle; retries run\n // there too, so this dispatch is a single routed attempt.\n try {\n await this.lifecycle.routes.to(\n {\n key: job.payload.owner_path_key ?? job.payload.owner_path,\n data: job.payload.owner_path\n },\n { type: \"dispatch\", item } satisfies QueueRouteMessage\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n // Preserve the item; Lifecycle defers platform-class failures to\n // a fresh invocation or the memory-limit breaker.\n throw error;\n }\n console.error(`error dispatching queue callback \"${job.fn}\"`, error);\n this.#emit(\"queue:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: 0\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n // Leave the item due so a later alarm cycle can retry dispatch, for\n // example once a transport can resolve its owner again.\n return \"yield\";\n }\n return undefined;\n }\n\n const handler = this.#resolveCallback(job.fn);\n if (!handler) {\n console.error(`callback ${job.fn} not found`);\n return undefined;\n }\n await this.lifecycle.runInHostContext(() => handler(item.payload, item));\n return undefined;\n }\n\n /** Observe one item's terminal application failure; the item is dropped. */\n async onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): Promise<LifecycleJobOutcome | void> {\n const { job } = context;\n const { maxAttempts } = resolveRetryConfig(job.retry, this.#retryDefaults);\n console.error(\n `queue callback \"${job.fn}\" failed after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"queue:error\", {\n callback: job.fn,\n id: job.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n return undefined;\n }\n\n /** Handle Queue protocol messages routed by another Lifecycle. */\n async onRoute(context: LifecycleRouteContext): Promise<unknown> {\n const message = context.payload as QueueRouteMessage;\n const owner = context.source ?? null;\n switch (message.type) {\n case \"push\":\n return this.#insert(\n owner,\n message.callback,\n message.payload,\n message.options\n );\n case \"get\":\n return this.#getForOwner(owner, message.id);\n case \"list\":\n return this.#listForOwner(owner, message.criteria);\n case \"cancel\":\n return this.#cancelForOwner(owner, message.id);\n case \"cancelAll\":\n return this.#cancelAllForOwner(owner, message.callback);\n case \"dispatch\":\n await this.#executeRouted(message.item);\n return true;\n default:\n throw new Error(\"Unknown routed Queue message\");\n }\n }\n\n /**\n * Execute a routed item locally with the historical retry handling. Runs\n * on the owning (facet) Queue, outside the root's event loop, so it applies\n * its own in-process retry budget. Platform-class failures re-throw so the\n * root preserves the item and the durable alarm retries on a fresh\n * invocation.\n */\n async #executeRouted(item: QueueItem<unknown>): Promise<void> {\n const handler = this.#resolveCallback(item.callback);\n if (!handler) {\n console.error(`callback ${item.callback} not found`);\n return;\n }\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n item.retry,\n this.#retryDefaults\n );\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this.#emit(\"queue:retry\", {\n callback: item.callback,\n id: item.id,\n attempt,\n maxAttempts\n });\n }\n await this.lifecycle.runInHostContext(() =>\n handler(item.payload, item)\n );\n },\n {\n baseDelayMs,\n maxDelayMs,\n shouldRetry: (error) => !isDurableObjectCodeUpdateReset(error)\n }\n );\n } catch (error) {\n if (isPlatformFailure(error)) {\n throw error;\n }\n console.error(\n `queue callback \"${item.callback}\" failed after ${maxAttempts} attempts`,\n error\n );\n this.#emit(\"queue:error\", {\n callback: item.callback,\n id: item.id,\n error: error instanceof Error ? error.message : String(error),\n attempts: maxAttempts\n });\n try {\n await this.#onError?.(error);\n } catch {\n // swallow onError errors\n }\n }\n }\n\n // ── Queue API ────────────────────────────────────────────────────────────\n\n /**\n * Push one item for a registered callback. The item is due immediately;\n * the Lifecycle alarm event loop runs it in push order after this call\n * returns.\n *\n * Once the Lifecycle has started (and this Queue is not routed through\n * another Lifecycle), the item row is written synchronously before this\n * method's promise is even returned, so a caller may pair a push with its\n * own writes in one synchronous block — the item then commits atomically\n * with them.\n */\n async push<Name extends keyof Handlers & string>(\n callback: Name,\n payload?: QueuePayload<Handlers[Name]>,\n options?: QueuePushOptions\n ): Promise<QueueItem<QueuePayload<Handlers[Name]>>> {\n if (this.lifecycle.status() !== \"started\") await this.lifecycle.ready();\n this.#validatePush(callback, options);\n const item = this.lifecycle.routes.source\n ? ((await this.lifecycle.routes.toRoot({\n type: \"push\",\n callback,\n payload,\n options\n } satisfies QueueRouteMessage)) as QueueItem<\n QueuePayload<Handlers[Name]>\n >)\n : await this.#insert<QueuePayload<Handlers[Name]>>(\n null,\n callback,\n payload,\n options\n );\n this.#emit(\"queue:create\", { callback, id: item.id });\n return item;\n }\n\n /** Cancel one pending item. Returns false when no item matched. */\n async cancel(id: string): Promise<boolean> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"cancel\",\n id\n } satisfies QueueRouteMessage)) as boolean;\n }\n return this.#cancelForOwner(null, id);\n }\n\n /** Cancel every pending item, or every item for one callback. Returns the count. */\n async cancelAll(callback?: string): Promise<number> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"cancelAll\",\n callback\n } satisfies QueueRouteMessage)) as number;\n }\n return this.#cancelAllForOwner(null, callback);\n }\n\n /** Read one pending item. */\n async get<T = unknown>(id: string): Promise<QueueItem<T> | undefined> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"get\",\n id\n } satisfies QueueRouteMessage)) as QueueItem<T> | undefined;\n }\n return this.#getForOwner<T>(null, id);\n }\n\n /** List pending items in push order, optionally filtered by callback. */\n async list<T = unknown>(criteria?: QueueCriteria): Promise<QueueItem<T>[]> {\n await this.lifecycle.ready();\n if (this.lifecycle.routes.source) {\n return (await this.lifecycle.routes.toRoot({\n type: \"list\",\n criteria\n } satisfies QueueRouteMessage)) as QueueItem<T>[];\n }\n return this.#listForOwner<T>(null, criteria);\n }\n\n // ── Internals ────────────────────────────────────────────────────────────\n\n #validatePush(callback: string, options?: QueuePushOptions): void {\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n if (!this.#hasCallback(callback)) {\n throw new Error(\n `Unknown queue callback \"${callback}\": not registered on this Queue`\n );\n }\n if (options?.retry)\n validateRetryOptions(options.retry, this.#retryDefaults);\n if (options?.id !== undefined && options.id.trim() === \"\") {\n throw new Error(\"Queue item ids must be non-empty\");\n }\n }\n\n /** Resolve a name to its registered or composition-root-supplied handler. */\n #resolveCallback(name: string): ResolvedQueueCallback | undefined {\n const handler = this.#handlers[name];\n if (handler) {\n // SAFETY: registered handlers are constrained with `never` parameters\n // so concrete handler types satisfy the map under contravariance; the\n // payload passed at dispatch was persisted with this handler's name.\n return handler as ResolvedQueueCallback;\n }\n return queueCallbackResolvers.get(this)?.(name);\n }\n\n #hasCallback(name: string): boolean {\n return this.#resolveCallback(name) !== undefined;\n }\n\n /** The next strictly increasing due time, never before now. */\n #nextTime(): number {\n if (this.#lastTime === null) {\n this.#lastTime = this.#ownedJobs().reduce(\n (lastTime, { job }) => Math.max(lastTime, job.time),\n 0\n );\n }\n const time = Math.max(Date.now(), this.#lastTime + 1);\n this.#lastTime = time;\n return time;\n }\n\n async #insert<T>(\n owner: LifecycleRouteAddress | null,\n callback: string,\n payload: unknown,\n options?: QueuePushOptions\n ): Promise<QueueItem<T>> {\n // A stable-id push replaces the item in place: it keeps the existing\n // item's due time, and so its position in the queue.\n const existing =\n options?.id !== undefined\n ? this.lifecycle.jobs.get(options.id)\n : undefined;\n const keepTime =\n existing !== undefined &&\n this.#getForOwner(owner, existing.id) !== undefined;\n const job = await this.lifecycle.jobs.push({\n id: options?.id,\n fn: callback,\n time: keepTime ? existing.time : this.#nextTime(),\n payload: {\n payload,\n owner_path: owner?.data ?? null,\n owner_path_key: owner?.key ?? null\n } satisfies QueueJobPayload,\n retry: resolveRetryConfig(options?.retry, this.#retryDefaults)\n });\n return this.#jobToItem<T>(job, job.payload as QueueJobPayload);\n }\n\n #jobToItem<T>(job: LifecycleJob, envelope: QueueJobPayload): QueueItem<T> {\n return {\n id: job.id,\n callback: job.fn,\n payload: envelope.payload as T,\n createdAt: job.createdAt,\n retry: job.retry\n };\n }\n\n /** Every queue job this Queue owns, in push order. */\n #ownedJobs(): Array<{ job: LifecycleJob; envelope: QueueJobPayload }> {\n const owned: Array<{ job: LifecycleJob; envelope: QueueJobPayload }> = [];\n for (const job of this.lifecycle.jobs.list()) {\n if (isQueueJobPayload(job.payload)) {\n owned.push({ job, envelope: job.payload });\n }\n }\n return owned;\n }\n\n #getForOwner<T>(\n owner: LifecycleRouteAddress | null,\n id: string\n ): QueueItem<T> | undefined {\n const ownerKey = owner?.key ?? null;\n const job = this.lifecycle.jobs.get(id);\n if (!job || !isQueueJobPayload(job.payload)) return undefined;\n if ((job.payload.owner_path_key ?? null) !== ownerKey) return undefined;\n return this.#jobToItem<T>(job, job.payload);\n }\n\n #listForOwner<T>(\n owner: LifecycleRouteAddress | null,\n criteria: QueueCriteria = {}\n ): QueueItem<T>[] {\n const ownerKey = owner?.key ?? null;\n const items: QueueItem<T>[] = [];\n for (const { job, envelope } of this.#ownedJobs()) {\n if ((envelope.owner_path_key ?? null) !== ownerKey) continue;\n if (criteria.callback && job.fn !== criteria.callback) continue;\n items.push(this.#jobToItem<T>(job, envelope));\n }\n return items;\n }\n\n async #cancelForOwner(\n owner: LifecycleRouteAddress | null,\n id: string\n ): Promise<boolean> {\n if (!this.#getForOwner(owner, id)) return false;\n return this.lifecycle.jobs.cancel(id);\n }\n\n async #cancelAllForOwner(\n owner: LifecycleRouteAddress | null,\n callback?: string\n ): Promise<number> {\n let cancelled = 0;\n for (const item of this.#listForOwner(owner, { callback })) {\n if (await this.lifecycle.jobs.cancel(item.id)) cancelled++;\n }\n return cancelled;\n }\n\n /** @internal Remove items owned by one routed Lifecycle subtree. */\n async __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(\n prefix: string\n ): Promise<void> {\n for (const { job, envelope } of this.#ownedJobs()) {\n const ownerKey = envelope.owner_path_key ?? envelope.owner_path;\n if (!envelope.owner_path || ownerKey === null) continue;\n if (ownerKey !== prefix && !ownerKey.startsWith(`${prefix}/`)) continue;\n await this.lifecycle.jobs.cancel(job.id);\n }\n }\n\n // ── Events ───────────────────────────────────────────────────────────────\n\n #emit(type: QueueEventType, payload: Record<string, unknown>): void {\n this.lifecycle.events.emit(type, payload);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA4CA,MAAM,yCAAyB,IAAI,QAGjC;;;;;;;;AASF,SAAgB,yBACd,OACA,UACM;CACN,uBAAuB,IAAI,OAAO,QAAQ;AAC5C;AAEA,MAAM,2BAA2B;;AAEjC,MAAM,+BAA+B;AAErC,MAAM,gBAAwC;CAC5C,aAAa;CACb,aAAa;CACb,YAAY;AACd;AAwBA,SAAS,kBAAkB,OAA0C;CAEnE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,gBAAgB;AACxE;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,QAAb,cAEU,oBAAoB;;;;;;;;;;;CAuB5B,YAAY,UAAkC,CAAC,GAAG;EAChD,MAAM,OAAO;;;;;8CAbY,IAAA;EAczB,uBAAA,WAAA,MAAiB,QAAQ,aAAa,CAAC,CAAA;EAI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C9D,OAAA,kBAAA,cAAO,MAAA,UAAA,CAAA,CAAA,KAAA,MAAmB,KAAK,IAAI,OAAO;AAC5C;AAEA,SAAA,cACE,OACA,WAA0B,CAAC,GACX;CAChB,MAAM,WAAW,OAAO,OAAO;CAC/B,MAAM,QAAwB,CAAC;CAC/B,KAAK,MAAM,EAAE,KAAK,cAAA,kBAAA,cAAc,MAAA,UAAA,CAAA,CAAA,KAAA,IAAgB,GAAG;EACjD,KAAK,SAAS,kBAAkB,UAAU,UAAU;EACpD,IAAI,SAAS,YAAY,IAAI,OAAO,SAAS,UAAU;EACvD,MAAM,KAAA,kBAAA,cAAK,MAAA,UAAA,CAAA,CAAA,KAAA,MAAmB,KAAK,QAAQ,CAAC;CAC9C;CACA,OAAO;AACT;AAEA,eAAA,gBACE,OACA,IACkB;CAClB,IAAI,CAAA,kBAAA,cAAC,MAAA,YAAA,CAAA,CAAA,KAAA,MAAkB,OAAO,EAAE,GAAG,OAAO;CAC1C,OAAO,KAAK,UAAU,KAAK,OAAO,EAAE;AACtC;AAEA,eAAA,mBACE,OACA,UACiB;CACjB,IAAI,YAAY;CAChB,KAAK,MAAM,QAAA,kBAAA,cAAQ,MAAA,aAAA,CAAA,CAAA,KAAA,MAAmB,OAAO,EAAE,SAAS,CAAC,GACvD,IAAI,MAAM,KAAK,UAAU,KAAK,OAAO,KAAK,EAAE,GAAG;CAEjD,OAAO;AACT;AAgBA,SAAA,MAAM,MAAsB,SAAwC;CAClE,KAAK,UAAU,OAAO,KAAK,MAAM,OAAO;AAC1C"}
package/dist/react.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import {
2
2
  C as MCPServersState,
3
- J as AgentToolRunState,
4
- q as AgentToolRunPart
5
- } from "./agent-routing-B2XLNMxq.js";
3
+ J as AgentToolRunPart,
4
+ Y as AgentToolRunState
5
+ } from "./agent-routing-0DR0Tk2v.js";
6
6
  import { ClientParameters } from "./serializable.js";
7
7
  import { t as AgentTransport } from "./transport-protocol-ZTew5Wso.js";
8
8
  import {
9
- _ as createStubProxy,
10
9
  c as CallOptions,
11
10
  d as OptionalAgentMethods,
12
11
  h as UntypedAgentStub,
@@ -14,8 +13,9 @@ import {
14
13
  m as StreamOptions,
15
14
  o as AgentPromiseReturnType,
16
15
  p as RequiredAgentMethods,
17
- s as AgentStub
18
- } from "./client-BxdkCuVy.js";
16
+ s as AgentStub,
17
+ v as createStubProxy
18
+ } from "./client-je3koD9Z.js";
19
19
  import { PartySocket } from "partysocket";
20
20
  import { usePartySocket } from "partysocket/react";
21
21