@cloudflare/ai-chat 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/experimental/forever.d.ts +4 -13
- package/dist/experimental/forever.js +1 -46
- package/dist/experimental/forever.js.map +1 -1
- package/dist/index.d.ts +59 -4
- package/dist/index.js +170 -28
- package/dist/index.js.map +1 -1
- package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
- package/dist/message-builder-uSvexDl2.js.map +1 -0
- package/dist/react.js +125 -31
- package/dist/react.js.map +1 -1
- package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
- package/dist/types.d.ts +2 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -3
- package/CHANGELOG.md +0 -244
- package/dist/message-builder-Bwc_Umye.js.map +0 -1
- package/e2e/chat.spec.ts +0 -1703
- package/e2e/client-tools.spec.ts +0 -504
- package/e2e/llm.spec.ts +0 -637
- package/e2e/playwright.config.ts +0 -27
- package/e2e/worker.ts +0 -174
- package/e2e/wrangler.jsonc +0 -23
- package/scripts/build.ts +0 -32
- package/src/ai-chat-v5-migration.ts +0 -403
- package/src/experimental/forever.ts +0 -66
- package/src/index.ts +0 -2269
- package/src/message-builder.ts +0 -384
- package/src/react-tests/setup.ts +0 -3
- package/src/react-tests/use-agent-chat.test.tsx +0 -1435
- package/src/react-tests/vitest.config.ts +0 -20
- package/src/react.tsx +0 -1447
- package/src/resumable-stream.ts +0 -441
- package/src/tests/cancel-request.test.ts +0 -280
- package/src/tests/chat-context.test.ts +0 -85
- package/src/tests/chat-persistence.test.ts +0 -426
- package/src/tests/clear-history.test.ts +0 -132
- package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
- package/src/tests/client-tools-broadcast.test.ts +0 -138
- package/src/tests/client-tools-continuation.test.ts +0 -314
- package/src/tests/client-tools-reconnect.test.ts +0 -143
- package/src/tests/cloudflare-test.d.ts +0 -5
- package/src/tests/custom-body-continuation.test.ts +0 -309
- package/src/tests/custom-body.test.ts +0 -186
- package/src/tests/destroy.test.ts +0 -57
- package/src/tests/get-messages-endpoint.test.ts +0 -153
- package/src/tests/max-persisted-messages.test.ts +0 -201
- package/src/tests/merge-server-state.test.ts +0 -343
- package/src/tests/message-builder.test.ts +0 -808
- package/src/tests/migration.test.ts +0 -282
- package/src/tests/non-sse-response.test.ts +0 -186
- package/src/tests/onfinish-cleanup.test.ts +0 -362
- package/src/tests/plaintext-response.test.ts +0 -87
- package/src/tests/request-id.test.ts +0 -312
- package/src/tests/resumable-streaming.test.ts +0 -758
- package/src/tests/row-size-guard.test.ts +0 -374
- package/src/tests/sanitize-messages.test.ts +0 -325
- package/src/tests/test-utils.ts +0 -39
- package/src/tests/tsconfig.json +0 -10
- package/src/tests/validate-messages.test.ts +0 -269
- package/src/tests/vitest.config.ts +0 -30
- package/src/tests/worker.ts +0 -456
- package/src/tests/wrangler.jsonc +0 -50
- package/src/types.ts +0 -152
- package/src/ws-chat-transport.ts +0 -203
- package/tsconfig.json +0 -4
- 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-
|
|
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;;EAG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xC,QAAO;;;;;;;;AAWb,SAAS,wBACP,OACA,MACA,IACyB;AACzB,MAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,IAAI,MAAM;AAChB,MAAI,EAAE,SAAS,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-
|
|
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,54 +45,63 @@ 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);
|
|
39
|
-
options.abortSignal?.addEventListener("abort", () => {
|
|
40
|
-
if (completed) return;
|
|
41
|
-
this.agent.send(JSON.stringify({
|
|
42
|
-
id: requestId,
|
|
43
|
-
type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
|
|
44
|
-
}));
|
|
45
|
-
this.activeRequestIds?.delete(requestId);
|
|
46
|
-
abortController.abort();
|
|
47
|
-
});
|
|
48
52
|
const agent = this.agent;
|
|
49
53
|
const activeIds = this.activeRequestIds;
|
|
54
|
+
const finish = (action) => {
|
|
55
|
+
if (completed) return;
|
|
56
|
+
completed = true;
|
|
57
|
+
try {
|
|
58
|
+
action();
|
|
59
|
+
} catch {}
|
|
60
|
+
activeIds?.delete(requestId);
|
|
61
|
+
abortController.abort();
|
|
62
|
+
};
|
|
63
|
+
const abortError = /* @__PURE__ */ new Error("Aborted");
|
|
64
|
+
abortError.name = "AbortError";
|
|
65
|
+
const onAbort = () => {
|
|
66
|
+
if (completed) return;
|
|
67
|
+
try {
|
|
68
|
+
agent.send(JSON.stringify({
|
|
69
|
+
id: requestId,
|
|
70
|
+
type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
|
|
71
|
+
}));
|
|
72
|
+
} catch {}
|
|
73
|
+
finish(() => streamController.error(abortError));
|
|
74
|
+
};
|
|
75
|
+
let streamController;
|
|
50
76
|
const stream = new ReadableStream({
|
|
51
77
|
start(controller) {
|
|
78
|
+
streamController = controller;
|
|
52
79
|
const onMessage = (event) => {
|
|
53
80
|
try {
|
|
54
81
|
const data = JSON.parse(event.data);
|
|
55
82
|
if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
|
|
56
83
|
if (data.id !== requestId) return;
|
|
57
84
|
if (data.error) {
|
|
58
|
-
|
|
59
|
-
controller.error(new Error(data.body));
|
|
60
|
-
activeIds?.delete(requestId);
|
|
61
|
-
abortController.abort();
|
|
85
|
+
finish(() => controller.error(new Error(data.body || "Stream error")));
|
|
62
86
|
return;
|
|
63
87
|
}
|
|
64
88
|
if (data.body?.trim()) try {
|
|
65
89
|
const chunk = JSON.parse(data.body);
|
|
66
90
|
controller.enqueue(chunk);
|
|
67
91
|
} catch {}
|
|
68
|
-
if (data.done)
|
|
69
|
-
completed = true;
|
|
70
|
-
try {
|
|
71
|
-
controller.close();
|
|
72
|
-
} catch {}
|
|
73
|
-
activeIds?.delete(requestId);
|
|
74
|
-
abortController.abort();
|
|
75
|
-
}
|
|
92
|
+
if (data.done) finish(() => controller.close());
|
|
76
93
|
} catch {}
|
|
77
94
|
};
|
|
78
95
|
agent.addEventListener("message", onMessage, { signal: abortController.signal });
|
|
79
96
|
},
|
|
80
97
|
cancel() {
|
|
81
|
-
|
|
98
|
+
onAbort();
|
|
82
99
|
}
|
|
83
100
|
});
|
|
101
|
+
if (options.abortSignal) {
|
|
102
|
+
options.abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
103
|
+
if (options.abortSignal.aborted) onAbort();
|
|
104
|
+
}
|
|
84
105
|
agent.send(JSON.stringify({
|
|
85
106
|
id: requestId,
|
|
86
107
|
init: {
|
|
@@ -92,7 +113,74 @@ var WebSocketChatTransport = class {
|
|
|
92
113
|
return stream;
|
|
93
114
|
}
|
|
94
115
|
async reconnectToStream(_options) {
|
|
95
|
-
|
|
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
|
+
});
|
|
96
184
|
}
|
|
97
185
|
};
|
|
98
186
|
|
|
@@ -226,7 +314,8 @@ function useAgentChat(options) {
|
|
|
226
314
|
* Used by onAgentMessage to skip messages already handled by the transport.
|
|
227
315
|
*/
|
|
228
316
|
const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
|
|
229
|
-
const
|
|
317
|
+
const customTransportRef = useRef(null);
|
|
318
|
+
if (customTransportRef.current === null) customTransportRef.current = new WebSocketChatTransport({
|
|
230
319
|
agent: agentRef.current,
|
|
231
320
|
activeRequestIds: localRequestIdsRef.current,
|
|
232
321
|
prepareBody: async ({ messages: msgs, trigger, messageId }) => {
|
|
@@ -239,7 +328,7 @@ function useAgentChat(options) {
|
|
|
239
328
|
}
|
|
240
329
|
if (prepareSendMessagesRequestRef.current) {
|
|
241
330
|
const userResult = await prepareSendMessagesRequestRef.current({
|
|
242
|
-
id:
|
|
331
|
+
id: agentRef.current._pk,
|
|
243
332
|
messages: msgs,
|
|
244
333
|
trigger,
|
|
245
334
|
messageId
|
|
@@ -248,13 +337,16 @@ function useAgentChat(options) {
|
|
|
248
337
|
}
|
|
249
338
|
return extraBody;
|
|
250
339
|
}
|
|
251
|
-
})
|
|
340
|
+
});
|
|
341
|
+
customTransportRef.current.agent = agentRef.current;
|
|
342
|
+
const customTransport = customTransportRef.current;
|
|
252
343
|
const useChatHelpers = useChat({
|
|
253
344
|
...rest,
|
|
254
345
|
onData,
|
|
255
346
|
messages: initialMessages,
|
|
256
347
|
transport: customTransport,
|
|
257
|
-
id:
|
|
348
|
+
id: initialMessagesCacheKey,
|
|
349
|
+
resume
|
|
258
350
|
});
|
|
259
351
|
const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage } = useChatHelpers;
|
|
260
352
|
const processedToolCalls = useRef(/* @__PURE__ */ new Set());
|
|
@@ -467,6 +559,8 @@ function useAgentChat(options) {
|
|
|
467
559
|
break;
|
|
468
560
|
case MessageType.CF_AGENT_STREAM_RESUMING:
|
|
469
561
|
if (!resume) return;
|
|
562
|
+
if (customTransport.handleStreamResuming(data)) return;
|
|
563
|
+
if (localRequestIdsRef.current.has(data.id)) return;
|
|
470
564
|
activeStreamRef.current = null;
|
|
471
565
|
activeStreamRef.current = {
|
|
472
566
|
id: data.id,
|
|
@@ -521,13 +615,12 @@ function useAgentChat(options) {
|
|
|
521
615
|
if (data.done || data.error) {
|
|
522
616
|
if (isReplay && activeMsg) flushActiveStreamToMessages(activeMsg);
|
|
523
617
|
activeStreamRef.current = null;
|
|
524
|
-
}
|
|
618
|
+
} else if (data.replayComplete && activeMsg) flushActiveStreamToMessages(activeMsg);
|
|
525
619
|
break;
|
|
526
620
|
}
|
|
527
621
|
}
|
|
528
622
|
}
|
|
529
623
|
agent.addEventListener("message", onAgentMessage);
|
|
530
|
-
if (resume) agent.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST }));
|
|
531
624
|
return () => {
|
|
532
625
|
agent.removeEventListener("message", onAgentMessage);
|
|
533
626
|
activeStreamRef.current = null;
|
|
@@ -536,7 +629,8 @@ function useAgentChat(options) {
|
|
|
536
629
|
agent,
|
|
537
630
|
setMessages,
|
|
538
631
|
resume,
|
|
539
|
-
flushActiveStreamToMessages
|
|
632
|
+
flushActiveStreamToMessages,
|
|
633
|
+
customTransport
|
|
540
634
|
]);
|
|
541
635
|
const addToolResultAndSendMessage = async (args) => {
|
|
542
636
|
const { toolCallId } = args;
|