@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.
Files changed (66) 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 +170 -28
  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 +125 -31
  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 -244
  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/types.ts +0 -152
  64. package/src/ws-chat-transport.ts +0 -203
  65. package/tsconfig.json +0 -4
  66. package/vitest.config.ts +0 -7
@@ -1,1957 +0,0 @@
1
- import { createExecutionContext, env } from "cloudflare:test";
2
- import { getAgentByName } from "agents";
3
- import { describe, it, expect } from "vitest";
4
- import worker from "./worker";
5
- import type { UIMessage as ChatMessage } from "ai";
6
- import { convertToModelMessages } from "ai";
7
- import {
8
- applyChunkToParts,
9
- type MessageParts,
10
- type StreamChunkData
11
- } from "../message-builder";
12
-
13
- describe("Client-side tool duplicate message prevention", () => {
14
- it("merges tool output into existing message by toolCallId", async () => {
15
- const room = crypto.randomUUID();
16
- const ctx = createExecutionContext();
17
- const req = new Request(
18
- `http://example.com/agents/test-chat-agent/${room}`,
19
- { headers: { Upgrade: "websocket" } }
20
- );
21
- const res = await worker.fetch(req, env, ctx);
22
- expect(res.status).toBe(101);
23
- const ws = res.webSocket as WebSocket;
24
- ws.accept();
25
- await ctx.waitUntil(Promise.resolve());
26
-
27
- const agentStub = await getAgentByName(env.TestChatAgent, room);
28
- const toolCallId = "call_merge_test";
29
-
30
- // Persist assistant message with tool in input-available state
31
- await agentStub.persistMessages([
32
- {
33
- id: "user-1",
34
- role: "user",
35
- parts: [{ type: "text", text: "Test" }]
36
- },
37
- {
38
- id: "assistant-original",
39
- role: "assistant",
40
- parts: [
41
- {
42
- type: "tool-testTool",
43
- toolCallId,
44
- state: "input-available",
45
- input: { param: "value" }
46
- }
47
- ] as ChatMessage["parts"]
48
- }
49
- ]);
50
-
51
- // Persist message with different ID but same toolCallId (simulates second stream)
52
- await agentStub.persistMessages([
53
- {
54
- id: "user-1",
55
- role: "user",
56
- parts: [{ type: "text", text: "Test" }]
57
- },
58
- {
59
- id: "assistant-different-id",
60
- role: "assistant",
61
- parts: [
62
- {
63
- type: "tool-testTool",
64
- toolCallId,
65
- state: "output-available",
66
- input: { param: "value" },
67
- output: "result"
68
- }
69
- ] as ChatMessage["parts"]
70
- }
71
- ]);
72
-
73
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
74
- const assistantMessages = messages.filter((m) => m.role === "assistant");
75
-
76
- // Should have exactly 1 assistant message (merged, not duplicated)
77
- expect(assistantMessages.length).toBe(1);
78
- const toolPart = assistantMessages[0].parts[0] as {
79
- state: string;
80
- output?: unknown;
81
- };
82
- expect(toolPart.state).toBe("output-available");
83
- expect(toolPart.output).toBe("result");
84
-
85
- ws.close(1000);
86
- });
87
-
88
- it("CF_AGENT_TOOL_RESULT applies tool result without auto-continuation by default", async () => {
89
- const room = crypto.randomUUID();
90
- const ctx = createExecutionContext();
91
- const req = new Request(
92
- `http://example.com/agents/test-chat-agent/${room}`,
93
- { headers: { Upgrade: "websocket" } }
94
- );
95
- const res = await worker.fetch(req, env, ctx);
96
- expect(res.status).toBe(101);
97
- const ws = res.webSocket as WebSocket;
98
- ws.accept();
99
- await ctx.waitUntil(Promise.resolve());
100
-
101
- const agentStub = await getAgentByName(env.TestChatAgent, room);
102
- const toolCallId = "call_tool_result_test";
103
-
104
- // Persist assistant message with tool in input-available state
105
- await agentStub.persistMessages([
106
- {
107
- id: "user-1",
108
- role: "user",
109
- parts: [{ type: "text", text: "Execute tool" }]
110
- },
111
- {
112
- id: "assistant-1",
113
- role: "assistant",
114
- parts: [
115
- {
116
- type: "tool-testTool",
117
- toolCallId,
118
- state: "input-available",
119
- input: { param: "value" }
120
- }
121
- ] as ChatMessage["parts"]
122
- }
123
- ]);
124
-
125
- // Send CF_AGENT_TOOL_RESULT via WebSocket WITHOUT autoContinue flag
126
- ws.send(
127
- JSON.stringify({
128
- type: "cf_agent_tool_result",
129
- toolCallId,
130
- toolName: "testTool",
131
- output: { success: true }
132
- // autoContinue not set - should NOT auto-continue
133
- })
134
- );
135
-
136
- await new Promise((resolve) => setTimeout(resolve, 200));
137
-
138
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
139
- const assistantMessages = messages.filter((m) => m.role === "assistant");
140
-
141
- // Should have exactly 1 assistant message (no auto-continuation)
142
- expect(assistantMessages.length).toBe(1);
143
-
144
- const assistantMsg = assistantMessages[0];
145
- expect(assistantMsg.id).toBe("assistant-1");
146
-
147
- // Tool result should be applied
148
- const toolPart = assistantMsg.parts[0] as {
149
- state: string;
150
- output?: unknown;
151
- };
152
- expect(toolPart.state).toBe("output-available");
153
- expect(toolPart.output).toEqual({ success: true });
154
-
155
- // No continuation parts (only the original tool part)
156
- expect(assistantMsg.parts.length).toBe(1);
157
-
158
- ws.close(1000);
159
- });
160
-
161
- it("CF_AGENT_TOOL_RESULT auto-continues and merges when autoContinue is true", async () => {
162
- const room = crypto.randomUUID();
163
- const ctx = createExecutionContext();
164
- const req = new Request(
165
- `http://example.com/agents/test-chat-agent/${room}`,
166
- { headers: { Upgrade: "websocket" } }
167
- );
168
- const res = await worker.fetch(req, env, ctx);
169
- expect(res.status).toBe(101);
170
- const ws = res.webSocket as WebSocket;
171
- ws.accept();
172
- await ctx.waitUntil(Promise.resolve());
173
-
174
- const agentStub = await getAgentByName(env.TestChatAgent, room);
175
- const toolCallId = "call_tool_result_auto_continue";
176
-
177
- // Persist assistant message with tool in input-available state
178
- await agentStub.persistMessages([
179
- {
180
- id: "user-1",
181
- role: "user",
182
- parts: [{ type: "text", text: "Execute tool" }]
183
- },
184
- {
185
- id: "assistant-1",
186
- role: "assistant",
187
- parts: [
188
- {
189
- type: "tool-testTool",
190
- toolCallId,
191
- state: "input-available",
192
- input: { param: "value" }
193
- }
194
- ] as ChatMessage["parts"]
195
- }
196
- ]);
197
-
198
- // Send CF_AGENT_TOOL_RESULT with autoContinue: true
199
- ws.send(
200
- JSON.stringify({
201
- type: "cf_agent_tool_result",
202
- toolCallId,
203
- toolName: "testTool",
204
- output: { success: true },
205
- autoContinue: true
206
- })
207
- );
208
-
209
- // Wait for tool result to be applied and continuation to happen
210
- // Note: When there's no active stream, the continuation waits 500ms before proceeding
211
- await new Promise((resolve) => setTimeout(resolve, 800));
212
-
213
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
214
- const assistantMessages = messages.filter((m) => m.role === "assistant");
215
-
216
- // Should still have exactly 1 assistant message (continuation merged into it)
217
- expect(assistantMessages.length).toBe(1);
218
-
219
- const assistantMsg = assistantMessages[0];
220
- expect(assistantMsg.id).toBe("assistant-1");
221
-
222
- // First part should be the tool with result applied
223
- const toolPart = assistantMsg.parts[0] as {
224
- state: string;
225
- output?: unknown;
226
- };
227
- expect(toolPart.state).toBe("output-available");
228
- expect(toolPart.output).toEqual({ success: true });
229
-
230
- // Continuation parts should be appended (TestChatAgent returns text response)
231
- expect(assistantMsg.parts.length).toBeGreaterThan(1);
232
-
233
- ws.close(1000);
234
- });
235
-
236
- it("strips OpenAI itemIds from persisted messages to prevent duplicate errors", async () => {
237
- const room = crypto.randomUUID();
238
- const ctx = createExecutionContext();
239
- const req = new Request(
240
- `http://example.com/agents/test-chat-agent/${room}`,
241
- { headers: { Upgrade: "websocket" } }
242
- );
243
- const res = await worker.fetch(req, env, ctx);
244
- expect(res.status).toBe(101);
245
- const ws = res.webSocket as WebSocket;
246
- ws.accept();
247
- await ctx.waitUntil(Promise.resolve());
248
-
249
- const agentStub = await getAgentByName(env.TestChatAgent, room);
250
-
251
- // Persist message with OpenAI itemId in providerMetadata (simulates OpenAI Responses API)
252
- await agentStub.persistMessages([
253
- {
254
- id: "user-1",
255
- role: "user",
256
- parts: [{ type: "text", text: "Hello" }]
257
- },
258
- {
259
- id: "assistant-1",
260
- role: "assistant",
261
- parts: [
262
- {
263
- type: "text",
264
- text: "Hello! How can I help?",
265
- providerMetadata: {
266
- openai: {
267
- itemId: "msg_abc123xyz" // This should be stripped
268
- }
269
- }
270
- }
271
- ] as ChatMessage["parts"]
272
- }
273
- ]);
274
-
275
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
276
- const assistantMessage = messages.find((m) => m.role === "assistant");
277
-
278
- expect(assistantMessage).toBeDefined();
279
- const textPart = assistantMessage!.parts[0] as {
280
- type: string;
281
- text: string;
282
- providerMetadata?: {
283
- openai?: {
284
- itemId?: string;
285
- };
286
- };
287
- };
288
-
289
- // The itemId should have been stripped during persistence
290
- expect(textPart.text).toBe("Hello! How can I help?");
291
- expect(textPart.providerMetadata?.openai?.itemId).toBeUndefined();
292
-
293
- ws.close(1000);
294
- });
295
-
296
- it("strips OpenAI itemIds from tool parts with callProviderMetadata", async () => {
297
- const room = crypto.randomUUID();
298
- const ctx = createExecutionContext();
299
- const req = new Request(
300
- `http://example.com/agents/test-chat-agent/${room}`,
301
- { headers: { Upgrade: "websocket" } }
302
- );
303
- const res = await worker.fetch(req, env, ctx);
304
- expect(res.status).toBe(101);
305
- const ws = res.webSocket as WebSocket;
306
- ws.accept();
307
- await ctx.waitUntil(Promise.resolve());
308
-
309
- const agentStub = await getAgentByName(env.TestChatAgent, room);
310
- const toolCallId = "call_openai_strip_test";
311
-
312
- // Persist message with tool that has OpenAI itemId in callProviderMetadata
313
- await agentStub.persistMessages([
314
- {
315
- id: "user-1",
316
- role: "user",
317
- parts: [{ type: "text", text: "What time is it?" }]
318
- },
319
- {
320
- id: "assistant-1",
321
- role: "assistant",
322
- parts: [
323
- {
324
- type: "tool-getTime",
325
- toolCallId,
326
- state: "input-available",
327
- input: { timezone: "UTC" },
328
- callProviderMetadata: {
329
- openai: {
330
- itemId: "fc_xyz789" // This should be stripped
331
- }
332
- }
333
- }
334
- ] as ChatMessage["parts"]
335
- }
336
- ]);
337
-
338
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
339
- const assistantMessage = messages.find((m) => m.role === "assistant");
340
-
341
- expect(assistantMessage).toBeDefined();
342
- const toolPart = assistantMessage!.parts[0] as {
343
- type: string;
344
- toolCallId: string;
345
- callProviderMetadata?: {
346
- openai?: {
347
- itemId?: string;
348
- };
349
- };
350
- };
351
-
352
- // The itemId should have been stripped during persistence
353
- expect(toolPart.toolCallId).toBe(toolCallId);
354
- expect(toolPart.callProviderMetadata?.openai?.itemId).toBeUndefined();
355
-
356
- ws.close(1000);
357
- });
358
-
359
- it("preserves other providerMetadata when stripping itemId", async () => {
360
- const room = crypto.randomUUID();
361
- const ctx = createExecutionContext();
362
- const req = new Request(
363
- `http://example.com/agents/test-chat-agent/${room}`,
364
- { headers: { Upgrade: "websocket" } }
365
- );
366
- const res = await worker.fetch(req, env, ctx);
367
- expect(res.status).toBe(101);
368
- const ws = res.webSocket as WebSocket;
369
- ws.accept();
370
- await ctx.waitUntil(Promise.resolve());
371
-
372
- const agentStub = await getAgentByName(env.TestChatAgent, room);
373
-
374
- // Persist message with other metadata alongside itemId
375
- await agentStub.persistMessages([
376
- {
377
- id: "user-1",
378
- role: "user",
379
- parts: [{ type: "text", text: "Hello" }]
380
- },
381
- {
382
- id: "assistant-1",
383
- role: "assistant",
384
- parts: [
385
- {
386
- type: "text",
387
- text: "Hello!",
388
- providerMetadata: {
389
- openai: {
390
- itemId: "msg_strip_me", // Should be stripped
391
- someOtherField: "keep_me" // Should be preserved
392
- },
393
- anthropic: {
394
- someField: "also_keep_me" // Should be preserved
395
- }
396
- }
397
- }
398
- ] as ChatMessage["parts"]
399
- }
400
- ]);
401
-
402
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
403
- const assistantMessage = messages.find((m) => m.role === "assistant");
404
-
405
- expect(assistantMessage).toBeDefined();
406
- const textPart = assistantMessage!.parts[0] as {
407
- type: string;
408
- providerMetadata?: {
409
- openai?: {
410
- itemId?: string;
411
- someOtherField?: string;
412
- };
413
- anthropic?: {
414
- someField?: string;
415
- };
416
- };
417
- };
418
-
419
- // itemId should be stripped
420
- expect(textPart.providerMetadata?.openai?.itemId).toBeUndefined();
421
- // Other fields should be preserved
422
- expect(textPart.providerMetadata?.openai?.someOtherField).toBe("keep_me");
423
- expect(textPart.providerMetadata?.anthropic?.someField).toBe(
424
- "also_keep_me"
425
- );
426
-
427
- ws.close(1000);
428
- });
429
-
430
- it("filters out empty reasoning parts to prevent AI SDK warnings", async () => {
431
- const room = crypto.randomUUID();
432
- const ctx = createExecutionContext();
433
- const req = new Request(
434
- `http://example.com/agents/test-chat-agent/${room}`,
435
- { headers: { Upgrade: "websocket" } }
436
- );
437
- const res = await worker.fetch(req, env, ctx);
438
- expect(res.status).toBe(101);
439
- const ws = res.webSocket as WebSocket;
440
- ws.accept();
441
- await ctx.waitUntil(Promise.resolve());
442
-
443
- const agentStub = await getAgentByName(env.TestChatAgent, room);
444
-
445
- // Persist message with empty reasoning part (simulates OpenAI Responses API)
446
- await agentStub.persistMessages([
447
- {
448
- id: "user-1",
449
- role: "user",
450
- parts: [{ type: "text", text: "Think about this" }]
451
- },
452
- {
453
- id: "assistant-1",
454
- role: "assistant",
455
- parts: [
456
- {
457
- type: "reasoning",
458
- text: "", // Empty reasoning - should be filtered out
459
- providerMetadata: {
460
- openai: {
461
- reasoningEncryptedContent: null
462
- }
463
- }
464
- },
465
- {
466
- type: "text",
467
- text: "Here is my response"
468
- }
469
- ] as ChatMessage["parts"]
470
- }
471
- ]);
472
-
473
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
474
- const assistantMessage = messages.find((m) => m.role === "assistant");
475
-
476
- expect(assistantMessage).toBeDefined();
477
- // Empty reasoning part should have been filtered out
478
- expect(assistantMessage!.parts.length).toBe(1);
479
- expect(assistantMessage!.parts[0].type).toBe("text");
480
-
481
- ws.close(1000);
482
- });
483
-
484
- it("preserves non-empty reasoning parts", async () => {
485
- const room = crypto.randomUUID();
486
- const ctx = createExecutionContext();
487
- const req = new Request(
488
- `http://example.com/agents/test-chat-agent/${room}`,
489
- { headers: { Upgrade: "websocket" } }
490
- );
491
- const res = await worker.fetch(req, env, ctx);
492
- expect(res.status).toBe(101);
493
- const ws = res.webSocket as WebSocket;
494
- ws.accept();
495
- await ctx.waitUntil(Promise.resolve());
496
-
497
- const agentStub = await getAgentByName(env.TestChatAgent, room);
498
-
499
- // Persist message with non-empty reasoning part
500
- await agentStub.persistMessages([
501
- {
502
- id: "user-1",
503
- role: "user",
504
- parts: [{ type: "text", text: "Think about this" }]
505
- },
506
- {
507
- id: "assistant-1",
508
- role: "assistant",
509
- parts: [
510
- {
511
- type: "reasoning",
512
- text: "Let me think about this carefully...", // Non-empty - should be kept
513
- providerMetadata: {
514
- openai: {
515
- itemId: "reason_123" // But itemId should still be stripped
516
- }
517
- }
518
- },
519
- {
520
- type: "text",
521
- text: "Here is my response"
522
- }
523
- ] as ChatMessage["parts"]
524
- }
525
- ]);
526
-
527
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
528
- const assistantMessage = messages.find((m) => m.role === "assistant");
529
-
530
- expect(assistantMessage).toBeDefined();
531
- // Non-empty reasoning part should be preserved
532
- expect(assistantMessage!.parts.length).toBe(2);
533
- expect(assistantMessage!.parts[0].type).toBe("reasoning");
534
-
535
- const reasoningPart = assistantMessage!.parts[0] as {
536
- type: string;
537
- text: string;
538
- providerMetadata?: {
539
- openai?: {
540
- itemId?: string;
541
- };
542
- };
543
- };
544
- expect(reasoningPart.text).toBe("Let me think about this carefully...");
545
- // itemId should still be stripped
546
- expect(reasoningPart.providerMetadata?.openai?.itemId).toBeUndefined();
547
-
548
- ws.close(1000);
549
- });
550
- });
551
-
552
- describe("Tool approval (needsApproval) duplicate message prevention", () => {
553
- it("CF_AGENT_TOOL_APPROVAL updates existing message in place", async () => {
554
- const room = crypto.randomUUID();
555
- const ctx = createExecutionContext();
556
- const req = new Request(
557
- `http://example.com/agents/test-chat-agent/${room}`,
558
- { headers: { Upgrade: "websocket" } }
559
- );
560
- const res = await worker.fetch(req, env, ctx);
561
- expect(res.status).toBe(101);
562
- const ws = res.webSocket as WebSocket;
563
- ws.accept();
564
- await ctx.waitUntil(Promise.resolve());
565
-
566
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
567
- const toolCallId = "call_approval_test";
568
-
569
- // Persist assistant message with tool in input-available state (needs approval)
570
- await agentStub.persistMessages([
571
- {
572
- id: "user-1",
573
- role: "user",
574
- parts: [{ type: "text", text: "Execute tool" }]
575
- },
576
- {
577
- id: "assistant-1",
578
- role: "assistant",
579
- parts: [
580
- {
581
- type: "tool-testTool",
582
- toolCallId,
583
- state: "input-available",
584
- input: { param: "value" }
585
- }
586
- ] as ChatMessage["parts"]
587
- }
588
- ]);
589
-
590
- // Send CF_AGENT_TOOL_APPROVAL via WebSocket
591
- ws.send(
592
- JSON.stringify({
593
- type: "cf_agent_tool_approval",
594
- toolCallId,
595
- approved: true
596
- })
597
- );
598
-
599
- await new Promise((resolve) => setTimeout(resolve, 200));
600
-
601
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
602
- const assistantMessages = messages.filter((m) => m.role === "assistant");
603
-
604
- // Should have exactly 1 assistant message (updated in place, not duplicated)
605
- expect(assistantMessages.length).toBe(1);
606
-
607
- const assistantMsg = assistantMessages[0];
608
- // Message ID should be preserved
609
- expect(assistantMsg.id).toBe("assistant-1");
610
-
611
- // Tool state should be updated to approval-responded
612
- const toolPart = assistantMsg.parts[0] as {
613
- state: string;
614
- approval?: { approved: boolean };
615
- };
616
- expect(toolPart.state).toBe("approval-responded");
617
- expect(toolPart.approval).toEqual({ approved: true });
618
-
619
- ws.close(1000);
620
- });
621
-
622
- it("CF_AGENT_TOOL_APPROVAL handles rejection (approved: false)", async () => {
623
- const room = crypto.randomUUID();
624
- const ctx = createExecutionContext();
625
- const req = new Request(
626
- `http://example.com/agents/test-chat-agent/${room}`,
627
- { headers: { Upgrade: "websocket" } }
628
- );
629
- const res = await worker.fetch(req, env, ctx);
630
- expect(res.status).toBe(101);
631
- const ws = res.webSocket as WebSocket;
632
- ws.accept();
633
- await ctx.waitUntil(Promise.resolve());
634
-
635
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
636
- const toolCallId = "call_rejection_test";
637
-
638
- // Persist assistant message with tool in input-available state
639
- await agentStub.persistMessages([
640
- {
641
- id: "user-1",
642
- role: "user",
643
- parts: [{ type: "text", text: "Execute tool" }]
644
- },
645
- {
646
- id: "assistant-1",
647
- role: "assistant",
648
- parts: [
649
- {
650
- type: "tool-testTool",
651
- toolCallId,
652
- state: "input-available",
653
- input: { param: "value" }
654
- }
655
- ] as ChatMessage["parts"]
656
- }
657
- ]);
658
-
659
- // Send CF_AGENT_TOOL_APPROVAL with approved: false (rejection)
660
- ws.send(
661
- JSON.stringify({
662
- type: "cf_agent_tool_approval",
663
- toolCallId,
664
- approved: false
665
- })
666
- );
667
-
668
- await new Promise((resolve) => setTimeout(resolve, 200));
669
-
670
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
671
- const assistantMessages = messages.filter((m) => m.role === "assistant");
672
-
673
- expect(assistantMessages.length).toBe(1);
674
-
675
- const toolPart = assistantMessages[0].parts[0] as {
676
- state: string;
677
- approval?: { approved: boolean };
678
- };
679
- expect(toolPart.state).toBe("output-denied");
680
- expect(toolPart.approval).toEqual({ approved: false });
681
-
682
- ws.close(1000);
683
- });
684
-
685
- it("CF_AGENT_TOOL_APPROVAL updates tool in approval-requested state", async () => {
686
- const room = crypto.randomUUID();
687
- const ctx = createExecutionContext();
688
- const req = new Request(
689
- `http://example.com/agents/test-chat-agent/${room}`,
690
- { headers: { Upgrade: "websocket" } }
691
- );
692
- const res = await worker.fetch(req, env, ctx);
693
- expect(res.status).toBe(101);
694
- const ws = res.webSocket as WebSocket;
695
- ws.accept();
696
- await ctx.waitUntil(Promise.resolve());
697
-
698
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
699
- const toolCallId = "call_approval_requested_test";
700
-
701
- // Persist assistant message with tool in approval-requested state
702
- await agentStub.persistMessages([
703
- {
704
- id: "user-1",
705
- role: "user",
706
- parts: [{ type: "text", text: "Execute tool" }]
707
- },
708
- {
709
- id: "assistant-1",
710
- role: "assistant",
711
- parts: [
712
- {
713
- type: "tool-testTool",
714
- toolCallId,
715
- state: "approval-requested",
716
- input: { param: "value" },
717
- approval: { id: "approval-123" }
718
- }
719
- ] as ChatMessage["parts"]
720
- }
721
- ]);
722
-
723
- // Send CF_AGENT_TOOL_APPROVAL
724
- ws.send(
725
- JSON.stringify({
726
- type: "cf_agent_tool_approval",
727
- toolCallId,
728
- approved: true
729
- })
730
- );
731
-
732
- await new Promise((resolve) => setTimeout(resolve, 200));
733
-
734
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
735
- const assistantMessages = messages.filter((m) => m.role === "assistant");
736
-
737
- expect(assistantMessages.length).toBe(1);
738
-
739
- const toolPart = assistantMessages[0].parts[0] as {
740
- state: string;
741
- approval?: { approved: boolean };
742
- };
743
- expect(toolPart.state).toBe("approval-responded");
744
- // approval.id is preserved from the approval-requested state
745
- expect(toolPart.approval).toEqual({ id: "approval-123", approved: true });
746
-
747
- ws.close(1000);
748
- });
749
-
750
- it("CF_AGENT_TOOL_APPROVAL rejection from approval-requested sets output-denied", async () => {
751
- const room = crypto.randomUUID();
752
- const ctx = createExecutionContext();
753
- const req = new Request(
754
- `http://example.com/agents/test-chat-agent/${room}`,
755
- { headers: { Upgrade: "websocket" } }
756
- );
757
- const res = await worker.fetch(req, env, ctx);
758
- expect(res.status).toBe(101);
759
- const ws = res.webSocket as WebSocket;
760
- ws.accept();
761
- await ctx.waitUntil(Promise.resolve());
762
-
763
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
764
- const toolCallId = "call_approval_requested_rejected";
765
-
766
- await agentStub.persistMessages([
767
- {
768
- id: "user-1",
769
- role: "user",
770
- parts: [{ type: "text", text: "Execute tool" }]
771
- },
772
- {
773
- id: "assistant-1",
774
- role: "assistant",
775
- parts: [
776
- {
777
- type: "tool-testTool",
778
- toolCallId,
779
- state: "approval-requested",
780
- input: { param: "value" },
781
- approval: { id: "approval-789" }
782
- }
783
- ] as ChatMessage["parts"]
784
- }
785
- ]);
786
-
787
- ws.send(
788
- JSON.stringify({
789
- type: "cf_agent_tool_approval",
790
- toolCallId,
791
- approved: false
792
- })
793
- );
794
-
795
- await new Promise((resolve) => setTimeout(resolve, 200));
796
-
797
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
798
- const assistantMessages = messages.filter((m) => m.role === "assistant");
799
-
800
- expect(assistantMessages.length).toBe(1);
801
-
802
- const toolPart = assistantMessages[0].parts[0] as {
803
- state: string;
804
- approval?: { id: string; approved: boolean };
805
- };
806
- expect(toolPart.state).toBe("output-denied");
807
- expect(toolPart.approval).toEqual({ id: "approval-789", approved: false });
808
-
809
- ws.close(1000);
810
- });
811
-
812
- it("CF_AGENT_TOOL_APPROVAL with non-existent toolCallId logs warning", async () => {
813
- const room = crypto.randomUUID();
814
- const ctx = createExecutionContext();
815
- const req = new Request(
816
- `http://example.com/agents/test-chat-agent/${room}`,
817
- { headers: { Upgrade: "websocket" } }
818
- );
819
- const res = await worker.fetch(req, env, ctx);
820
- expect(res.status).toBe(101);
821
- const ws = res.webSocket as WebSocket;
822
- ws.accept();
823
- await ctx.waitUntil(Promise.resolve());
824
-
825
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
826
-
827
- // Persist a message without any tool calls
828
- await agentStub.persistMessages([
829
- {
830
- id: "user-1",
831
- role: "user",
832
- parts: [{ type: "text", text: "Hello" }]
833
- },
834
- {
835
- id: "assistant-1",
836
- role: "assistant",
837
- parts: [{ type: "text", text: "Hi there!" }] as ChatMessage["parts"]
838
- }
839
- ]);
840
-
841
- // Send CF_AGENT_TOOL_APPROVAL for non-existent tool
842
- ws.send(
843
- JSON.stringify({
844
- type: "cf_agent_tool_approval",
845
- toolCallId: "non_existent_tool_call",
846
- approved: true
847
- })
848
- );
849
-
850
- await new Promise((resolve) => setTimeout(resolve, 1200)); // Wait for retries (10 * 100ms + buffer)
851
-
852
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
853
-
854
- // Messages should remain unchanged (no crash, graceful handling)
855
- expect(messages.length).toBe(2);
856
- const assistantMsg = messages.find((m) => m.role === "assistant");
857
- expect(assistantMsg?.parts[0]).toEqual({ type: "text", text: "Hi there!" });
858
-
859
- ws.close(1000);
860
- });
861
-
862
- it("CF_AGENT_TOOL_APPROVAL does not update tool already in output-available state", async () => {
863
- const room = crypto.randomUUID();
864
- const ctx = createExecutionContext();
865
- const req = new Request(
866
- `http://example.com/agents/test-chat-agent/${room}`,
867
- { headers: { Upgrade: "websocket" } }
868
- );
869
- const res = await worker.fetch(req, env, ctx);
870
- expect(res.status).toBe(101);
871
- const ws = res.webSocket as WebSocket;
872
- ws.accept();
873
- await ctx.waitUntil(Promise.resolve());
874
-
875
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
876
- const toolCallId = "call_already_completed";
877
-
878
- // Persist assistant message with tool already in output-available state
879
- await agentStub.persistMessages([
880
- {
881
- id: "user-1",
882
- role: "user",
883
- parts: [{ type: "text", text: "Execute tool" }]
884
- },
885
- {
886
- id: "assistant-1",
887
- role: "assistant",
888
- parts: [
889
- {
890
- type: "tool-testTool",
891
- toolCallId,
892
- state: "output-available",
893
- input: { param: "value" },
894
- output: { result: "done" }
895
- }
896
- ] as ChatMessage["parts"]
897
- }
898
- ]);
899
-
900
- // Send CF_AGENT_TOOL_APPROVAL for tool that's already completed
901
- ws.send(
902
- JSON.stringify({
903
- type: "cf_agent_tool_approval",
904
- toolCallId,
905
- approved: true
906
- })
907
- );
908
-
909
- await new Promise((resolve) => setTimeout(resolve, 200));
910
-
911
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
912
- const assistantMessages = messages.filter((m) => m.role === "assistant");
913
-
914
- expect(assistantMessages.length).toBe(1);
915
-
916
- // State should remain output-available (not changed to approval-responded)
917
- const toolPart = assistantMessages[0].parts[0] as {
918
- state: string;
919
- output?: unknown;
920
- };
921
- expect(toolPart.state).toBe("output-available");
922
- expect(toolPart.output).toEqual({ result: "done" });
923
-
924
- ws.close(1000);
925
- });
926
- });
927
-
928
- describe("Tool approval auto-continuation (needsApproval)", () => {
929
- it("CF_AGENT_TOOL_APPROVAL without autoContinue does NOT trigger continuation", async () => {
930
- const room = crypto.randomUUID();
931
- const ctx = createExecutionContext();
932
- const req = new Request(
933
- `http://example.com/agents/test-chat-agent/${room}`,
934
- { headers: { Upgrade: "websocket" } }
935
- );
936
- const res = await worker.fetch(req, env, ctx);
937
- expect(res.status).toBe(101);
938
- const ws = res.webSocket as WebSocket;
939
- ws.accept();
940
- await ctx.waitUntil(Promise.resolve());
941
-
942
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
943
- const toolCallId = "call_no_auto_continue";
944
-
945
- // Persist assistant message with tool in input-available state
946
- await agentStub.persistMessages([
947
- {
948
- id: "user-1",
949
- role: "user",
950
- parts: [{ type: "text", text: "Execute tool" }]
951
- },
952
- {
953
- id: "assistant-1",
954
- role: "assistant",
955
- parts: [
956
- {
957
- type: "tool-testTool",
958
- toolCallId,
959
- state: "input-available",
960
- input: { param: "value" }
961
- }
962
- ] as ChatMessage["parts"]
963
- }
964
- ]);
965
-
966
- // Send approval WITHOUT autoContinue
967
- ws.send(
968
- JSON.stringify({
969
- type: "cf_agent_tool_approval",
970
- toolCallId,
971
- approved: true
972
- // no autoContinue
973
- })
974
- );
975
-
976
- await new Promise((resolve) => setTimeout(resolve, 800));
977
-
978
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
979
- const assistantMessages = messages.filter((m) => m.role === "assistant");
980
-
981
- // Should have exactly 1 assistant message (no continuation)
982
- expect(assistantMessages.length).toBe(1);
983
-
984
- const assistantMsg = assistantMessages[0];
985
- expect(assistantMsg.id).toBe("assistant-1");
986
-
987
- // Tool state should be approval-responded but no continuation parts
988
- const toolPart = assistantMsg.parts[0] as {
989
- state: string;
990
- approval?: { approved: boolean };
991
- };
992
- expect(toolPart.state).toBe("approval-responded");
993
- expect(toolPart.approval).toEqual({ approved: true });
994
- expect(assistantMsg.parts.length).toBe(1);
995
-
996
- ws.close(1000);
997
- });
998
-
999
- it("CF_AGENT_TOOL_APPROVAL with autoContinue triggers continuation", async () => {
1000
- const room = crypto.randomUUID();
1001
- const ctx = createExecutionContext();
1002
- const req = new Request(
1003
- `http://example.com/agents/test-chat-agent/${room}`,
1004
- { headers: { Upgrade: "websocket" } }
1005
- );
1006
- const res = await worker.fetch(req, env, ctx);
1007
- expect(res.status).toBe(101);
1008
- const ws = res.webSocket as WebSocket;
1009
- ws.accept();
1010
- await ctx.waitUntil(Promise.resolve());
1011
-
1012
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1013
- const toolCallId = "call_auto_continue_approval";
1014
-
1015
- // Persist assistant message with tool in input-available state
1016
- await agentStub.persistMessages([
1017
- {
1018
- id: "user-1",
1019
- role: "user",
1020
- parts: [{ type: "text", text: "Execute tool" }]
1021
- },
1022
- {
1023
- id: "assistant-1",
1024
- role: "assistant",
1025
- parts: [
1026
- {
1027
- type: "tool-testTool",
1028
- toolCallId,
1029
- state: "input-available",
1030
- input: { param: "value" }
1031
- }
1032
- ] as ChatMessage["parts"]
1033
- }
1034
- ]);
1035
-
1036
- // Send approval WITH autoContinue: true
1037
- ws.send(
1038
- JSON.stringify({
1039
- type: "cf_agent_tool_approval",
1040
- toolCallId,
1041
- approved: true,
1042
- autoContinue: true
1043
- })
1044
- );
1045
-
1046
- // Wait for approval + continuation (500ms wait + stream)
1047
- await new Promise((resolve) => setTimeout(resolve, 800));
1048
-
1049
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1050
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1051
-
1052
- // Should still have 1 assistant message (continuation merged into it)
1053
- expect(assistantMessages.length).toBe(1);
1054
-
1055
- const assistantMsg = assistantMessages[0];
1056
- expect(assistantMsg.id).toBe("assistant-1");
1057
-
1058
- // First part should be the approved tool
1059
- const toolPart = assistantMsg.parts[0] as {
1060
- state: string;
1061
- approval?: { approved: boolean };
1062
- };
1063
- expect(toolPart.state).toBe("approval-responded");
1064
- expect(toolPart.approval).toEqual({ approved: true });
1065
-
1066
- // Continuation parts should be appended (TestChatAgent returns text response)
1067
- expect(assistantMsg.parts.length).toBeGreaterThan(1);
1068
-
1069
- ws.close(1000);
1070
- });
1071
-
1072
- it("CF_AGENT_TOOL_APPROVAL with approved: false and autoContinue triggers continuation", async () => {
1073
- const room = crypto.randomUUID();
1074
- const ctx = createExecutionContext();
1075
- const req = new Request(
1076
- `http://example.com/agents/test-chat-agent/${room}`,
1077
- { headers: { Upgrade: "websocket" } }
1078
- );
1079
- const res = await worker.fetch(req, env, ctx);
1080
- expect(res.status).toBe(101);
1081
- const ws = res.webSocket as WebSocket;
1082
- ws.accept();
1083
- await ctx.waitUntil(Promise.resolve());
1084
-
1085
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1086
- const toolCallId = "call_rejected_continue";
1087
-
1088
- await agentStub.persistMessages([
1089
- {
1090
- id: "user-1",
1091
- role: "user",
1092
- parts: [{ type: "text", text: "Execute tool" }]
1093
- },
1094
- {
1095
- id: "assistant-1",
1096
- role: "assistant",
1097
- parts: [
1098
- {
1099
- type: "tool-testTool",
1100
- toolCallId,
1101
- state: "input-available",
1102
- input: { param: "value" }
1103
- }
1104
- ] as ChatMessage["parts"]
1105
- }
1106
- ]);
1107
-
1108
- ws.send(
1109
- JSON.stringify({
1110
- type: "cf_agent_tool_approval",
1111
- toolCallId,
1112
- approved: false,
1113
- autoContinue: true
1114
- })
1115
- );
1116
-
1117
- await new Promise((resolve) => setTimeout(resolve, 800));
1118
-
1119
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1120
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1121
-
1122
- expect(assistantMessages.length).toBe(1);
1123
-
1124
- const assistantMsg = assistantMessages[0];
1125
- const toolPart = assistantMsg.parts[0] as {
1126
- state: string;
1127
- approval?: { approved: boolean };
1128
- };
1129
- expect(toolPart.state).toBe("output-denied");
1130
- expect(toolPart.approval).toEqual({ approved: false });
1131
-
1132
- // Continuation parts should be appended (LLM sees denial and responds)
1133
- expect(assistantMsg.parts.length).toBeGreaterThan(1);
1134
-
1135
- ws.close(1000);
1136
- });
1137
-
1138
- it("CF_AGENT_TOOL_APPROVAL with autoContinue on approval-requested state triggers continuation", async () => {
1139
- const room = crypto.randomUUID();
1140
- const ctx = createExecutionContext();
1141
- const req = new Request(
1142
- `http://example.com/agents/test-chat-agent/${room}`,
1143
- { headers: { Upgrade: "websocket" } }
1144
- );
1145
- const res = await worker.fetch(req, env, ctx);
1146
- expect(res.status).toBe(101);
1147
- const ws = res.webSocket as WebSocket;
1148
- ws.accept();
1149
- await ctx.waitUntil(Promise.resolve());
1150
-
1151
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1152
- const toolCallId = "call_approval_requested_continue";
1153
-
1154
- // Persist assistant message with tool in approval-requested state
1155
- await agentStub.persistMessages([
1156
- {
1157
- id: "user-1",
1158
- role: "user",
1159
- parts: [{ type: "text", text: "Execute tool" }]
1160
- },
1161
- {
1162
- id: "assistant-1",
1163
- role: "assistant",
1164
- parts: [
1165
- {
1166
- type: "tool-testTool",
1167
- toolCallId,
1168
- state: "approval-requested",
1169
- input: { param: "value" },
1170
- approval: { id: "approval-456" }
1171
- }
1172
- ] as ChatMessage["parts"]
1173
- }
1174
- ]);
1175
-
1176
- // Send approval with autoContinue
1177
- ws.send(
1178
- JSON.stringify({
1179
- type: "cf_agent_tool_approval",
1180
- toolCallId,
1181
- approved: true,
1182
- autoContinue: true
1183
- })
1184
- );
1185
-
1186
- await new Promise((resolve) => setTimeout(resolve, 800));
1187
-
1188
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1189
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1190
-
1191
- expect(assistantMessages.length).toBe(1);
1192
-
1193
- const assistantMsg = assistantMessages[0];
1194
-
1195
- // Tool part should be updated
1196
- const toolPart = assistantMsg.parts[0] as {
1197
- state: string;
1198
- approval?: { approved: boolean };
1199
- };
1200
- expect(toolPart.state).toBe("approval-responded");
1201
- expect(toolPart.approval).toEqual({ id: "approval-456", approved: true });
1202
-
1203
- // Continuation should have appended parts
1204
- expect(assistantMsg.parts.length).toBeGreaterThan(1);
1205
-
1206
- ws.close(1000);
1207
- });
1208
- });
1209
-
1210
- describe("applyChunkToParts: tool-approval-request", () => {
1211
- it("transitions tool part from input-available to approval-requested", () => {
1212
- const parts: MessageParts = [
1213
- {
1214
- type: "tool-calculate",
1215
- toolCallId: "call_123",
1216
- toolName: "calculate",
1217
- state: "input-available",
1218
- input: { a: 5000, b: 3, operator: "*" }
1219
- } as MessageParts[number]
1220
- ];
1221
-
1222
- const handled = applyChunkToParts(parts, {
1223
- type: "tool-approval-request",
1224
- approvalId: "approval-abc",
1225
- toolCallId: "call_123"
1226
- } as StreamChunkData);
1227
-
1228
- expect(handled).toBe(true);
1229
- const part = parts[0] as Record<string, unknown>;
1230
- expect(part.state).toBe("approval-requested");
1231
- expect(part.approval).toEqual({ id: "approval-abc" });
1232
- // Input should be preserved
1233
- expect(part.input).toEqual({ a: 5000, b: 3, operator: "*" });
1234
- });
1235
-
1236
- it("does nothing if tool part not found", () => {
1237
- const parts: MessageParts = [];
1238
-
1239
- const handled = applyChunkToParts(parts, {
1240
- type: "tool-approval-request",
1241
- approvalId: "approval-abc",
1242
- toolCallId: "call_nonexistent"
1243
- } as StreamChunkData);
1244
-
1245
- expect(handled).toBe(true);
1246
- expect(parts.length).toBe(0);
1247
- });
1248
- });
1249
-
1250
- describe("applyChunkToParts: tool-output-denied", () => {
1251
- it("transitions tool part to output-denied state", () => {
1252
- const parts: MessageParts = [
1253
- {
1254
- type: "tool-calculate",
1255
- toolCallId: "call_456",
1256
- toolName: "calculate",
1257
- state: "approval-requested",
1258
- input: { a: 5000, b: 3, operator: "*" },
1259
- approval: { id: "approval-xyz" }
1260
- } as MessageParts[number]
1261
- ];
1262
-
1263
- const handled = applyChunkToParts(parts, {
1264
- type: "tool-output-denied",
1265
- toolCallId: "call_456"
1266
- } as StreamChunkData);
1267
-
1268
- expect(handled).toBe(true);
1269
- const part = parts[0] as Record<string, unknown>;
1270
- expect(part.state).toBe("output-denied");
1271
- // Input and approval should be preserved
1272
- expect(part.input).toEqual({ a: 5000, b: 3, operator: "*" });
1273
- expect(part.approval).toEqual({ id: "approval-xyz" });
1274
- });
1275
- });
1276
-
1277
- describe("Tool approval persistence across reconnect", () => {
1278
- it("persisted messages include approval-requested state after approval-request chunk", async () => {
1279
- const room = crypto.randomUUID();
1280
- const ctx = createExecutionContext();
1281
- const req = new Request(
1282
- `http://example.com/agents/test-chat-agent/${room}`,
1283
- { headers: { Upgrade: "websocket" } }
1284
- );
1285
- const res = await worker.fetch(req, env, ctx);
1286
- expect(res.status).toBe(101);
1287
- const ws = res.webSocket as WebSocket;
1288
- ws.accept();
1289
- await ctx.waitUntil(Promise.resolve());
1290
-
1291
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1292
- const toolCallId = "call_persist_approval_test";
1293
-
1294
- // Manually persist messages that simulate the state after
1295
- // a tool-approval-request was received and early-persisted.
1296
- // In a real flow, the streaming handler would do this.
1297
- await agentStub.persistMessages([
1298
- {
1299
- id: "user-1",
1300
- role: "user",
1301
- parts: [{ type: "text", text: "Calculate 5000 * 3" }]
1302
- },
1303
- {
1304
- id: "assistant-1",
1305
- role: "assistant",
1306
- parts: [
1307
- {
1308
- type: "tool-calculate",
1309
- toolCallId,
1310
- state: "approval-requested",
1311
- input: { a: 5000, b: 3, operator: "*" },
1312
- approval: { id: "approval-persist-test" }
1313
- }
1314
- ] as ChatMessage["parts"]
1315
- }
1316
- ]);
1317
-
1318
- // Verify the messages were persisted with approval-requested state
1319
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1320
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1321
- expect(assistantMessages.length).toBe(1);
1322
-
1323
- const toolPart = assistantMessages[0].parts[0] as Record<string, unknown>;
1324
- expect(toolPart.state).toBe("approval-requested");
1325
- expect(toolPart.approval).toEqual({ id: "approval-persist-test" });
1326
-
1327
- // Now simulate a client reconnecting and approving the tool.
1328
- // A new client would receive these persisted messages and see the approval UI.
1329
- // When they approve, CF_AGENT_TOOL_APPROVAL is sent.
1330
- ws.send(
1331
- JSON.stringify({
1332
- type: "cf_agent_tool_approval",
1333
- toolCallId,
1334
- approved: true
1335
- })
1336
- );
1337
-
1338
- await new Promise((resolve) => setTimeout(resolve, 200));
1339
-
1340
- const updatedMessages =
1341
- (await agentStub.getPersistedMessages()) as ChatMessage[];
1342
- const updatedAssistant = updatedMessages.filter(
1343
- (m) => m.role === "assistant"
1344
- );
1345
- expect(updatedAssistant.length).toBe(1);
1346
-
1347
- const updatedToolPart = updatedAssistant[0].parts[0] as Record<
1348
- string,
1349
- unknown
1350
- >;
1351
- expect(updatedToolPart.state).toBe("approval-responded");
1352
- // approval.id preserved from the approval-requested state
1353
- expect(updatedToolPart.approval).toEqual({
1354
- id: "approval-persist-test",
1355
- approved: true
1356
- });
1357
-
1358
- ws.close(1000);
1359
- });
1360
- });
1361
-
1362
- describe("Tool approval denial produces tool_result via convertToModelMessages", () => {
1363
- it("rejected approval yields tool-result in model messages (required by Anthropic)", async () => {
1364
- const room = crypto.randomUUID();
1365
- const ctx = createExecutionContext();
1366
- const req = new Request(
1367
- `http://example.com/agents/test-chat-agent/${room}`,
1368
- { headers: { Upgrade: "websocket" } }
1369
- );
1370
- const res = await worker.fetch(req, env, ctx);
1371
- expect(res.status).toBe(101);
1372
- const ws = res.webSocket as WebSocket;
1373
- ws.accept();
1374
- await ctx.waitUntil(Promise.resolve());
1375
-
1376
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1377
- const toolCallId = "call_e2e_denied";
1378
-
1379
- await agentStub.persistMessages([
1380
- {
1381
- id: "user-1",
1382
- role: "user",
1383
- parts: [{ type: "text", text: "Run the tool" }]
1384
- },
1385
- {
1386
- id: "assistant-1",
1387
- role: "assistant",
1388
- parts: [
1389
- {
1390
- type: "tool-testTool",
1391
- toolCallId,
1392
- state: "approval-requested",
1393
- input: { param: "value" },
1394
- approval: { id: "approval-e2e" }
1395
- }
1396
- ] as ChatMessage["parts"]
1397
- }
1398
- ]);
1399
-
1400
- ws.send(
1401
- JSON.stringify({
1402
- type: "cf_agent_tool_approval",
1403
- toolCallId,
1404
- approved: false
1405
- })
1406
- );
1407
-
1408
- await new Promise((resolve) => setTimeout(resolve, 200));
1409
-
1410
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1411
- const modelMessages = await convertToModelMessages(messages);
1412
-
1413
- const toolMessage = modelMessages.find((m) => m.role === "tool");
1414
- expect(toolMessage).toBeDefined();
1415
-
1416
- const toolContent = toolMessage!.content as Array<{
1417
- type: string;
1418
- [key: string]: unknown;
1419
- }>;
1420
-
1421
- const approvalResponse = toolContent.find(
1422
- (c) => c.type === "tool-approval-response"
1423
- );
1424
- expect(approvalResponse).toBeDefined();
1425
- expect(approvalResponse!.approved).toBe(false);
1426
-
1427
- const toolResult = toolContent.find((c) => c.type === "tool-result");
1428
- expect(toolResult).toBeDefined();
1429
- expect(toolResult!.toolCallId).toBe(toolCallId);
1430
- expect(toolResult!.toolName).toBe("testTool");
1431
-
1432
- ws.close(1000);
1433
- });
1434
- });
1435
-
1436
- describe("CF_AGENT_TOOL_RESULT with approval states and output-error", () => {
1437
- it("applies tool result to a tool in approval-requested state", async () => {
1438
- const room = crypto.randomUUID();
1439
- const ctx = createExecutionContext();
1440
- const req = new Request(
1441
- `http://example.com/agents/test-chat-agent/${room}`,
1442
- { headers: { Upgrade: "websocket" } }
1443
- );
1444
- const res = await worker.fetch(req, env, ctx);
1445
- expect(res.status).toBe(101);
1446
- const ws = res.webSocket as WebSocket;
1447
- ws.accept();
1448
- await ctx.waitUntil(Promise.resolve());
1449
-
1450
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1451
- const toolCallId = "call_approval_tool_result";
1452
-
1453
- await agentStub.persistMessages([
1454
- {
1455
- id: "user-1",
1456
- role: "user",
1457
- parts: [{ type: "text", text: "Execute tool" }]
1458
- },
1459
- {
1460
- id: "assistant-1",
1461
- role: "assistant",
1462
- parts: [
1463
- {
1464
- type: "tool-testTool",
1465
- toolCallId,
1466
- state: "approval-requested",
1467
- input: { param: "value" },
1468
- approval: { id: "approval-tr-1" }
1469
- }
1470
- ] as ChatMessage["parts"]
1471
- }
1472
- ]);
1473
-
1474
- ws.send(
1475
- JSON.stringify({
1476
- type: "cf_agent_tool_result",
1477
- toolCallId,
1478
- toolName: "testTool",
1479
- output: { result: "done" }
1480
- })
1481
- );
1482
-
1483
- await new Promise((resolve) => setTimeout(resolve, 200));
1484
-
1485
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1486
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1487
-
1488
- expect(assistantMessages.length).toBe(1);
1489
-
1490
- const toolPart = assistantMessages[0].parts[0] as {
1491
- state: string;
1492
- output?: unknown;
1493
- };
1494
- expect(toolPart.state).toBe("output-available");
1495
- expect(toolPart.output).toEqual({ result: "done" });
1496
-
1497
- ws.close(1000);
1498
- });
1499
-
1500
- it("sets output-error state with errorText via CF_AGENT_TOOL_RESULT", async () => {
1501
- const room = crypto.randomUUID();
1502
- const ctx = createExecutionContext();
1503
- const req = new Request(
1504
- `http://example.com/agents/test-chat-agent/${room}`,
1505
- { headers: { Upgrade: "websocket" } }
1506
- );
1507
- const res = await worker.fetch(req, env, ctx);
1508
- expect(res.status).toBe(101);
1509
- const ws = res.webSocket as WebSocket;
1510
- ws.accept();
1511
- await ctx.waitUntil(Promise.resolve());
1512
-
1513
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1514
- const toolCallId = "call_output_error";
1515
-
1516
- await agentStub.persistMessages([
1517
- {
1518
- id: "user-1",
1519
- role: "user",
1520
- parts: [{ type: "text", text: "Execute tool" }]
1521
- },
1522
- {
1523
- id: "assistant-1",
1524
- role: "assistant",
1525
- parts: [
1526
- {
1527
- type: "tool-testTool",
1528
- toolCallId,
1529
- state: "approval-requested",
1530
- input: { param: "value" },
1531
- approval: { id: "approval-err-1" }
1532
- }
1533
- ] as ChatMessage["parts"]
1534
- }
1535
- ]);
1536
-
1537
- ws.send(
1538
- JSON.stringify({
1539
- type: "cf_agent_tool_result",
1540
- toolCallId,
1541
- toolName: "testTool",
1542
- output: null,
1543
- state: "output-error",
1544
- errorText: "User declined: not authorized"
1545
- })
1546
- );
1547
-
1548
- await new Promise((resolve) => setTimeout(resolve, 200));
1549
-
1550
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1551
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1552
-
1553
- expect(assistantMessages.length).toBe(1);
1554
-
1555
- const toolPart = assistantMessages[0].parts[0] as {
1556
- state: string;
1557
- errorText?: string;
1558
- };
1559
- expect(toolPart.state).toBe("output-error");
1560
- expect(toolPart.errorText).toBe("User declined: not authorized");
1561
-
1562
- ws.close(1000);
1563
- });
1564
-
1565
- it("output-error produces tool_result with custom errorText in model messages", async () => {
1566
- const room = crypto.randomUUID();
1567
- const ctx = createExecutionContext();
1568
- const req = new Request(
1569
- `http://example.com/agents/test-chat-agent/${room}`,
1570
- { headers: { Upgrade: "websocket" } }
1571
- );
1572
- const res = await worker.fetch(req, env, ctx);
1573
- expect(res.status).toBe(101);
1574
- const ws = res.webSocket as WebSocket;
1575
- ws.accept();
1576
- await ctx.waitUntil(Promise.resolve());
1577
-
1578
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1579
- const toolCallId = "call_e2e_error";
1580
-
1581
- await agentStub.persistMessages([
1582
- {
1583
- id: "user-1",
1584
- role: "user",
1585
- parts: [{ type: "text", text: "Run the tool" }]
1586
- },
1587
- {
1588
- id: "assistant-1",
1589
- role: "assistant",
1590
- parts: [
1591
- {
1592
- type: "tool-testTool",
1593
- toolCallId,
1594
- state: "input-available",
1595
- input: { param: "value" }
1596
- }
1597
- ] as ChatMessage["parts"]
1598
- }
1599
- ]);
1600
-
1601
- ws.send(
1602
- JSON.stringify({
1603
- type: "cf_agent_tool_result",
1604
- toolCallId,
1605
- toolName: "testTool",
1606
- output: null,
1607
- state: "output-error",
1608
- errorText: "Denied: insufficient permissions"
1609
- })
1610
- );
1611
-
1612
- await new Promise((resolve) => setTimeout(resolve, 200));
1613
-
1614
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1615
- const modelMessages = await convertToModelMessages(messages);
1616
-
1617
- const toolMessage = modelMessages.find((m) => m.role === "tool");
1618
- expect(toolMessage).toBeDefined();
1619
-
1620
- const toolContent = toolMessage!.content as Array<{
1621
- type: string;
1622
- [key: string]: unknown;
1623
- }>;
1624
-
1625
- const toolResult = toolContent.find((c) => c.type === "tool-result");
1626
- expect(toolResult).toBeDefined();
1627
- expect(toolResult!.toolCallId).toBe(toolCallId);
1628
-
1629
- const output = toolResult!.output as { type: string; value: string };
1630
- expect(output.type).toBe("error-text");
1631
- expect(output.value).toBe("Denied: insufficient permissions");
1632
-
1633
- ws.close(1000);
1634
- });
1635
-
1636
- it("CF_AGENT_TOOL_RESULT does not update tool already in output-denied state", async () => {
1637
- const room = crypto.randomUUID();
1638
- const ctx = createExecutionContext();
1639
- const req = new Request(
1640
- `http://example.com/agents/test-chat-agent/${room}`,
1641
- { headers: { Upgrade: "websocket" } }
1642
- );
1643
- const res = await worker.fetch(req, env, ctx);
1644
- expect(res.status).toBe(101);
1645
- const ws = res.webSocket as WebSocket;
1646
- ws.accept();
1647
- await ctx.waitUntil(Promise.resolve());
1648
-
1649
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1650
- const toolCallId = "call_already_denied";
1651
-
1652
- await agentStub.persistMessages([
1653
- {
1654
- id: "user-1",
1655
- role: "user",
1656
- parts: [{ type: "text", text: "Execute tool" }]
1657
- },
1658
- {
1659
- id: "assistant-1",
1660
- role: "assistant",
1661
- parts: [
1662
- {
1663
- type: "tool-testTool",
1664
- toolCallId,
1665
- state: "output-denied",
1666
- input: { param: "value" },
1667
- approval: { id: "approval-denied-guard", approved: false }
1668
- }
1669
- ] as ChatMessage["parts"]
1670
- }
1671
- ]);
1672
-
1673
- ws.send(
1674
- JSON.stringify({
1675
- type: "cf_agent_tool_result",
1676
- toolCallId,
1677
- toolName: "testTool",
1678
- output: { result: "override attempt" }
1679
- })
1680
- );
1681
-
1682
- await new Promise((resolve) => setTimeout(resolve, 200));
1683
-
1684
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1685
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1686
-
1687
- expect(assistantMessages.length).toBe(1);
1688
-
1689
- const toolPart = assistantMessages[0].parts[0] as {
1690
- state: string;
1691
- };
1692
- expect(toolPart.state).toBe("output-denied");
1693
-
1694
- ws.close(1000);
1695
- });
1696
-
1697
- it("CF_AGENT_TOOL_RESULT does not update tool already in output-available state", async () => {
1698
- const room = crypto.randomUUID();
1699
- const ctx = createExecutionContext();
1700
- const req = new Request(
1701
- `http://example.com/agents/test-chat-agent/${room}`,
1702
- { headers: { Upgrade: "websocket" } }
1703
- );
1704
- const res = await worker.fetch(req, env, ctx);
1705
- expect(res.status).toBe(101);
1706
- const ws = res.webSocket as WebSocket;
1707
- ws.accept();
1708
- await ctx.waitUntil(Promise.resolve());
1709
-
1710
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1711
- const toolCallId = "call_already_completed_tr";
1712
-
1713
- await agentStub.persistMessages([
1714
- {
1715
- id: "user-1",
1716
- role: "user",
1717
- parts: [{ type: "text", text: "Execute tool" }]
1718
- },
1719
- {
1720
- id: "assistant-1",
1721
- role: "assistant",
1722
- parts: [
1723
- {
1724
- type: "tool-testTool",
1725
- toolCallId,
1726
- state: "output-available",
1727
- input: { param: "value" },
1728
- output: { result: "original" }
1729
- }
1730
- ] as ChatMessage["parts"]
1731
- }
1732
- ]);
1733
-
1734
- ws.send(
1735
- JSON.stringify({
1736
- type: "cf_agent_tool_result",
1737
- toolCallId,
1738
- toolName: "testTool",
1739
- output: { result: "override attempt" }
1740
- })
1741
- );
1742
-
1743
- await new Promise((resolve) => setTimeout(resolve, 200));
1744
-
1745
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1746
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1747
-
1748
- expect(assistantMessages.length).toBe(1);
1749
-
1750
- const toolPart = assistantMessages[0].parts[0] as {
1751
- state: string;
1752
- output?: unknown;
1753
- };
1754
- expect(toolPart.state).toBe("output-available");
1755
- expect(toolPart.output).toEqual({ result: "original" });
1756
-
1757
- ws.close(1000);
1758
- });
1759
-
1760
- it("applies tool result to a tool in approval-responded state", async () => {
1761
- const room = crypto.randomUUID();
1762
- const ctx = createExecutionContext();
1763
- const req = new Request(
1764
- `http://example.com/agents/test-chat-agent/${room}`,
1765
- { headers: { Upgrade: "websocket" } }
1766
- );
1767
- const res = await worker.fetch(req, env, ctx);
1768
- expect(res.status).toBe(101);
1769
- const ws = res.webSocket as WebSocket;
1770
- ws.accept();
1771
- await ctx.waitUntil(Promise.resolve());
1772
-
1773
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1774
- const toolCallId = "call_responded_tool_result";
1775
-
1776
- await agentStub.persistMessages([
1777
- {
1778
- id: "user-1",
1779
- role: "user",
1780
- parts: [{ type: "text", text: "Execute tool" }]
1781
- },
1782
- {
1783
- id: "assistant-1",
1784
- role: "assistant",
1785
- parts: [
1786
- {
1787
- type: "tool-testTool",
1788
- toolCallId,
1789
- state: "approval-responded",
1790
- input: { param: "value" },
1791
- approval: { id: "approval-resp-1", approved: true }
1792
- }
1793
- ] as ChatMessage["parts"]
1794
- }
1795
- ]);
1796
-
1797
- ws.send(
1798
- JSON.stringify({
1799
- type: "cf_agent_tool_result",
1800
- toolCallId,
1801
- toolName: "testTool",
1802
- output: { result: "custom result" }
1803
- })
1804
- );
1805
-
1806
- await new Promise((resolve) => setTimeout(resolve, 200));
1807
-
1808
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1809
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1810
-
1811
- expect(assistantMessages.length).toBe(1);
1812
-
1813
- const toolPart = assistantMessages[0].parts[0] as {
1814
- state: string;
1815
- output?: unknown;
1816
- };
1817
- expect(toolPart.state).toBe("output-available");
1818
- expect(toolPart.output).toEqual({ result: "custom result" });
1819
-
1820
- ws.close(1000);
1821
- });
1822
-
1823
- it("output-error without errorText uses default message", async () => {
1824
- const room = crypto.randomUUID();
1825
- const ctx = createExecutionContext();
1826
- const req = new Request(
1827
- `http://example.com/agents/test-chat-agent/${room}`,
1828
- { headers: { Upgrade: "websocket" } }
1829
- );
1830
- const res = await worker.fetch(req, env, ctx);
1831
- expect(res.status).toBe(101);
1832
- const ws = res.webSocket as WebSocket;
1833
- ws.accept();
1834
- await ctx.waitUntil(Promise.resolve());
1835
-
1836
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1837
- const toolCallId = "call_default_error";
1838
-
1839
- await agentStub.persistMessages([
1840
- {
1841
- id: "user-1",
1842
- role: "user",
1843
- parts: [{ type: "text", text: "Execute tool" }]
1844
- },
1845
- {
1846
- id: "assistant-1",
1847
- role: "assistant",
1848
- parts: [
1849
- {
1850
- type: "tool-testTool",
1851
- toolCallId,
1852
- state: "input-available",
1853
- input: { param: "value" }
1854
- }
1855
- ] as ChatMessage["parts"]
1856
- }
1857
- ]);
1858
-
1859
- ws.send(
1860
- JSON.stringify({
1861
- type: "cf_agent_tool_result",
1862
- toolCallId,
1863
- toolName: "testTool",
1864
- output: null,
1865
- state: "output-error"
1866
- })
1867
- );
1868
-
1869
- await new Promise((resolve) => setTimeout(resolve, 200));
1870
-
1871
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1872
- const assistantMessages = messages.filter((m) => m.role === "assistant");
1873
-
1874
- expect(assistantMessages.length).toBe(1);
1875
-
1876
- const toolPart = assistantMessages[0].parts[0] as {
1877
- state: string;
1878
- errorText?: string;
1879
- };
1880
- expect(toolPart.state).toBe("output-error");
1881
- expect(toolPart.errorText).toBe("Tool execution denied by user");
1882
-
1883
- ws.close(1000);
1884
- });
1885
-
1886
- it("output-error on approval-responded produces tool_result via convertToModelMessages", async () => {
1887
- const room = crypto.randomUUID();
1888
- const ctx = createExecutionContext();
1889
- const req = new Request(
1890
- `http://example.com/agents/test-chat-agent/${room}`,
1891
- { headers: { Upgrade: "websocket" } }
1892
- );
1893
- const res = await worker.fetch(req, env, ctx);
1894
- expect(res.status).toBe(101);
1895
- const ws = res.webSocket as WebSocket;
1896
- ws.accept();
1897
- await ctx.waitUntil(Promise.resolve());
1898
-
1899
- const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1900
- const toolCallId = "call_e2e_responded_error";
1901
-
1902
- await agentStub.persistMessages([
1903
- {
1904
- id: "user-1",
1905
- role: "user",
1906
- parts: [{ type: "text", text: "Run the tool" }]
1907
- },
1908
- {
1909
- id: "assistant-1",
1910
- role: "assistant",
1911
- parts: [
1912
- {
1913
- type: "tool-testTool",
1914
- toolCallId,
1915
- state: "approval-responded",
1916
- input: { param: "value" },
1917
- approval: { id: "approval-e2e-2", approved: true }
1918
- }
1919
- ] as ChatMessage["parts"]
1920
- }
1921
- ]);
1922
-
1923
- ws.send(
1924
- JSON.stringify({
1925
- type: "cf_agent_tool_result",
1926
- toolCallId,
1927
- toolName: "testTool",
1928
- output: null,
1929
- state: "output-error",
1930
- errorText: "Execution failed: timeout"
1931
- })
1932
- );
1933
-
1934
- await new Promise((resolve) => setTimeout(resolve, 200));
1935
-
1936
- const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1937
- const modelMessages = await convertToModelMessages(messages);
1938
-
1939
- const toolMessage = modelMessages.find((m) => m.role === "tool");
1940
- expect(toolMessage).toBeDefined();
1941
-
1942
- const toolContent = toolMessage!.content as Array<{
1943
- type: string;
1944
- [key: string]: unknown;
1945
- }>;
1946
-
1947
- const toolResult = toolContent.find((c) => c.type === "tool-result");
1948
- expect(toolResult).toBeDefined();
1949
- expect(toolResult!.toolCallId).toBe(toolCallId);
1950
-
1951
- const output = toolResult!.output as { type: string; value: string };
1952
- expect(output.type).toBe("error-text");
1953
- expect(output.value).toBe("Execution failed: timeout");
1954
-
1955
- ws.close(1000);
1956
- });
1957
- });