@cloudflare/ai-chat 0.1.5 → 0.1.7

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 (67) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +150 -36
  6. package/dist/index.js.map +1 -1
  7. package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
  8. package/dist/message-builder-uSvexDl2.js.map +1 -0
  9. package/dist/react.js +96 -10
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -251
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/tests/ws-transport-abort.test.ts +0 -198
  64. package/src/types.ts +0 -152
  65. package/src/ws-chat-transport.ts +0 -227
  66. package/tsconfig.json +0 -4
  67. package/vitest.config.ts +0 -7
@@ -96,7 +96,10 @@ function applyChunkToParts(parts, chunk) {
96
96
  toolCallId: chunk.toolCallId,
97
97
  toolName: chunk.toolName,
98
98
  state: "input-streaming",
99
- input: void 0
99
+ input: void 0,
100
+ ...chunk.providerExecuted != null ? { providerExecuted: chunk.providerExecuted } : {},
101
+ ...chunk.providerMetadata != null ? { callProviderMetadata: chunk.providerMetadata } : {},
102
+ ...chunk.title != null ? { title: chunk.title } : {}
100
103
  });
101
104
  return true;
102
105
  case "tool-input-delta": {
@@ -110,12 +113,18 @@ function applyChunkToParts(parts, chunk) {
110
113
  const p = existing;
111
114
  p.state = "input-available";
112
115
  p.input = chunk.input;
116
+ if (chunk.providerExecuted != null) p.providerExecuted = chunk.providerExecuted;
117
+ if (chunk.providerMetadata != null) p.callProviderMetadata = chunk.providerMetadata;
118
+ if (chunk.title != null) p.title = chunk.title;
113
119
  } else parts.push({
114
120
  type: `tool-${chunk.toolName}`,
115
121
  toolCallId: chunk.toolCallId,
116
122
  toolName: chunk.toolName,
117
123
  state: "input-available",
118
- input: chunk.input
124
+ input: chunk.input,
125
+ ...chunk.providerExecuted != null ? { providerExecuted: chunk.providerExecuted } : {},
126
+ ...chunk.providerMetadata != null ? { callProviderMetadata: chunk.providerMetadata } : {},
127
+ ...chunk.title != null ? { title: chunk.title } : {}
119
128
  });
120
129
  return true;
121
130
  }
@@ -126,13 +135,17 @@ function applyChunkToParts(parts, chunk) {
126
135
  p.state = "output-error";
127
136
  p.errorText = chunk.errorText;
128
137
  p.input = chunk.input;
138
+ if (chunk.providerExecuted != null) p.providerExecuted = chunk.providerExecuted;
139
+ if (chunk.providerMetadata != null) p.callProviderMetadata = chunk.providerMetadata;
129
140
  } else parts.push({
130
141
  type: `tool-${chunk.toolName}`,
131
142
  toolCallId: chunk.toolCallId,
132
143
  toolName: chunk.toolName,
133
144
  state: "output-error",
134
145
  input: chunk.input,
135
- errorText: chunk.errorText
146
+ errorText: chunk.errorText,
147
+ ...chunk.providerExecuted != null ? { providerExecuted: chunk.providerExecuted } : {},
148
+ ...chunk.providerMetadata != null ? { callProviderMetadata: chunk.providerMetadata } : {}
136
149
  });
137
150
  return true;
138
151
  }
@@ -228,4 +241,4 @@ function findDataPartByTypeAndId(parts, type, id) {
228
241
 
229
242
  //#endregion
230
243
  export { applyChunkToParts as t };
231
- //# sourceMappingURL=message-builder-Bwc_Umye.js.map
244
+ //# sourceMappingURL=message-builder-uSvexDl2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message-builder-uSvexDl2.js","names":[],"sources":["../src/message-builder.ts"],"sourcesContent":["/**\n * Shared message builder for reconstructing UIMessage parts from stream chunks.\n *\n * Used by both the server (_streamSSEReply) and client (onAgentMessage in react.tsx)\n * to avoid duplicating the chunk-type switch/case logic. The server handles additional\n * chunk types (tool-input-start, tool-input-delta, etc.) on top of this shared base.\n *\n * Operates on a mutable parts array for performance (avoids allocating new arrays\n * on every chunk during streaming).\n */\n\nimport type { UIMessage } from \"ai\";\n\n/** The parts array type from UIMessage */\nexport type MessageParts = UIMessage[\"parts\"];\n\n/** A single part from the UIMessage parts array */\nexport type MessagePart = MessageParts[number];\n\n/**\n * Parsed chunk data from an AI SDK stream event.\n * This is the JSON-parsed body of a CF_AGENT_USE_CHAT_RESPONSE message,\n * or the `data:` payload of an SSE line.\n */\nexport type StreamChunkData = {\n type: string;\n id?: string;\n delta?: string;\n text?: string;\n mediaType?: string;\n url?: string;\n sourceId?: string;\n title?: string;\n filename?: string;\n toolCallId?: string;\n toolName?: string;\n input?: unknown;\n inputTextDelta?: string;\n output?: unknown;\n state?: string;\n errorText?: string;\n /** When true, the output is preliminary (may be updated by a later chunk) */\n preliminary?: boolean;\n /** Approval ID for tools with needsApproval */\n approvalId?: string;\n providerMetadata?: Record<string, unknown>;\n /** Whether the tool was executed by the provider (e.g. Gemini code execution) */\n providerExecuted?: boolean;\n /** Payload for data-* parts (developer-defined typed JSON) */\n data?: unknown;\n /** When true, data parts are ephemeral and not persisted to message.parts */\n transient?: boolean;\n [key: string]: unknown;\n};\n\n/**\n * Applies a stream chunk to a mutable parts array, building up the message\n * incrementally. Returns true if the chunk was handled, false if it was\n * an unrecognized type (caller may handle it with additional logic).\n *\n * Handles all common chunk types that both server and client need:\n * - text-start / text-delta / text-end\n * - reasoning-start / reasoning-delta / reasoning-end\n * - file\n * - source-url / source-document\n * - tool-input-start / tool-input-delta / tool-input-available / tool-input-error\n * - tool-output-available / tool-output-error\n * - step-start (aliased from start-step)\n * - data-* (developer-defined typed JSON blobs)\n *\n * @param parts - The mutable parts array to update\n * @param chunk - The parsed stream chunk data\n * @returns true if handled, false if the chunk type is not recognized\n */\nexport function applyChunkToParts(\n parts: MessagePart[],\n chunk: StreamChunkData\n): boolean {\n switch (chunk.type) {\n case \"text-start\": {\n parts.push({\n type: \"text\",\n text: \"\",\n state: \"streaming\"\n } as MessagePart);\n return true;\n }\n\n case \"text-delta\": {\n const lastTextPart = findLastPartByType(parts, \"text\");\n if (lastTextPart && lastTextPart.type === \"text\") {\n (lastTextPart as { text: string }).text += chunk.delta ?? \"\";\n } else {\n // No text-start received — create a new text part (stream resumption fallback)\n parts.push({\n type: \"text\",\n text: chunk.delta ?? \"\",\n state: \"streaming\"\n } as MessagePart);\n }\n return true;\n }\n\n case \"text-end\": {\n const lastTextPart = findLastPartByType(parts, \"text\");\n if (lastTextPart && \"state\" in lastTextPart) {\n (lastTextPart as { state: string }).state = \"done\";\n }\n return true;\n }\n\n case \"reasoning-start\": {\n parts.push({\n type: \"reasoning\",\n text: \"\",\n state: \"streaming\"\n } as MessagePart);\n return true;\n }\n\n case \"reasoning-delta\": {\n const lastReasoningPart = findLastPartByType(parts, \"reasoning\");\n if (lastReasoningPart && lastReasoningPart.type === \"reasoning\") {\n (lastReasoningPart as { text: string }).text += chunk.delta ?? \"\";\n } else {\n // No reasoning-start received — create a new reasoning part (stream resumption fallback)\n parts.push({\n type: \"reasoning\",\n text: chunk.delta ?? \"\",\n state: \"streaming\"\n } as MessagePart);\n }\n return true;\n }\n\n case \"reasoning-end\": {\n const lastReasoningPart = findLastPartByType(parts, \"reasoning\");\n if (lastReasoningPart && \"state\" in lastReasoningPart) {\n (lastReasoningPart as { state: string }).state = \"done\";\n }\n return true;\n }\n\n case \"file\": {\n parts.push({\n type: \"file\",\n mediaType: chunk.mediaType,\n url: chunk.url\n } as MessagePart);\n return true;\n }\n\n case \"source-url\": {\n parts.push({\n type: \"source-url\",\n sourceId: chunk.sourceId,\n url: chunk.url,\n title: chunk.title,\n providerMetadata: chunk.providerMetadata\n } as MessagePart);\n return true;\n }\n\n case \"source-document\": {\n parts.push({\n type: \"source-document\",\n sourceId: chunk.sourceId,\n mediaType: chunk.mediaType,\n title: chunk.title,\n filename: chunk.filename,\n providerMetadata: chunk.providerMetadata\n } as MessagePart);\n return true;\n }\n\n case \"tool-input-start\": {\n // Create a tool part in input-streaming state with no input yet.\n // Cross-tab clients see the tool appear immediately with \"streaming\" indicator.\n parts.push({\n type: `tool-${chunk.toolName}`,\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-streaming\",\n input: undefined,\n ...(chunk.providerExecuted != null\n ? { providerExecuted: chunk.providerExecuted }\n : {}),\n ...(chunk.providerMetadata != null\n ? { callProviderMetadata: chunk.providerMetadata }\n : {}),\n ...(chunk.title != null ? { title: chunk.title } : {})\n } as MessagePart);\n return true;\n }\n\n case \"tool-input-delta\": {\n // Update the existing tool part with partial input as it streams in.\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n (toolPart as Record<string, unknown>).input = chunk.input;\n }\n return true;\n }\n\n case \"tool-input-available\": {\n // Finalize the tool input. If tool-input-start was received, update\n // the existing part; otherwise create a new one (for non-streaming tools).\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (existing) {\n const p = existing as Record<string, unknown>;\n p.state = \"input-available\";\n p.input = chunk.input;\n if (chunk.providerExecuted != null) {\n p.providerExecuted = chunk.providerExecuted;\n }\n if (chunk.providerMetadata != null) {\n p.callProviderMetadata = chunk.providerMetadata;\n }\n if (chunk.title != null) {\n p.title = chunk.title;\n }\n } else {\n parts.push({\n type: `tool-${chunk.toolName}`,\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-available\",\n input: chunk.input,\n ...(chunk.providerExecuted != null\n ? { providerExecuted: chunk.providerExecuted }\n : {}),\n ...(chunk.providerMetadata != null\n ? { callProviderMetadata: chunk.providerMetadata }\n : {}),\n ...(chunk.title != null ? { title: chunk.title } : {})\n } as MessagePart);\n }\n return true;\n }\n\n case \"tool-input-error\": {\n // Tool input parsing failed. Update existing part or create one.\n const existing = findToolPartByCallId(parts, chunk.toolCallId);\n if (existing) {\n const p = existing as Record<string, unknown>;\n p.state = \"output-error\";\n p.errorText = chunk.errorText;\n p.input = chunk.input;\n if (chunk.providerExecuted != null) {\n p.providerExecuted = chunk.providerExecuted;\n }\n if (chunk.providerMetadata != null) {\n p.callProviderMetadata = chunk.providerMetadata;\n }\n } else {\n parts.push({\n type: `tool-${chunk.toolName}`,\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"output-error\",\n input: chunk.input,\n errorText: chunk.errorText,\n ...(chunk.providerExecuted != null\n ? { providerExecuted: chunk.providerExecuted }\n : {}),\n ...(chunk.providerMetadata != null\n ? { callProviderMetadata: chunk.providerMetadata }\n : {})\n } as MessagePart);\n }\n return true;\n }\n\n case \"tool-approval-request\": {\n // Tool requires user approval before executing.\n // Transition the tool part to approval-requested state with the approval ID.\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n p.state = \"approval-requested\";\n p.approval = { id: chunk.approvalId };\n }\n return true;\n }\n\n case \"tool-output-denied\": {\n // User rejected the tool approval request.\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n p.state = \"output-denied\";\n }\n return true;\n }\n\n case \"tool-output-available\": {\n // Update existing tool part with output.\n // Supports `preliminary: true` for streaming tool results —\n // the output may be updated by a subsequent chunk.\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n p.state = \"output-available\";\n p.output = chunk.output;\n if (chunk.preliminary !== undefined) {\n p.preliminary = chunk.preliminary;\n }\n }\n return true;\n }\n\n case \"tool-output-error\": {\n // Tool execution failed. Update the existing tool part.\n const toolPart = findToolPartByCallId(parts, chunk.toolCallId);\n if (toolPart) {\n const p = toolPart as Record<string, unknown>;\n p.state = \"output-error\";\n p.errorText = chunk.errorText;\n }\n return true;\n }\n\n // Both \"step-start\" (client convention) and \"start-step\" (server convention)\n case \"step-start\":\n case \"start-step\": {\n parts.push({ type: \"step-start\" } as MessagePart);\n return true;\n }\n\n default: {\n // https://ai-sdk.dev/docs/ai-sdk-ui/streaming-data\n if (chunk.type.startsWith(\"data-\")) {\n // Transient parts are ephemeral — the AI SDK client fires an onData\n // callback instead of adding them to message.parts. On the server we\n // still broadcast them (so connected clients see them in real time)\n // but skip persisting them into the stored message parts.\n if (chunk.transient) {\n return true;\n }\n\n // Reconciliation: if a part with the same type AND id already exists,\n // update its data in-place instead of appending a duplicate.\n if (chunk.id != null) {\n const existing = findDataPartByTypeAndId(parts, chunk.type, chunk.id);\n if (existing) {\n (existing as Record<string, unknown>).data = chunk.data;\n return true;\n }\n }\n\n // Append new data parts to the array directly.\n // Note: `chunk.data` should always be provided — if omitted, the\n // persisted part will have `data: undefined` which JSON.stringify\n // drops, so the part will have no `data` field on reload.\n // The cast is needed because UIMessage[\"parts\"] doesn't include\n // data-* types in its union because they're an open extension point.\n parts.push({\n type: chunk.type,\n ...(chunk.id != null && { id: chunk.id }),\n data: chunk.data\n } as MessagePart);\n return true;\n }\n\n return false;\n }\n }\n}\n\n/**\n * Finds the last part in the array matching the given type.\n * Searches from the end for efficiency (the part we want is usually recent).\n */\nfunction findLastPartByType(\n parts: MessagePart[],\n type: string\n): MessagePart | undefined {\n for (let i = parts.length - 1; i >= 0; i--) {\n if (parts[i].type === type) {\n return parts[i];\n }\n }\n return undefined;\n}\n\n/**\n * Finds a tool part by its toolCallId.\n * Searches from the end since the tool part is usually recent.\n */\nfunction findToolPartByCallId(\n parts: MessagePart[],\n toolCallId: string | undefined\n): MessagePart | undefined {\n if (!toolCallId) return undefined;\n for (let i = parts.length - 1; i >= 0; i--) {\n const p = parts[i];\n if (\"toolCallId\" in p && p.toolCallId === toolCallId) {\n return p;\n }\n }\n return undefined;\n}\n\n/**\n * Finds a data part by its type and id for reconciliation.\n * Data parts use type+id as a composite key so when the same combination\n * is seen again, the existing part's data is updated in-place.\n */\nfunction findDataPartByTypeAndId(\n parts: MessagePart[],\n type: string,\n id: string\n): MessagePart | undefined {\n for (let i = parts.length - 1; i >= 0; i--) {\n const p = parts[i];\n if (p.type === type && \"id\" in p && (p as { id: string }).id === id) {\n return p;\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,kBACd,OACA,OACS;AACT,SAAQ,MAAM,MAAd;EACE,KAAK;AACH,SAAM,KAAK;IACT,MAAM;IACN,MAAM;IACN,OAAO;IACR,CAAgB;AACjB,UAAO;EAGT,KAAK,cAAc;GACjB,MAAM,eAAe,mBAAmB,OAAO,OAAO;AACtD,OAAI,gBAAgB,aAAa,SAAS,OACxC,CAAC,aAAkC,QAAQ,MAAM,SAAS;OAG1D,OAAM,KAAK;IACT,MAAM;IACN,MAAM,MAAM,SAAS;IACrB,OAAO;IACR,CAAgB;AAEnB,UAAO;;EAGT,KAAK,YAAY;GACf,MAAM,eAAe,mBAAmB,OAAO,OAAO;AACtD,OAAI,gBAAgB,WAAW,aAC7B,CAAC,aAAmC,QAAQ;AAE9C,UAAO;;EAGT,KAAK;AACH,SAAM,KAAK;IACT,MAAM;IACN,MAAM;IACN,OAAO;IACR,CAAgB;AACjB,UAAO;EAGT,KAAK,mBAAmB;GACtB,MAAM,oBAAoB,mBAAmB,OAAO,YAAY;AAChE,OAAI,qBAAqB,kBAAkB,SAAS,YAClD,CAAC,kBAAuC,QAAQ,MAAM,SAAS;OAG/D,OAAM,KAAK;IACT,MAAM;IACN,MAAM,MAAM,SAAS;IACrB,OAAO;IACR,CAAgB;AAEnB,UAAO;;EAGT,KAAK,iBAAiB;GACpB,MAAM,oBAAoB,mBAAmB,OAAO,YAAY;AAChE,OAAI,qBAAqB,WAAW,kBAClC,CAAC,kBAAwC,QAAQ;AAEnD,UAAO;;EAGT,KAAK;AACH,SAAM,KAAK;I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AS,QAAQ,QAAQ,KAAM,EAAqB,OAAO,GAC/D,QAAO"}
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MessageType } from "./types.js";
2
- import { t as applyChunkToParts } from "./message-builder-Bwc_Umye.js";
2
+ import { t as applyChunkToParts } from "./message-builder-uSvexDl2.js";
3
3
  import { getToolName, isToolUIPart } from "ai";
4
4
  import { nanoid } from "nanoid";
5
5
  import { useChat } from "@ai-sdk/react";
@@ -13,10 +13,22 @@ import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
13
13
  */
14
14
  var WebSocketChatTransport = class {
15
15
  constructor(options) {
16
+ this._resumeResolver = null;
16
17
  this.agent = options.agent;
17
18
  this.prepareBody = options.prepareBody;
18
19
  this.activeRequestIds = options.activeRequestIds;
19
20
  }
21
+ /**
22
+ * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUMING.
23
+ * If reconnectToStream is waiting, this handles the resume handshake
24
+ * (ACK + stream creation) and returns true. Otherwise returns false
25
+ * so the caller can use its own fallback path.
26
+ */
27
+ handleStreamResuming(data) {
28
+ if (!this._resumeResolver) return false;
29
+ this._resumeResolver(data);
30
+ return true;
31
+ }
20
32
  async sendMessages(options) {
21
33
  const requestId = nanoid(8);
22
34
  const abortController = new AbortController();
@@ -33,6 +45,7 @@ var WebSocketChatTransport = class {
33
45
  };
34
46
  const bodyPayload = JSON.stringify({
35
47
  messages: options.messages,
48
+ trigger: options.trigger,
36
49
  ...extraBody
37
50
  });
38
51
  this.activeRequestIds?.add(requestId);
@@ -69,7 +82,7 @@ var WebSocketChatTransport = class {
69
82
  if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
70
83
  if (data.id !== requestId) return;
71
84
  if (data.error) {
72
- finish(() => controller.error(new Error(data.body)));
85
+ finish(() => controller.error(new Error(data.body || "Stream error")));
73
86
  return;
74
87
  }
75
88
  if (data.body?.trim()) try {
@@ -100,7 +113,74 @@ var WebSocketChatTransport = class {
100
113
  return stream;
101
114
  }
102
115
  async reconnectToStream(_options) {
103
- return null;
116
+ const activeIds = this.activeRequestIds;
117
+ return new Promise((resolve) => {
118
+ let resolved = false;
119
+ let timeout;
120
+ const done = (value) => {
121
+ if (resolved) return;
122
+ resolved = true;
123
+ this._resumeResolver = null;
124
+ if (timeout) clearTimeout(timeout);
125
+ resolve(value);
126
+ };
127
+ this._resumeResolver = (data) => {
128
+ const requestId = data.id;
129
+ activeIds?.add(requestId);
130
+ this.agent.send(JSON.stringify({
131
+ type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
132
+ id: requestId
133
+ }));
134
+ done(this._createResumeStream(requestId));
135
+ };
136
+ try {
137
+ this.agent.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST }));
138
+ } catch {}
139
+ timeout = setTimeout(() => done(null), 5e3);
140
+ });
141
+ }
142
+ /**
143
+ * Creates a ReadableStream that receives resumed stream chunks
144
+ * and forwards them to useChat as UIMessageChunk objects.
145
+ */
146
+ _createResumeStream(requestId) {
147
+ const agent = this.agent;
148
+ const activeIds = this.activeRequestIds;
149
+ const chunkController = new AbortController();
150
+ let completed = false;
151
+ const finish = (action) => {
152
+ if (completed) return;
153
+ completed = true;
154
+ try {
155
+ action();
156
+ } catch {}
157
+ activeIds?.delete(requestId);
158
+ chunkController.abort();
159
+ };
160
+ return new ReadableStream({
161
+ start(controller) {
162
+ const onMessage = (event) => {
163
+ try {
164
+ const data = JSON.parse(event.data);
165
+ if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
166
+ if (data.id !== requestId) return;
167
+ if (data.error) {
168
+ finish(() => controller.error(new Error(data.body || "Stream error")));
169
+ return;
170
+ }
171
+ if (data.body?.trim()) try {
172
+ const chunk = JSON.parse(data.body);
173
+ controller.enqueue(chunk);
174
+ } catch {}
175
+ if (data.done) finish(() => controller.close());
176
+ } catch {}
177
+ };
178
+ agent.addEventListener("message", onMessage, { signal: chunkController.signal });
179
+ },
180
+ cancel() {
181
+ finish(() => {});
182
+ }
183
+ });
104
184
  }
105
185
  };
106
186
 
@@ -234,7 +314,8 @@ function useAgentChat(options) {
234
314
  * Used by onAgentMessage to skip messages already handled by the transport.
235
315
  */
236
316
  const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
237
- const customTransport = useMemo(() => new WebSocketChatTransport({
317
+ const customTransportRef = useRef(null);
318
+ if (customTransportRef.current === null) customTransportRef.current = new WebSocketChatTransport({
238
319
  agent: agentRef.current,
239
320
  activeRequestIds: localRequestIdsRef.current,
240
321
  prepareBody: async ({ messages: msgs, trigger, messageId }) => {
@@ -247,7 +328,7 @@ function useAgentChat(options) {
247
328
  }
248
329
  if (prepareSendMessagesRequestRef.current) {
249
330
  const userResult = await prepareSendMessagesRequestRef.current({
250
- id: agent._pk,
331
+ id: agentRef.current._pk,
251
332
  messages: msgs,
252
333
  trigger,
253
334
  messageId
@@ -256,13 +337,16 @@ function useAgentChat(options) {
256
337
  }
257
338
  return extraBody;
258
339
  }
259
- }), [agent._pk]);
340
+ });
341
+ customTransportRef.current.agent = agentRef.current;
342
+ const customTransport = customTransportRef.current;
260
343
  const useChatHelpers = useChat({
261
344
  ...rest,
262
345
  onData,
263
346
  messages: initialMessages,
264
347
  transport: customTransport,
265
- id: agent._pk
348
+ id: initialMessagesCacheKey,
349
+ resume
266
350
  });
267
351
  const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage } = useChatHelpers;
268
352
  const processedToolCalls = useRef(/* @__PURE__ */ new Set());
@@ -475,6 +559,8 @@ function useAgentChat(options) {
475
559
  break;
476
560
  case MessageType.CF_AGENT_STREAM_RESUMING:
477
561
  if (!resume) return;
562
+ if (customTransport.handleStreamResuming(data)) return;
563
+ if (localRequestIdsRef.current.has(data.id)) return;
478
564
  activeStreamRef.current = null;
479
565
  activeStreamRef.current = {
480
566
  id: data.id,
@@ -529,13 +615,12 @@ function useAgentChat(options) {
529
615
  if (data.done || data.error) {
530
616
  if (isReplay && activeMsg) flushActiveStreamToMessages(activeMsg);
531
617
  activeStreamRef.current = null;
532
- }
618
+ } else if (data.replayComplete && activeMsg) flushActiveStreamToMessages(activeMsg);
533
619
  break;
534
620
  }
535
621
  }
536
622
  }
537
623
  agent.addEventListener("message", onAgentMessage);
538
- if (resume) agent.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST }));
539
624
  return () => {
540
625
  agent.removeEventListener("message", onAgentMessage);
541
626
  activeStreamRef.current = null;
@@ -544,7 +629,8 @@ function useAgentChat(options) {
544
629
  agent,
545
630
  setMessages,
546
631
  resume,
547
- flushActiveStreamToMessages
632
+ flushActiveStreamToMessages,
633
+ customTransport
548
634
  ]);
549
635
  const addToolResultAndSendMessage = async (args) => {
550
636
  const { toolCallId } = args;