@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
package/src/tests/worker.ts
DELETED
|
@@ -1,456 +0,0 @@
|
|
|
1
|
-
import { AIChatAgent, type OnChatMessageOptions } from "../";
|
|
2
|
-
import type {
|
|
3
|
-
UIMessage as ChatMessage,
|
|
4
|
-
StreamTextOnFinishCallback,
|
|
5
|
-
ToolSet
|
|
6
|
-
} from "ai";
|
|
7
|
-
import { getCurrentAgent, routeAgentRequest } from "agents";
|
|
8
|
-
import { MessageType, type OutgoingMessage } from "../types";
|
|
9
|
-
import type { ClientToolSchema } from "../";
|
|
10
|
-
|
|
11
|
-
// Type helper for tool call parts - extracts from ChatMessage parts
|
|
12
|
-
type TestToolCallPart = Extract<
|
|
13
|
-
ChatMessage["parts"][number],
|
|
14
|
-
{ type: `tool-${string}` }
|
|
15
|
-
>;
|
|
16
|
-
|
|
17
|
-
export type Env = {
|
|
18
|
-
TestChatAgent: DurableObjectNamespace<TestChatAgent>;
|
|
19
|
-
AgentWithSuperCall: DurableObjectNamespace<AgentWithSuperCall>;
|
|
20
|
-
AgentWithoutSuperCall: DurableObjectNamespace<AgentWithoutSuperCall>;
|
|
21
|
-
SlowStreamAgent: DurableObjectNamespace<SlowStreamAgent>;
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export class TestChatAgent extends AIChatAgent<Env> {
|
|
25
|
-
observability = undefined;
|
|
26
|
-
// Store captured context for testing
|
|
27
|
-
private _capturedContext: {
|
|
28
|
-
hasAgent: boolean;
|
|
29
|
-
hasConnection: boolean;
|
|
30
|
-
connectionId: string | undefined;
|
|
31
|
-
} | null = null;
|
|
32
|
-
// Store context captured from nested async function (simulates tool execute)
|
|
33
|
-
private _nestedContext: {
|
|
34
|
-
hasAgent: boolean;
|
|
35
|
-
hasConnection: boolean;
|
|
36
|
-
connectionId: string | undefined;
|
|
37
|
-
} | null = null;
|
|
38
|
-
// Store captured body from onChatMessage options for testing
|
|
39
|
-
private _capturedBody: Record<string, unknown> | undefined = undefined;
|
|
40
|
-
// Store captured clientTools from onChatMessage options for testing
|
|
41
|
-
private _capturedClientTools: ClientToolSchema[] | undefined = undefined;
|
|
42
|
-
// Store captured requestId from onChatMessage options for testing
|
|
43
|
-
private _capturedRequestId: string | undefined = undefined;
|
|
44
|
-
|
|
45
|
-
async onChatMessage(
|
|
46
|
-
_onFinish: StreamTextOnFinishCallback<ToolSet>,
|
|
47
|
-
options?: OnChatMessageOptions
|
|
48
|
-
) {
|
|
49
|
-
// Capture the body, clientTools, and requestId from options for testing
|
|
50
|
-
this._capturedBody = options?.body;
|
|
51
|
-
this._capturedClientTools = options?.clientTools;
|
|
52
|
-
this._capturedRequestId = options?.requestId;
|
|
53
|
-
|
|
54
|
-
// Capture getCurrentAgent() context for testing
|
|
55
|
-
const { agent, connection } = getCurrentAgent();
|
|
56
|
-
this._capturedContext = {
|
|
57
|
-
hasAgent: agent !== undefined,
|
|
58
|
-
hasConnection: connection !== undefined,
|
|
59
|
-
connectionId: connection?.id
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
// Simulate what happens inside a tool's execute function:
|
|
63
|
-
// It's a nested async function called from within onChatMessage
|
|
64
|
-
await this._simulateToolExecute();
|
|
65
|
-
|
|
66
|
-
// Simple echo response for testing
|
|
67
|
-
return new Response("Hello from chat agent!", {
|
|
68
|
-
headers: { "Content-Type": "text/plain" }
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// This simulates an AI SDK tool's execute function being called
|
|
73
|
-
private async _simulateToolExecute(): Promise<void> {
|
|
74
|
-
// Add a small delay to ensure we're in a new microtask (like real tool execution)
|
|
75
|
-
await Promise.resolve();
|
|
76
|
-
|
|
77
|
-
// Capture context inside the "tool execute" function
|
|
78
|
-
const { agent, connection } = getCurrentAgent();
|
|
79
|
-
this._nestedContext = {
|
|
80
|
-
hasAgent: agent !== undefined,
|
|
81
|
-
hasConnection: connection !== undefined,
|
|
82
|
-
connectionId: connection?.id
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
getCapturedContext(): {
|
|
87
|
-
hasAgent: boolean;
|
|
88
|
-
hasConnection: boolean;
|
|
89
|
-
connectionId: string | undefined;
|
|
90
|
-
} | null {
|
|
91
|
-
return this._capturedContext;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
getNestedContext(): {
|
|
95
|
-
hasAgent: boolean;
|
|
96
|
-
hasConnection: boolean;
|
|
97
|
-
connectionId: string | undefined;
|
|
98
|
-
} | null {
|
|
99
|
-
return this._nestedContext;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
clearCapturedContext(): void {
|
|
103
|
-
this._capturedContext = null;
|
|
104
|
-
this._nestedContext = null;
|
|
105
|
-
this._capturedBody = undefined;
|
|
106
|
-
this._capturedClientTools = undefined;
|
|
107
|
-
this._capturedRequestId = undefined;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
getCapturedBody(): Record<string, unknown> | undefined {
|
|
111
|
-
return this._capturedBody;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
getCapturedClientTools(): ClientToolSchema[] | undefined {
|
|
115
|
-
return this._capturedClientTools;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
getCapturedRequestId(): string | undefined {
|
|
119
|
-
return this._capturedRequestId;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
getPersistedMessages(): ChatMessage[] {
|
|
123
|
-
const rawMessages = (
|
|
124
|
-
this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
|
|
125
|
-
[]
|
|
126
|
-
).map((row) => {
|
|
127
|
-
return JSON.parse(row.message as string);
|
|
128
|
-
});
|
|
129
|
-
return rawMessages;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
async testPersistToolCall(messageId: string, toolName: string) {
|
|
133
|
-
const toolCallPart: TestToolCallPart = {
|
|
134
|
-
type: `tool-${toolName}`,
|
|
135
|
-
toolCallId: `call_${messageId}`,
|
|
136
|
-
state: "input-available",
|
|
137
|
-
input: { location: "London" }
|
|
138
|
-
};
|
|
139
|
-
|
|
140
|
-
const messageWithToolCall: ChatMessage = {
|
|
141
|
-
id: messageId,
|
|
142
|
-
role: "assistant",
|
|
143
|
-
parts: [toolCallPart] as ChatMessage["parts"]
|
|
144
|
-
};
|
|
145
|
-
await this.persistMessages([messageWithToolCall]);
|
|
146
|
-
return messageWithToolCall;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
async testPersistToolResult(
|
|
150
|
-
messageId: string,
|
|
151
|
-
toolName: string,
|
|
152
|
-
output: string
|
|
153
|
-
) {
|
|
154
|
-
const toolResultPart: TestToolCallPart = {
|
|
155
|
-
type: `tool-${toolName}`,
|
|
156
|
-
toolCallId: `call_${messageId}`,
|
|
157
|
-
state: "output-available",
|
|
158
|
-
input: { location: "London" },
|
|
159
|
-
output
|
|
160
|
-
};
|
|
161
|
-
|
|
162
|
-
const messageWithToolOutput: ChatMessage = {
|
|
163
|
-
id: messageId,
|
|
164
|
-
role: "assistant",
|
|
165
|
-
parts: [toolResultPart] as ChatMessage["parts"]
|
|
166
|
-
};
|
|
167
|
-
await this.persistMessages([messageWithToolOutput]);
|
|
168
|
-
return messageWithToolOutput;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// Resumable streaming test helpers
|
|
172
|
-
|
|
173
|
-
testStartStream(requestId: string): string {
|
|
174
|
-
return this._startStream(requestId);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
testStoreStreamChunk(streamId: string, body: string): void {
|
|
178
|
-
this._storeStreamChunk(streamId, body);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
testBroadcastLiveChunk(
|
|
182
|
-
requestId: string,
|
|
183
|
-
streamId: string,
|
|
184
|
-
body: string
|
|
185
|
-
): void {
|
|
186
|
-
this._storeStreamChunk(streamId, body);
|
|
187
|
-
const message: OutgoingMessage = {
|
|
188
|
-
body,
|
|
189
|
-
done: false,
|
|
190
|
-
id: requestId,
|
|
191
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
192
|
-
};
|
|
193
|
-
(
|
|
194
|
-
this as unknown as {
|
|
195
|
-
_broadcastChatMessage: (
|
|
196
|
-
msg: OutgoingMessage,
|
|
197
|
-
exclude?: string[]
|
|
198
|
-
) => void;
|
|
199
|
-
}
|
|
200
|
-
)._broadcastChatMessage(message);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
testFlushChunkBuffer(): void {
|
|
204
|
-
this._flushChunkBuffer();
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
testCompleteStream(streamId: string): void {
|
|
208
|
-
this._completeStream(streamId);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
testMarkStreamError(streamId: string): void {
|
|
212
|
-
this._markStreamError(streamId);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
getActiveStreamId(): string | null {
|
|
216
|
-
return this._activeStreamId;
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
getActiveRequestId(): string | null {
|
|
220
|
-
return this._activeRequestId;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
getStreamChunks(
|
|
224
|
-
streamId: string
|
|
225
|
-
): Array<{ body: string; chunk_index: number }> {
|
|
226
|
-
return (
|
|
227
|
-
this.sql<{ body: string; chunk_index: number }>`
|
|
228
|
-
select body, chunk_index from cf_ai_chat_stream_chunks
|
|
229
|
-
where stream_id = ${streamId}
|
|
230
|
-
order by chunk_index asc
|
|
231
|
-
` || []
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
getStreamMetadata(
|
|
236
|
-
streamId: string
|
|
237
|
-
): { status: string; request_id: string } | null {
|
|
238
|
-
const result = this.sql<{ status: string; request_id: string }>`
|
|
239
|
-
select status, request_id from cf_ai_chat_stream_metadata
|
|
240
|
-
where id = ${streamId}
|
|
241
|
-
`;
|
|
242
|
-
return result && result.length > 0 ? result[0] : null;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
getAllStreamMetadata(): Array<{
|
|
246
|
-
id: string;
|
|
247
|
-
status: string;
|
|
248
|
-
request_id: string;
|
|
249
|
-
created_at: number;
|
|
250
|
-
}> {
|
|
251
|
-
return (
|
|
252
|
-
this.sql<{
|
|
253
|
-
id: string;
|
|
254
|
-
status: string;
|
|
255
|
-
request_id: string;
|
|
256
|
-
created_at: number;
|
|
257
|
-
}>`select id, status, request_id, created_at from cf_ai_chat_stream_metadata` ||
|
|
258
|
-
[]
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
testInsertStaleStream(
|
|
263
|
-
streamId: string,
|
|
264
|
-
requestId: string,
|
|
265
|
-
ageMs: number
|
|
266
|
-
): void {
|
|
267
|
-
const createdAt = Date.now() - ageMs;
|
|
268
|
-
this.sql`
|
|
269
|
-
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
270
|
-
values (${streamId}, ${requestId}, 'streaming', ${createdAt})
|
|
271
|
-
`;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
testInsertOldErroredStream(
|
|
275
|
-
streamId: string,
|
|
276
|
-
requestId: string,
|
|
277
|
-
ageMs: number
|
|
278
|
-
): void {
|
|
279
|
-
const createdAt = Date.now() - ageMs;
|
|
280
|
-
const completedAt = createdAt + 1000;
|
|
281
|
-
this.sql`
|
|
282
|
-
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at, completed_at)
|
|
283
|
-
values (${streamId}, ${requestId}, 'error', ${createdAt}, ${completedAt})
|
|
284
|
-
`;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
testRestoreActiveStream(): void {
|
|
288
|
-
this._restoreActiveStream();
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
testTriggerStreamCleanup(): void {
|
|
292
|
-
// Force the cleanup interval to 0 so the next completeStream triggers it
|
|
293
|
-
// We do this by starting and immediately completing a dummy stream
|
|
294
|
-
const dummyId = this._startStream("cleanup-trigger");
|
|
295
|
-
this._completeStream(dummyId);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* Insert a raw JSON string as a message directly into SQLite.
|
|
300
|
-
* Used to test validation of malformed/corrupt messages.
|
|
301
|
-
*/
|
|
302
|
-
insertRawMessage(rowId: string, rawJson: string): void {
|
|
303
|
-
this.sql`
|
|
304
|
-
insert into cf_ai_chat_agent_messages (id, message)
|
|
305
|
-
values (${rowId}, ${rawJson})
|
|
306
|
-
`;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
setMaxPersistedMessages(max: number | null): void {
|
|
310
|
-
this.maxPersistedMessages = max ?? undefined;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
getMessageCount(): number {
|
|
314
|
-
const result = this.sql<{ cnt: number }>`
|
|
315
|
-
select count(*) as cnt from cf_ai_chat_agent_messages
|
|
316
|
-
`;
|
|
317
|
-
return result?.[0]?.cnt ?? 0;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/**
|
|
321
|
-
* Returns the number of active abort controllers.
|
|
322
|
-
* Used to verify that cleanup happens after stream completion.
|
|
323
|
-
* If controllers leak, this count grows with each request.
|
|
324
|
-
*/
|
|
325
|
-
getAbortControllerCount(): number {
|
|
326
|
-
return (
|
|
327
|
-
this as unknown as {
|
|
328
|
-
_chatMessageAbortControllers: Map<string, unknown>;
|
|
329
|
-
}
|
|
330
|
-
)._chatMessageAbortControllers.size;
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
/**
|
|
335
|
-
* Test agent that streams chunks slowly, useful for testing cancel/abort.
|
|
336
|
-
*
|
|
337
|
-
* Control via request body fields:
|
|
338
|
-
* - `format`: "sse" | "plaintext" (default: "plaintext")
|
|
339
|
-
* - `useAbortSignal`: boolean — whether to connect abortSignal to the stream
|
|
340
|
-
* - `chunkCount`: number of chunks to emit (default: 20)
|
|
341
|
-
* - `chunkDelayMs`: delay between chunks in ms (default: 50)
|
|
342
|
-
*/
|
|
343
|
-
export class SlowStreamAgent extends AIChatAgent<Env> {
|
|
344
|
-
observability = undefined;
|
|
345
|
-
|
|
346
|
-
async onChatMessage(
|
|
347
|
-
_onFinish: StreamTextOnFinishCallback<ToolSet>,
|
|
348
|
-
options?: OnChatMessageOptions
|
|
349
|
-
) {
|
|
350
|
-
const body = options?.body as
|
|
351
|
-
| {
|
|
352
|
-
format?: string;
|
|
353
|
-
useAbortSignal?: boolean;
|
|
354
|
-
chunkCount?: number;
|
|
355
|
-
chunkDelayMs?: number;
|
|
356
|
-
}
|
|
357
|
-
| undefined;
|
|
358
|
-
const format = body?.format ?? "plaintext";
|
|
359
|
-
const useAbortSignal = body?.useAbortSignal ?? false;
|
|
360
|
-
const chunkCount = body?.chunkCount ?? 20;
|
|
361
|
-
const chunkDelayMs = body?.chunkDelayMs ?? 50;
|
|
362
|
-
const abortSignal = useAbortSignal ? options?.abortSignal : undefined;
|
|
363
|
-
|
|
364
|
-
const encoder = new TextEncoder();
|
|
365
|
-
const stream = new ReadableStream({
|
|
366
|
-
async pull(controller) {
|
|
367
|
-
for (let i = 0; i < chunkCount; i++) {
|
|
368
|
-
if (abortSignal?.aborted) {
|
|
369
|
-
controller.close();
|
|
370
|
-
return;
|
|
371
|
-
}
|
|
372
|
-
await new Promise((r) => setTimeout(r, chunkDelayMs));
|
|
373
|
-
if (abortSignal?.aborted) {
|
|
374
|
-
controller.close();
|
|
375
|
-
return;
|
|
376
|
-
}
|
|
377
|
-
if (format === "sse") {
|
|
378
|
-
const chunk = JSON.stringify({
|
|
379
|
-
type: "text-delta",
|
|
380
|
-
textDelta: `chunk-${i} `
|
|
381
|
-
});
|
|
382
|
-
controller.enqueue(encoder.encode(`data: ${chunk}\n\n`));
|
|
383
|
-
} else {
|
|
384
|
-
controller.enqueue(encoder.encode(`chunk-${i} `));
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
if (format === "sse") {
|
|
388
|
-
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
|
389
|
-
}
|
|
390
|
-
controller.close();
|
|
391
|
-
}
|
|
392
|
-
});
|
|
393
|
-
|
|
394
|
-
const contentType = format === "sse" ? "text/event-stream" : "text/plain";
|
|
395
|
-
return new Response(stream, {
|
|
396
|
-
headers: { "Content-Type": contentType }
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
getAbortControllerCount(): number {
|
|
401
|
-
return (
|
|
402
|
-
this as unknown as {
|
|
403
|
-
_chatMessageAbortControllers: Map<string, unknown>;
|
|
404
|
-
}
|
|
405
|
-
)._chatMessageAbortControllers.size;
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
// Test agent that overrides onRequest and calls super.onRequest()
|
|
410
|
-
export class AgentWithSuperCall extends AIChatAgent<Env> {
|
|
411
|
-
async onRequest(request: Request): Promise<Response> {
|
|
412
|
-
const url = new URL(request.url);
|
|
413
|
-
if (url.pathname.endsWith("/custom-route")) {
|
|
414
|
-
return new Response("custom route");
|
|
415
|
-
}
|
|
416
|
-
return super.onRequest(request);
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
async onChatMessage() {
|
|
420
|
-
return new Response("chat response");
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
// Test agent that overrides onRequest WITHOUT calling super.onRequest()
|
|
425
|
-
export class AgentWithoutSuperCall extends AIChatAgent<Env> {
|
|
426
|
-
async onRequest(_request: Request): Promise<Response> {
|
|
427
|
-
return new Response("custom only");
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
async onChatMessage() {
|
|
431
|
-
return new Response("chat response");
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
export default {
|
|
436
|
-
async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
|
|
437
|
-
const url = new URL(request.url);
|
|
438
|
-
|
|
439
|
-
if (url.pathname === "/500") {
|
|
440
|
-
return new Response("Internal Server Error", { status: 500 });
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
return (
|
|
444
|
-
(await routeAgentRequest(request, env)) ||
|
|
445
|
-
new Response("Not found", { status: 404 })
|
|
446
|
-
);
|
|
447
|
-
},
|
|
448
|
-
|
|
449
|
-
async email(
|
|
450
|
-
_message: ForwardableEmailMessage,
|
|
451
|
-
_env: Env,
|
|
452
|
-
_ctx: ExecutionContext
|
|
453
|
-
) {
|
|
454
|
-
// Bring this in when we write tests for the complete email handler flow
|
|
455
|
-
}
|
|
456
|
-
};
|
package/src/tests/wrangler.jsonc
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compatibility_date": "2026-01-28",
|
|
3
|
-
"compatibility_flags": [
|
|
4
|
-
"nodejs_compat",
|
|
5
|
-
// adding these flags since the vitest runner needs them
|
|
6
|
-
"enable_nodejs_tty_module",
|
|
7
|
-
"enable_nodejs_fs_module",
|
|
8
|
-
"enable_nodejs_http_modules",
|
|
9
|
-
"enable_nodejs_perf_hooks_module"
|
|
10
|
-
],
|
|
11
|
-
"durable_objects": {
|
|
12
|
-
"bindings": [
|
|
13
|
-
{
|
|
14
|
-
"class_name": "TestChatAgent",
|
|
15
|
-
"name": "TestChatAgent"
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
"class_name": "AgentWithSuperCall",
|
|
19
|
-
"name": "AgentWithSuperCall"
|
|
20
|
-
},
|
|
21
|
-
{
|
|
22
|
-
"class_name": "AgentWithoutSuperCall",
|
|
23
|
-
"name": "AgentWithoutSuperCall"
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
"class_name": "SlowStreamAgent",
|
|
27
|
-
"name": "SlowStreamAgent"
|
|
28
|
-
}
|
|
29
|
-
]
|
|
30
|
-
},
|
|
31
|
-
"main": "worker.ts",
|
|
32
|
-
"migrations": [
|
|
33
|
-
{
|
|
34
|
-
"new_sqlite_classes": ["TestChatAgent"],
|
|
35
|
-
"tag": "v1"
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
"new_sqlite_classes": ["AgentWithSuperCall"],
|
|
39
|
-
"tag": "v2"
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
"new_sqlite_classes": ["AgentWithoutSuperCall"],
|
|
43
|
-
"tag": "v3"
|
|
44
|
-
},
|
|
45
|
-
{
|
|
46
|
-
"new_sqlite_classes": ["SlowStreamAgent"],
|
|
47
|
-
"tag": "v4"
|
|
48
|
-
}
|
|
49
|
-
]
|
|
50
|
-
}
|
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
|
-
};
|