@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
package/src/types.ts DELETED
@@ -1,152 +0,0 @@
1
- import type { JSONSchema7, UIMessage } from "ai";
2
-
3
- /**
4
- * Enum for message types to improve type safety and maintainability
5
- */
6
- export enum MessageType {
7
- CF_AGENT_CHAT_MESSAGES = "cf_agent_chat_messages",
8
- CF_AGENT_USE_CHAT_REQUEST = "cf_agent_use_chat_request",
9
- CF_AGENT_USE_CHAT_RESPONSE = "cf_agent_use_chat_response",
10
- CF_AGENT_CHAT_CLEAR = "cf_agent_chat_clear",
11
- CF_AGENT_CHAT_REQUEST_CANCEL = "cf_agent_chat_request_cancel",
12
-
13
- /** Sent by server when client connects and there's an active stream to resume */
14
- CF_AGENT_STREAM_RESUMING = "cf_agent_stream_resuming",
15
- /** Sent by client to acknowledge stream resuming notification and request chunks */
16
- CF_AGENT_STREAM_RESUME_ACK = "cf_agent_stream_resume_ack",
17
- /** Sent by client after message handler is ready, requesting stream resume check */
18
- CF_AGENT_STREAM_RESUME_REQUEST = "cf_agent_stream_resume_request",
19
-
20
- /** Client sends tool result to server (for client-side tools) */
21
- CF_AGENT_TOOL_RESULT = "cf_agent_tool_result",
22
- /** Server notifies client that a message was updated (e.g., tool result applied) */
23
- CF_AGENT_MESSAGE_UPDATED = "cf_agent_message_updated",
24
- /** Client sends tool approval response to server (for tools with needsApproval) */
25
- CF_AGENT_TOOL_APPROVAL = "cf_agent_tool_approval"
26
- }
27
-
28
- /**
29
- * Types of messages sent from the Agent to clients
30
- */
31
- export type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =
32
- | {
33
- /** Indicates this message is a command to clear chat history */
34
- type: MessageType.CF_AGENT_CHAT_CLEAR;
35
- }
36
- | {
37
- /** Indicates this message contains updated chat messages */
38
- type: MessageType.CF_AGENT_CHAT_MESSAGES;
39
- /** Array of chat messages */
40
- messages: ChatMessage[];
41
- }
42
- | {
43
- /** Indicates this message is a response to a chat request */
44
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE;
45
- /** Unique ID of the request this response corresponds to */
46
- id: string;
47
- /** Content body of the response */
48
- body: string;
49
- /** Whether this is the final chunk of the response */
50
- done: boolean;
51
- /** Whether this response contains an error */
52
- error?: boolean;
53
- /** Whether this is a continuation (append to last assistant message) */
54
- continuation?: boolean;
55
- /** Whether this chunk is being replayed from storage (stream resumption) */
56
- replay?: boolean;
57
- }
58
- | {
59
- /** Indicates the server is resuming an active stream */
60
- type: MessageType.CF_AGENT_STREAM_RESUMING;
61
- /** The request ID of the stream being resumed */
62
- id: string;
63
- }
64
- | {
65
- /** Server notifies client that a message was updated (e.g., tool result applied) */
66
- type: MessageType.CF_AGENT_MESSAGE_UPDATED;
67
- /** The updated message */
68
- message: ChatMessage;
69
- };
70
-
71
- /**
72
- * Types of messages sent from clients to the Agent
73
- */
74
- export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
75
- | {
76
- /** Indicates this message is a command to clear chat history */
77
- type: MessageType.CF_AGENT_CHAT_CLEAR;
78
- }
79
- | {
80
- /** Indicates this message is a request to the chat API */
81
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST;
82
- /** Unique ID for this request */
83
- id: string;
84
- /** Request initialization options */
85
- init: Pick<
86
- RequestInit,
87
- | "method"
88
- | "keepalive"
89
- | "headers"
90
- | "body"
91
- | "redirect"
92
- | "integrity"
93
- | "credentials"
94
- | "mode"
95
- | "referrer"
96
- | "referrerPolicy"
97
- | "window"
98
- >;
99
- }
100
- | {
101
- /** Indicates this message contains updated chat messages */
102
- type: MessageType.CF_AGENT_CHAT_MESSAGES;
103
- /** Array of chat messages */
104
- messages: ChatMessage[];
105
- }
106
- | {
107
- /** Indicates the user wants to stop generation of this message */
108
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL;
109
- id: string;
110
- }
111
- | {
112
- /** Client acknowledges stream resuming notification and is ready to receive chunks */
113
- type: MessageType.CF_AGENT_STREAM_RESUME_ACK;
114
- /** The request ID of the stream being resumed */
115
- id: string;
116
- }
117
- | {
118
- /** Client requests stream resume check after message handler is registered */
119
- type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST;
120
- }
121
- | {
122
- /** Client sends tool result to server (for client-side tools) */
123
- type: MessageType.CF_AGENT_TOOL_RESULT;
124
- /** The tool call ID this result is for */
125
- toolCallId: string;
126
- /** The name of the tool */
127
- toolName: string;
128
- /** The output from the tool execution */
129
- output: unknown;
130
- /** Override the tool part state (e.g. "output-error" for custom denial) */
131
- state?: "output-available" | "output-error";
132
- /** Error message when state is "output-error" */
133
- errorText?: string;
134
- /** Whether server should auto-continue the conversation after applying result */
135
- autoContinue?: boolean;
136
- /** Client tool schemas for continuation (client is source of truth) */
137
- clientTools?: Array<{
138
- name: string;
139
- description?: string;
140
- parameters?: JSONSchema7;
141
- }>;
142
- }
143
- | {
144
- /** Client sends tool approval response to server (for tools with needsApproval) */
145
- type: MessageType.CF_AGENT_TOOL_APPROVAL;
146
- /** The tool call ID this approval is for */
147
- toolCallId: string;
148
- /** Whether the tool execution was approved */
149
- approved: boolean;
150
- /** Whether server should auto-continue the conversation after applying approval */
151
- autoContinue?: boolean;
152
- };
@@ -1,227 +0,0 @@
1
- /**
2
- * WebSocket-based ChatTransport for useAgentChat.
3
- *
4
- * Replaces the aiFetch + DefaultChatTransport indirection with a direct
5
- * WebSocket implementation that speaks the CF_AGENT protocol natively.
6
- *
7
- * Data flow (old): WS → aiFetch fake Response → DefaultChatTransport → useChat
8
- * Data flow (new): WS → WebSocketChatTransport → useChat
9
- */
10
-
11
- import type { ChatTransport, UIMessage, UIMessageChunk } from "ai";
12
- import { nanoid } from "nanoid";
13
- import { MessageType, type OutgoingMessage } from "./types";
14
-
15
- /**
16
- * Agent-like interface for sending/receiving WebSocket messages.
17
- * Matches the shape returned by useAgent from agents/react.
18
- */
19
- export interface AgentConnection {
20
- send: (data: string) => void;
21
- addEventListener: (
22
- type: string,
23
- listener: (event: MessageEvent) => void,
24
- options?: { signal?: AbortSignal }
25
- ) => void;
26
- removeEventListener: (
27
- type: string,
28
- listener: (event: MessageEvent) => void
29
- ) => void;
30
- }
31
-
32
- export type WebSocketChatTransportOptions<
33
- ChatMessage extends UIMessage = UIMessage
34
- > = {
35
- /** The agent connection from useAgent */
36
- agent: AgentConnection;
37
- /**
38
- * Callback to prepare the request body before sending.
39
- * Can add custom headers, body fields, or credentials.
40
- */
41
- prepareBody?: (options: {
42
- messages: ChatMessage[];
43
- trigger: "submit-message" | "regenerate-message";
44
- messageId?: string;
45
- }) => Promise<Record<string, unknown>> | Record<string, unknown>;
46
- /**
47
- * Optional set to track active request IDs.
48
- * IDs are added when a request starts and removed when it completes.
49
- * Used by the onAgentMessage handler to skip messages already handled by the transport.
50
- */
51
- activeRequestIds?: Set<string>;
52
- };
53
-
54
- /**
55
- * ChatTransport that sends messages over WebSocket and returns a
56
- * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.
57
- * No fake fetch, no Response reconstruction, no double SSE parsing.
58
- */
59
- export class WebSocketChatTransport<
60
- ChatMessage extends UIMessage = UIMessage
61
- > implements ChatTransport<ChatMessage> {
62
- private agent: AgentConnection;
63
- private prepareBody?: WebSocketChatTransportOptions<ChatMessage>["prepareBody"];
64
- private activeRequestIds?: Set<string>;
65
-
66
- constructor(options: WebSocketChatTransportOptions<ChatMessage>) {
67
- this.agent = options.agent;
68
- this.prepareBody = options.prepareBody;
69
- this.activeRequestIds = options.activeRequestIds;
70
- }
71
-
72
- async sendMessages(options: {
73
- chatId: string;
74
- messages: ChatMessage[];
75
- abortSignal: AbortSignal | undefined;
76
- trigger: "submit-message" | "regenerate-message";
77
- messageId?: string;
78
- body?: object;
79
- headers?: Record<string, string> | Headers;
80
- metadata?: unknown;
81
- }): Promise<ReadableStream<UIMessageChunk>> {
82
- const requestId = nanoid(8);
83
- const abortController = new AbortController();
84
- let completed = false;
85
-
86
- // Build the request body
87
- let extraBody: Record<string, unknown> = {};
88
- if (this.prepareBody) {
89
- extraBody = await this.prepareBody({
90
- messages: options.messages,
91
- trigger: options.trigger,
92
- messageId: options.messageId
93
- });
94
- }
95
- if (options.body) {
96
- extraBody = {
97
- ...extraBody,
98
- ...(options.body as Record<string, unknown>)
99
- };
100
- }
101
-
102
- const bodyPayload = JSON.stringify({
103
- messages: options.messages,
104
- ...extraBody
105
- });
106
-
107
- // Track this request so the onAgentMessage handler skips it
108
- this.activeRequestIds?.add(requestId);
109
-
110
- // Create a ReadableStream<UIMessageChunk> that emits parsed chunks
111
- // as they arrive over the WebSocket
112
- const agent = this.agent;
113
- const activeIds = this.activeRequestIds;
114
-
115
- // Single cleanup helper — every terminal path (done, error, abort)
116
- // goes through here exactly once.
117
- const finish = (action: () => void) => {
118
- if (completed) return;
119
- completed = true;
120
- try {
121
- action();
122
- } catch {
123
- // Stream may already be closed
124
- }
125
- activeIds?.delete(requestId);
126
- abortController.abort();
127
- };
128
-
129
- const abortError = new Error("Aborted");
130
- abortError.name = "AbortError";
131
-
132
- // Abort handler: send cancel to server, then terminate the stream.
133
- // Used by both the caller's abortSignal and stream.cancel().
134
- const onAbort = () => {
135
- if (completed) return;
136
- try {
137
- agent.send(
138
- JSON.stringify({
139
- id: requestId,
140
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
141
- })
142
- );
143
- } catch {
144
- // Ignore failures (e.g. agent already disconnected)
145
- }
146
- finish(() => streamController.error(abortError));
147
- };
148
-
149
- // streamController is assigned synchronously by start(), so it is
150
- // always available by the time onAbort or onMessage can fire.
151
- let streamController!: ReadableStreamDefaultController<UIMessageChunk>;
152
-
153
- const stream = new ReadableStream<UIMessageChunk>({
154
- start(controller) {
155
- streamController = controller;
156
-
157
- const onMessage = (event: MessageEvent) => {
158
- try {
159
- const data = JSON.parse(
160
- event.data as string
161
- ) as OutgoingMessage<ChatMessage>;
162
-
163
- if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
164
- if (data.id !== requestId) return;
165
-
166
- if (data.error) {
167
- finish(() => controller.error(new Error(data.body)));
168
- return;
169
- }
170
-
171
- // Parse the body as UIMessageChunk and enqueue
172
- if (data.body?.trim()) {
173
- try {
174
- const chunk = JSON.parse(data.body) as UIMessageChunk;
175
- controller.enqueue(chunk);
176
- } catch {
177
- // Skip malformed chunk bodies
178
- }
179
- }
180
-
181
- if (data.done) {
182
- finish(() => controller.close());
183
- }
184
- } catch {
185
- // Ignore non-JSON messages
186
- }
187
- };
188
-
189
- agent.addEventListener("message", onMessage, {
190
- signal: abortController.signal
191
- });
192
- },
193
- cancel() {
194
- onAbort();
195
- }
196
- });
197
-
198
- // Handle abort from the caller
199
- if (options.abortSignal) {
200
- options.abortSignal.addEventListener("abort", onAbort, { once: true });
201
- if (options.abortSignal.aborted) onAbort();
202
- }
203
-
204
- // Send the request over WebSocket
205
- agent.send(
206
- JSON.stringify({
207
- id: requestId,
208
- init: {
209
- method: "POST",
210
- body: bodyPayload
211
- },
212
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST
213
- })
214
- );
215
-
216
- return stream;
217
- }
218
-
219
- async reconnectToStream(_options: {
220
- chatId: string;
221
- }): Promise<ReadableStream<UIMessageChunk> | null> {
222
- // Stream resumption is handled by the onAgentMessage handler
223
- // in useAgentChat (CF_AGENT_STREAM_RESUME_REQUEST flow).
224
- // The transport returns null to let the hook handle it.
225
- return null;
226
- }
227
- }
package/tsconfig.json DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "exclude": ["src/tests/**/*.ts", "src/e2e/**/*.ts"],
3
- "extends": "../../tsconfig.base.json"
4
- }
package/vitest.config.ts DELETED
@@ -1,7 +0,0 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- export default defineConfig({
4
- test: {
5
- projects: ["src/tests/vitest.config.ts", "src/react-tests/vitest.config.ts"]
6
- }
7
- });