@cloudflare/ai-chat 0.1.2 → 0.1.4
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 +50 -0
- package/dist/index.d.ts +62 -39
- package/dist/index.js +176 -77
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +40 -25
- package/dist/react.js +18 -13
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +5 -1
- package/dist/types.js.map +1 -1
- package/e2e/playwright.config.ts +5 -4
- package/e2e/worker.ts +0 -2
- package/e2e/wrangler.jsonc +1 -1
- package/package.json +3 -3
- package/src/index.ts +402 -184
- package/src/react-tests/vitest.config.ts +1 -0
- package/src/react.tsx +98 -57
- package/src/tests/cancel-request.test.ts +280 -0
- package/src/tests/client-tool-duplicate-message.test.ts +666 -9
- package/src/tests/get-messages-endpoint.test.ts +74 -0
- package/src/tests/merge-server-state.test.ts +237 -0
- package/src/tests/request-id.test.ts +312 -0
- package/src/tests/sanitize-messages.test.ts +110 -0
- package/src/tests/vitest.config.ts +1 -0
- package/src/tests/worker.ts +113 -1
- package/src/tests/wrangler.jsonc +24 -0
- package/src/types.ts +4 -0
- package/e2e/global-setup.ts +0 -34
|
@@ -133,6 +133,116 @@ describe("Message Sanitization", () => {
|
|
|
133
133
|
ws.close(1000);
|
|
134
134
|
});
|
|
135
135
|
|
|
136
|
+
it("preserves Anthropic redacted_thinking blocks with empty text", async () => {
|
|
137
|
+
const room = crypto.randomUUID();
|
|
138
|
+
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
139
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
140
|
+
|
|
141
|
+
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
142
|
+
|
|
143
|
+
const messageWithRedactedThinking: ChatMessage = {
|
|
144
|
+
id: "msg-sanitize-redacted",
|
|
145
|
+
role: "assistant",
|
|
146
|
+
parts: [
|
|
147
|
+
{
|
|
148
|
+
type: "reasoning",
|
|
149
|
+
text: "",
|
|
150
|
+
state: "done",
|
|
151
|
+
providerMetadata: {
|
|
152
|
+
anthropic: {
|
|
153
|
+
redactedData: "base64-encrypted-data"
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
{ type: "reasoning", text: "", state: "done" },
|
|
158
|
+
{ type: "text", text: "Here is my answer" },
|
|
159
|
+
{
|
|
160
|
+
type: "reasoning",
|
|
161
|
+
text: "Visible thinking",
|
|
162
|
+
state: "done"
|
|
163
|
+
}
|
|
164
|
+
] as ChatMessage["parts"]
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
await agentStub.persistMessages([messageWithRedactedThinking]);
|
|
168
|
+
|
|
169
|
+
const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
170
|
+
expect(persisted.length).toBe(1);
|
|
171
|
+
|
|
172
|
+
// The Anthropic redacted_thinking part (empty text + providerMetadata.anthropic) should be preserved
|
|
173
|
+
// The plain empty reasoning part should be filtered out
|
|
174
|
+
// The non-empty reasoning part should be preserved
|
|
175
|
+
const reasoningParts = persisted[0].parts.filter(
|
|
176
|
+
(p) => p.type === "reasoning"
|
|
177
|
+
);
|
|
178
|
+
expect(reasoningParts.length).toBe(2);
|
|
179
|
+
|
|
180
|
+
const redactedPart = reasoningParts[0] as {
|
|
181
|
+
text: string;
|
|
182
|
+
providerMetadata?: Record<string, unknown>;
|
|
183
|
+
};
|
|
184
|
+
expect(redactedPart.text).toBe("");
|
|
185
|
+
expect(redactedPart.providerMetadata?.anthropic).toEqual({
|
|
186
|
+
redactedData: "base64-encrypted-data"
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
expect((reasoningParts[1] as { text: string }).text).toBe(
|
|
190
|
+
"Visible thinking"
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
// Text part should be preserved
|
|
194
|
+
const textParts = persisted[0].parts.filter((p) => p.type === "text");
|
|
195
|
+
expect(textParts.length).toBe(1);
|
|
196
|
+
|
|
197
|
+
ws.close(1000);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("removes empty OpenAI reasoning placeholders after stripping metadata", async () => {
|
|
201
|
+
const room = crypto.randomUUID();
|
|
202
|
+
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
203
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
204
|
+
|
|
205
|
+
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
206
|
+
|
|
207
|
+
// OpenAI returns empty reasoning parts with only ephemeral metadata.
|
|
208
|
+
// After stripping OpenAI fields, these should be filtered out entirely.
|
|
209
|
+
const messageWithOpenAIReasoning: ChatMessage = {
|
|
210
|
+
id: "msg-sanitize-openai-reasoning",
|
|
211
|
+
role: "assistant",
|
|
212
|
+
parts: [
|
|
213
|
+
{
|
|
214
|
+
type: "reasoning",
|
|
215
|
+
text: "",
|
|
216
|
+
state: "done",
|
|
217
|
+
providerMetadata: {
|
|
218
|
+
openai: {
|
|
219
|
+
itemId: "item_reasoning_1",
|
|
220
|
+
reasoningEncryptedContent: "encrypted-blob"
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
{ type: "text", text: "Final answer" }
|
|
225
|
+
] as ChatMessage["parts"]
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
await agentStub.persistMessages([messageWithOpenAIReasoning]);
|
|
229
|
+
|
|
230
|
+
const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
231
|
+
expect(persisted.length).toBe(1);
|
|
232
|
+
|
|
233
|
+
// The empty reasoning part should be gone (OpenAI metadata stripped, then empty part filtered)
|
|
234
|
+
const reasoningParts = persisted[0].parts.filter(
|
|
235
|
+
(p) => p.type === "reasoning"
|
|
236
|
+
);
|
|
237
|
+
expect(reasoningParts.length).toBe(0);
|
|
238
|
+
|
|
239
|
+
// Text part should be preserved
|
|
240
|
+
const textParts = persisted[0].parts.filter((p) => p.type === "text");
|
|
241
|
+
expect(textParts.length).toBe(1);
|
|
242
|
+
|
|
243
|
+
ws.close(1000);
|
|
244
|
+
});
|
|
245
|
+
|
|
136
246
|
it("strips callProviderMetadata from tool parts", async () => {
|
|
137
247
|
const room = crypto.randomUUID();
|
|
138
248
|
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
package/src/tests/worker.ts
CHANGED
|
@@ -16,6 +16,9 @@ type TestToolCallPart = Extract<
|
|
|
16
16
|
|
|
17
17
|
export type Env = {
|
|
18
18
|
TestChatAgent: DurableObjectNamespace<TestChatAgent>;
|
|
19
|
+
AgentWithSuperCall: DurableObjectNamespace<AgentWithSuperCall>;
|
|
20
|
+
AgentWithoutSuperCall: DurableObjectNamespace<AgentWithoutSuperCall>;
|
|
21
|
+
SlowStreamAgent: DurableObjectNamespace<SlowStreamAgent>;
|
|
19
22
|
};
|
|
20
23
|
|
|
21
24
|
export class TestChatAgent extends AIChatAgent<Env> {
|
|
@@ -36,14 +39,17 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
36
39
|
private _capturedBody: Record<string, unknown> | undefined = undefined;
|
|
37
40
|
// Store captured clientTools from onChatMessage options for testing
|
|
38
41
|
private _capturedClientTools: ClientToolSchema[] | undefined = undefined;
|
|
42
|
+
// Store captured requestId from onChatMessage options for testing
|
|
43
|
+
private _capturedRequestId: string | undefined = undefined;
|
|
39
44
|
|
|
40
45
|
async onChatMessage(
|
|
41
46
|
_onFinish: StreamTextOnFinishCallback<ToolSet>,
|
|
42
47
|
options?: OnChatMessageOptions
|
|
43
48
|
) {
|
|
44
|
-
// Capture the body and
|
|
49
|
+
// Capture the body, clientTools, and requestId from options for testing
|
|
45
50
|
this._capturedBody = options?.body;
|
|
46
51
|
this._capturedClientTools = options?.clientTools;
|
|
52
|
+
this._capturedRequestId = options?.requestId;
|
|
47
53
|
|
|
48
54
|
// Capture getCurrentAgent() context for testing
|
|
49
55
|
const { agent, connection } = getCurrentAgent();
|
|
@@ -98,6 +104,7 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
98
104
|
this._nestedContext = null;
|
|
99
105
|
this._capturedBody = undefined;
|
|
100
106
|
this._capturedClientTools = undefined;
|
|
107
|
+
this._capturedRequestId = undefined;
|
|
101
108
|
}
|
|
102
109
|
|
|
103
110
|
getCapturedBody(): Record<string, unknown> | undefined {
|
|
@@ -108,6 +115,10 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
108
115
|
return this._capturedClientTools;
|
|
109
116
|
}
|
|
110
117
|
|
|
118
|
+
getCapturedRequestId(): string | undefined {
|
|
119
|
+
return this._capturedRequestId;
|
|
120
|
+
}
|
|
121
|
+
|
|
111
122
|
getPersistedMessages(): ChatMessage[] {
|
|
112
123
|
const rawMessages = (
|
|
113
124
|
this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
|
|
@@ -320,6 +331,107 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
320
331
|
}
|
|
321
332
|
}
|
|
322
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
|
+
|
|
323
435
|
export default {
|
|
324
436
|
async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
|
|
325
437
|
const url = new URL(request.url);
|
package/src/tests/wrangler.jsonc
CHANGED
|
@@ -13,6 +13,18 @@
|
|
|
13
13
|
{
|
|
14
14
|
"class_name": "TestChatAgent",
|
|
15
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"
|
|
16
28
|
}
|
|
17
29
|
]
|
|
18
30
|
},
|
|
@@ -21,6 +33,18 @@
|
|
|
21
33
|
{
|
|
22
34
|
"new_sqlite_classes": ["TestChatAgent"],
|
|
23
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"
|
|
24
48
|
}
|
|
25
49
|
]
|
|
26
50
|
}
|
package/src/types.ts
CHANGED
|
@@ -127,6 +127,10 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
|
|
|
127
127
|
toolName: string;
|
|
128
128
|
/** The output from the tool execution */
|
|
129
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;
|
|
130
134
|
/** Whether server should auto-continue the conversation after applying result */
|
|
131
135
|
autoContinue?: boolean;
|
|
132
136
|
/** Client tool schemas for continuation (client is source of truth) */
|
package/e2e/global-setup.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Playwright global setup: kill any stale process on the test port
|
|
3
|
-
* left behind by a previous run that was forcefully terminated.
|
|
4
|
-
*/
|
|
5
|
-
import { execSync } from "node:child_process";
|
|
6
|
-
|
|
7
|
-
const PORT = 8799;
|
|
8
|
-
|
|
9
|
-
function killProcessOnPort(port: number): void {
|
|
10
|
-
try {
|
|
11
|
-
const output = execSync(`lsof -ti tcp:${port} 2>/dev/null || true`)
|
|
12
|
-
.toString()
|
|
13
|
-
.trim();
|
|
14
|
-
if (output) {
|
|
15
|
-
const pids = output.split("\n").filter(Boolean);
|
|
16
|
-
for (const pid of pids) {
|
|
17
|
-
try {
|
|
18
|
-
process.kill(Number(pid), "SIGKILL");
|
|
19
|
-
console.log(
|
|
20
|
-
`[global-setup] Killed stale process ${pid} on port ${port}`
|
|
21
|
-
);
|
|
22
|
-
} catch {
|
|
23
|
-
// Process may have already exited
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
} catch {
|
|
28
|
-
// lsof not available or other error — ignore
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export default function globalSetup() {
|
|
33
|
-
killProcessOnPort(PORT);
|
|
34
|
-
}
|