@cloudflare/ai-chat 0.0.7 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -0
- package/README.md +225 -459
- package/dist/ai-chat-v5-migration.d.ts +9 -9
- package/dist/ai-chat-v5-migration.js +25 -4
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +29 -0
- package/dist/experimental/forever.js +55 -0
- package/dist/experimental/forever.js.map +1 -0
- package/dist/index.d.ts +126 -74
- package/dist/index.js +753 -632
- package/dist/index.js.map +1 -1
- package/dist/message-builder-Bwc_Umye.js +231 -0
- package/dist/message-builder-Bwc_Umye.js.map +1 -0
- package/dist/react.d.ts +27 -9
- package/dist/react.js +248 -259
- package/dist/react.js.map +1 -1
- package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
- package/dist/types.d.ts +16 -4
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/e2e/chat.spec.ts +1703 -0
- package/e2e/client-tools.spec.ts +504 -0
- package/e2e/llm.spec.ts +637 -0
- package/e2e/playwright.config.ts +24 -0
- package/e2e/worker.ts +176 -0
- package/e2e/wrangler.jsonc +23 -0
- package/package.json +12 -5
- package/scripts/build.ts +2 -1
- package/src/ai-chat-v5-migration.ts +32 -5
- package/src/experimental/forever.ts +66 -0
- package/src/index.ts +850 -1132
- package/src/message-builder.ts +384 -0
- package/src/react-tests/use-agent-chat.test.tsx +738 -2
- package/src/react.tsx +396 -462
- package/src/resumable-stream.ts +441 -0
- package/src/tests/chat-context.test.ts +1 -1
- package/src/tests/chat-persistence.test.ts +5 -5
- package/src/tests/clear-history.test.ts +132 -0
- package/src/tests/client-tool-duplicate-message.test.ts +457 -14
- package/src/tests/client-tools-broadcast.test.ts +2 -2
- package/src/tests/client-tools-continuation.test.ts +314 -0
- package/src/tests/client-tools-reconnect.test.ts +143 -0
- package/src/tests/custom-body-continuation.test.ts +309 -0
- package/src/tests/custom-body.test.ts +186 -0
- package/src/tests/destroy.test.ts +57 -0
- package/src/tests/get-messages-endpoint.test.ts +79 -0
- package/src/tests/max-persisted-messages.test.ts +201 -0
- package/src/tests/merge-server-state.test.ts +106 -0
- package/src/tests/message-builder.test.ts +808 -0
- package/src/tests/migration.test.ts +282 -0
- package/src/tests/non-sse-response.test.ts +2 -2
- package/src/tests/onfinish-cleanup.test.ts +362 -0
- package/src/tests/plaintext-response.test.ts +87 -0
- package/src/tests/resumable-streaming.test.ts +220 -14
- package/src/tests/row-size-guard.test.ts +374 -0
- package/src/tests/sanitize-messages.test.ts +215 -0
- package/src/tests/validate-messages.test.ts +269 -0
- package/src/tests/worker.ts +85 -23
- package/src/types.ts +17 -1
- package/src/ws-chat-transport.ts +203 -0
|
@@ -0,0 +1,203 @@
|
|
|
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
|
+
// Handle abort from the caller (only if the stream has not already completed)
|
|
111
|
+
options.abortSignal?.addEventListener("abort", () => {
|
|
112
|
+
if (completed) return;
|
|
113
|
+
this.agent.send(
|
|
114
|
+
JSON.stringify({
|
|
115
|
+
id: requestId,
|
|
116
|
+
type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
|
|
117
|
+
})
|
|
118
|
+
);
|
|
119
|
+
this.activeRequestIds?.delete(requestId);
|
|
120
|
+
abortController.abort();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// Create a ReadableStream<UIMessageChunk> that emits parsed chunks
|
|
124
|
+
// as they arrive over the WebSocket
|
|
125
|
+
const agent = this.agent;
|
|
126
|
+
const activeIds = this.activeRequestIds;
|
|
127
|
+
const stream = new ReadableStream<UIMessageChunk>({
|
|
128
|
+
start(controller) {
|
|
129
|
+
const onMessage = (event: MessageEvent) => {
|
|
130
|
+
try {
|
|
131
|
+
const data = JSON.parse(
|
|
132
|
+
event.data as string
|
|
133
|
+
) as OutgoingMessage<ChatMessage>;
|
|
134
|
+
|
|
135
|
+
if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
|
|
136
|
+
if (data.id !== requestId) return;
|
|
137
|
+
|
|
138
|
+
if (data.error) {
|
|
139
|
+
completed = true;
|
|
140
|
+
controller.error(new Error(data.body));
|
|
141
|
+
activeIds?.delete(requestId);
|
|
142
|
+
abortController.abort();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Parse the body as UIMessageChunk and enqueue
|
|
147
|
+
if (data.body?.trim()) {
|
|
148
|
+
try {
|
|
149
|
+
const chunk = JSON.parse(data.body) as UIMessageChunk;
|
|
150
|
+
controller.enqueue(chunk);
|
|
151
|
+
} catch {
|
|
152
|
+
// Skip malformed chunk bodies
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (data.done) {
|
|
157
|
+
completed = true;
|
|
158
|
+
try {
|
|
159
|
+
controller.close();
|
|
160
|
+
} catch {
|
|
161
|
+
// Stream may already be closed
|
|
162
|
+
}
|
|
163
|
+
activeIds?.delete(requestId);
|
|
164
|
+
abortController.abort();
|
|
165
|
+
}
|
|
166
|
+
} catch {
|
|
167
|
+
// Ignore non-JSON messages
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
agent.addEventListener("message", onMessage, {
|
|
172
|
+
signal: abortController.signal
|
|
173
|
+
});
|
|
174
|
+
},
|
|
175
|
+
cancel() {
|
|
176
|
+
abortController.abort();
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// Send the request over WebSocket
|
|
181
|
+
agent.send(
|
|
182
|
+
JSON.stringify({
|
|
183
|
+
id: requestId,
|
|
184
|
+
init: {
|
|
185
|
+
method: "POST",
|
|
186
|
+
body: bodyPayload
|
|
187
|
+
},
|
|
188
|
+
type: MessageType.CF_AGENT_USE_CHAT_REQUEST
|
|
189
|
+
})
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
return stream;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async reconnectToStream(_options: {
|
|
196
|
+
chatId: string;
|
|
197
|
+
}): Promise<ReadableStream<UIMessageChunk> | null> {
|
|
198
|
+
// Stream resumption is handled by the onAgentMessage handler
|
|
199
|
+
// in useAgentChat (CF_AGENT_STREAM_RESUME_REQUEST flow).
|
|
200
|
+
// The transport returns null to let the hook handle it.
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|