@cloudflare/ai-chat 0.1.5 → 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 (67) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +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 +96 -10
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -251
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/tests/ws-transport-abort.test.ts +0 -198
  64. package/src/types.ts +0 -152
  65. package/src/ws-chat-transport.ts +0 -227
  66. package/tsconfig.json +0 -4
  67. package/vitest.config.ts +0 -7
@@ -1,374 +0,0 @@
1
- import { env } from "cloudflare:test";
2
- import { describe, it, expect } from "vitest";
3
- import type { UIMessage as ChatMessage } from "ai";
4
- import { connectChatWS } from "./test-utils";
5
- import { getAgentByName } from "agents";
6
- import { MessageType } from "../types";
7
-
8
- describe("Row Size Guard and Incremental Persistence", () => {
9
- describe("Incremental persistence", () => {
10
- it("persists new messages and skips unchanged ones on second call", async () => {
11
- const room = crypto.randomUUID();
12
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
13
- await new Promise((r) => setTimeout(r, 50));
14
-
15
- const agentStub = await getAgentByName(env.TestChatAgent, room);
16
-
17
- // Persist two messages
18
- const messages: ChatMessage[] = [
19
- {
20
- id: "inc-1",
21
- role: "user",
22
- parts: [{ type: "text", text: "Hello" }]
23
- },
24
- {
25
- id: "inc-2",
26
- role: "assistant",
27
- parts: [{ type: "text", text: "Hi there!" }]
28
- }
29
- ];
30
-
31
- await agentStub.persistMessages(messages);
32
-
33
- let persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
34
- expect(persisted.length).toBe(2);
35
-
36
- // Persist the same messages again -- should be a no-op in SQL
37
- // (we can't directly observe SQL write count, but we can verify
38
- // the messages are still correct)
39
- await agentStub.persistMessages(messages);
40
-
41
- persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
42
- expect(persisted.length).toBe(2);
43
- expect(persisted[0].id).toBe("inc-1");
44
- expect(persisted[1].id).toBe("inc-2");
45
-
46
- ws.close(1000);
47
- });
48
-
49
- it("persists modified messages when content changes", async () => {
50
- const room = crypto.randomUUID();
51
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
52
- await new Promise((r) => setTimeout(r, 50));
53
-
54
- const agentStub = await getAgentByName(env.TestChatAgent, room);
55
-
56
- // Persist initial message
57
- await agentStub.persistMessages([
58
- {
59
- id: "mod-1",
60
- role: "assistant",
61
- parts: [{ type: "text", text: "Original" }]
62
- }
63
- ]);
64
-
65
- // Modify the message
66
- await agentStub.persistMessages([
67
- {
68
- id: "mod-1",
69
- role: "assistant",
70
- parts: [{ type: "text", text: "Updated content" }]
71
- }
72
- ]);
73
-
74
- const persisted =
75
- (await agentStub.getPersistedMessages()) as ChatMessage[];
76
- expect(persisted.length).toBe(1);
77
- const textPart = persisted[0].parts[0] as { text: string };
78
- expect(textPart.text).toBe("Updated content");
79
-
80
- ws.close(1000);
81
- });
82
-
83
- it("cache is cleared on chat clear", async () => {
84
- const room = crypto.randomUUID();
85
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
86
- await new Promise((r) => setTimeout(r, 50));
87
-
88
- const agentStub = await getAgentByName(env.TestChatAgent, room);
89
-
90
- // Persist a message
91
- await agentStub.persistMessages([
92
- {
93
- id: "clear-cache-1",
94
- role: "user",
95
- parts: [{ type: "text", text: "Hello" }]
96
- }
97
- ]);
98
-
99
- // Clear via WebSocket
100
- ws.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
101
- await new Promise((r) => setTimeout(r, 100));
102
-
103
- // Verify cleared
104
- const persisted =
105
- (await agentStub.getPersistedMessages()) as ChatMessage[];
106
- expect(persisted.length).toBe(0);
107
-
108
- // Persist a new message with the same ID -- should succeed
109
- // (cache was cleared, so it won't skip)
110
- await agentStub.persistMessages([
111
- {
112
- id: "clear-cache-1",
113
- role: "user",
114
- parts: [{ type: "text", text: "New message same ID" }]
115
- }
116
- ]);
117
-
118
- const afterPersist =
119
- (await agentStub.getPersistedMessages()) as ChatMessage[];
120
- expect(afterPersist.length).toBe(1);
121
- expect((afterPersist[0].parts[0] as { text: string }).text).toBe(
122
- "New message same ID"
123
- );
124
-
125
- ws.close(1000);
126
- });
127
- });
128
-
129
- describe("Row size enforcement", () => {
130
- it("messages under 1.8MB pass through unchanged", async () => {
131
- const room = crypto.randomUUID();
132
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
133
- await new Promise((r) => setTimeout(r, 50));
134
-
135
- const agentStub = await getAgentByName(env.TestChatAgent, room);
136
-
137
- // Create a message with a moderately large tool output (50KB)
138
- const toolOutput = "A".repeat(50_000);
139
- const message: ChatMessage = {
140
- id: "size-ok",
141
- role: "assistant",
142
- parts: [
143
- {
144
- type: "tool-bigTool",
145
- toolCallId: "call_ok",
146
- state: "output-available",
147
- input: {},
148
- output: toolOutput
149
- }
150
- ] as ChatMessage["parts"]
151
- };
152
-
153
- await agentStub.persistMessages([message]);
154
-
155
- const persisted =
156
- (await agentStub.getPersistedMessages()) as ChatMessage[];
157
- expect(persisted.length).toBe(1);
158
-
159
- // Output should be preserved at full fidelity (under 1.8MB)
160
- const part = persisted[0].parts[0] as { output: unknown };
161
- expect(part.output).toBe(toolOutput);
162
-
163
- ws.close(1000);
164
- });
165
-
166
- it("messages over 1.8MB have tool outputs compacted", async () => {
167
- const room = crypto.randomUUID();
168
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
169
- await new Promise((r) => setTimeout(r, 50));
170
-
171
- const agentStub = await getAgentByName(env.TestChatAgent, room);
172
-
173
- // Create a message with a huge tool output that pushes over 1.8MB
174
- const hugeOutput = "X".repeat(1_900_000);
175
- const message: ChatMessage = {
176
- id: "size-big",
177
- role: "assistant",
178
- parts: [
179
- {
180
- type: "tool-hugeTool",
181
- toolCallId: "call_huge",
182
- state: "output-available",
183
- input: { query: "big data" },
184
- output: hugeOutput
185
- }
186
- ] as ChatMessage["parts"]
187
- };
188
-
189
- // Should NOT throw -- the guard compacts the output
190
- await agentStub.persistMessages([message]);
191
-
192
- const persisted =
193
- (await agentStub.getPersistedMessages()) as ChatMessage[];
194
- expect(persisted.length).toBe(1);
195
-
196
- // Output should be compacted (not the original huge string)
197
- const part = persisted[0].parts[0] as { output: unknown };
198
- const outputStr = part.output as string;
199
- expect(outputStr).toContain("too large to persist");
200
- expect(outputStr).toContain("bytes");
201
- expect(outputStr.length).toBeLessThan(hugeOutput.length);
202
-
203
- ws.close(1000);
204
- });
205
-
206
- it("compacted messages have metadata with compactedToolOutputs", async () => {
207
- const room = crypto.randomUUID();
208
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
209
- await new Promise((r) => setTimeout(r, 50));
210
-
211
- const agentStub = await getAgentByName(env.TestChatAgent, room);
212
-
213
- const message: ChatMessage = {
214
- id: "meta-compact",
215
- role: "assistant",
216
- parts: [
217
- {
218
- type: "tool-bigTool",
219
- toolCallId: "call_meta",
220
- state: "output-available",
221
- input: {},
222
- output: "Y".repeat(1_900_000)
223
- }
224
- ] as ChatMessage["parts"]
225
- };
226
-
227
- await agentStub.persistMessages([message]);
228
-
229
- const persisted =
230
- (await agentStub.getPersistedMessages()) as ChatMessage[];
231
- const metadata = persisted[0].metadata as Record<string, unknown>;
232
- expect(metadata).toBeDefined();
233
- expect(metadata.compactedToolOutputs).toEqual(["call_meta"]);
234
-
235
- ws.close(1000);
236
- });
237
-
238
- it("non-assistant messages pass through even if large", async () => {
239
- const room = crypto.randomUUID();
240
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
241
- await new Promise((r) => setTimeout(r, 50));
242
-
243
- const agentStub = await getAgentByName(env.TestChatAgent, room);
244
-
245
- // A large user message (no tool outputs to compact)
246
- // This tests the text truncation fallback for non-assistant messages
247
- const largeText = "Z".repeat(1_900_000);
248
- const message: ChatMessage = {
249
- id: "user-big",
250
- role: "user",
251
- parts: [{ type: "text", text: largeText }]
252
- };
253
-
254
- // Should not crash
255
- await agentStub.persistMessages([message]);
256
-
257
- const persisted =
258
- (await agentStub.getPersistedMessages()) as ChatMessage[];
259
- expect(persisted.length).toBe(1);
260
-
261
- // Text should be truncated
262
- const textPart = persisted[0].parts[0] as { text: string };
263
- expect(textPart.text).toContain("truncated for storage");
264
- expect(textPart.text.length).toBeLessThan(largeText.length);
265
-
266
- ws.close(1000);
267
- });
268
- });
269
-
270
- describe("Unicode byte-length measurement", () => {
271
- it("compacts messages with multi-byte Unicode that exceed byte limit", async () => {
272
- const room = crypto.randomUUID();
273
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
274
- await new Promise((r) => setTimeout(r, 50));
275
-
276
- const agentStub = await getAgentByName(env.TestChatAgent, room);
277
-
278
- // CJK character \u4e00 is 1 JS char but 3 bytes in UTF-8.
279
- // 700,000 CJK chars = 700,000 JS chars (under 1.8M char limit)
280
- // but 2,100,000 UTF-8 bytes (over 1.8MB byte limit).
281
- // This tests that the byte-length guard catches it.
282
- const cjkOutput = "\u4e00".repeat(700_000);
283
-
284
- const message: ChatMessage = {
285
- id: "unicode-test",
286
- role: "assistant",
287
- parts: [
288
- {
289
- type: "tool-cjkTool",
290
- toolCallId: "call_unicode",
291
- state: "output-available",
292
- input: {},
293
- output: cjkOutput
294
- }
295
- ] as ChatMessage["parts"]
296
- };
297
-
298
- await agentStub.persistMessages([message]);
299
-
300
- const persisted =
301
- (await agentStub.getPersistedMessages()) as ChatMessage[];
302
- expect(persisted.length).toBe(1);
303
-
304
- // The tool output should be compacted (byte size exceeds limit)
305
- const part = persisted[0].parts[0] as { output: unknown };
306
- expect(typeof part.output).toBe("string");
307
- expect((part.output as string).length).toBeLessThan(cjkOutput.length);
308
- expect(part.output as string).toContain("too large to persist");
309
-
310
- ws.close(1000);
311
- });
312
- });
313
-
314
- describe("Stream chunk size guard", () => {
315
- it("normal chunks are stored", async () => {
316
- const room = crypto.randomUUID();
317
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
318
- await new Promise((r) => setTimeout(r, 50));
319
-
320
- const agentStub = await getAgentByName(env.TestChatAgent, room);
321
-
322
- const streamId = await agentStub.testStartStream("req-chunk-ok");
323
- await agentStub.testStoreStreamChunk(
324
- streamId,
325
- '{"type":"text-delta","delta":"hello"}'
326
- );
327
- await agentStub.testFlushChunkBuffer();
328
-
329
- const chunks = await agentStub.getStreamChunks(streamId);
330
- expect(chunks.length).toBe(1);
331
-
332
- ws.close(1000);
333
- });
334
-
335
- it("oversized chunks are skipped without crash", async () => {
336
- const room = crypto.randomUUID();
337
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
338
- await new Promise((r) => setTimeout(r, 50));
339
-
340
- const agentStub = await getAgentByName(env.TestChatAgent, room);
341
-
342
- const streamId = await agentStub.testStartStream("req-chunk-big");
343
-
344
- // Store a normal chunk first
345
- await agentStub.testStoreStreamChunk(
346
- streamId,
347
- '{"type":"text-start","id":"t1"}'
348
- );
349
-
350
- // Store an oversized chunk (>1.8MB) -- should be skipped
351
- const hugeChunk =
352
- '{"type":"tool-output-available","output":"' +
353
- "X".repeat(1_900_000) +
354
- '"}';
355
- await agentStub.testStoreStreamChunk(streamId, hugeChunk);
356
-
357
- // Store another normal chunk after
358
- await agentStub.testStoreStreamChunk(
359
- streamId,
360
- '{"type":"text-end","id":"t1"}'
361
- );
362
-
363
- await agentStub.testFlushChunkBuffer();
364
-
365
- const chunks = await agentStub.getStreamChunks(streamId);
366
- // Should have 2 chunks (the oversized one was skipped)
367
- expect(chunks.length).toBe(2);
368
- expect(chunks[0].body).toContain("text-start");
369
- expect(chunks[1].body).toContain("text-end");
370
-
371
- ws.close(1000);
372
- });
373
- });
374
- });
@@ -1,325 +0,0 @@
1
- import { env } from "cloudflare:test";
2
- import { describe, it, expect } from "vitest";
3
- import type { UIMessage as ChatMessage } from "ai";
4
- import { connectChatWS } from "./test-utils";
5
- import { getAgentByName } from "agents";
6
-
7
- describe("Message Sanitization", () => {
8
- it("strips OpenAI itemId from persisted messages", async () => {
9
- const room = crypto.randomUUID();
10
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
11
- await new Promise((r) => setTimeout(r, 50));
12
-
13
- const agentStub = await getAgentByName(env.TestChatAgent, room);
14
-
15
- // Persist a message with OpenAI providerMetadata containing itemId
16
- const messageWithItemId: ChatMessage = {
17
- id: "msg-sanitize-1",
18
- role: "assistant",
19
- parts: [
20
- {
21
- type: "text",
22
- text: "Hello!",
23
- providerMetadata: {
24
- openai: {
25
- itemId: "item_abc123",
26
- someOtherField: "keep-me"
27
- }
28
- }
29
- }
30
- ]
31
- };
32
-
33
- await agentStub.persistMessages([messageWithItemId]);
34
-
35
- const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
36
- expect(persisted.length).toBe(1);
37
-
38
- const textPart = persisted[0].parts[0] as {
39
- type: string;
40
- text: string;
41
- providerMetadata?: Record<string, unknown>;
42
- };
43
-
44
- // itemId should be stripped
45
- expect(
46
- (textPart.providerMetadata?.openai as Record<string, unknown>)?.itemId
47
- ).toBeUndefined();
48
-
49
- // Other OpenAI fields should be preserved
50
- expect(
51
- (textPart.providerMetadata?.openai as Record<string, unknown>)
52
- ?.someOtherField
53
- ).toBe("keep-me");
54
-
55
- ws.close(1000);
56
- });
57
-
58
- it("strips reasoningEncryptedContent from persisted messages", async () => {
59
- const room = crypto.randomUUID();
60
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
61
- await new Promise((r) => setTimeout(r, 50));
62
-
63
- const agentStub = await getAgentByName(env.TestChatAgent, room);
64
-
65
- const messageWithEncrypted: ChatMessage = {
66
- id: "msg-sanitize-2",
67
- role: "assistant",
68
- parts: [
69
- {
70
- type: "text",
71
- text: "Thought about it",
72
- providerMetadata: {
73
- openai: {
74
- itemId: "item_xyz",
75
- reasoningEncryptedContent: "encrypted-blob"
76
- }
77
- }
78
- }
79
- ]
80
- };
81
-
82
- await agentStub.persistMessages([messageWithEncrypted]);
83
-
84
- const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
85
- const textPart = persisted[0].parts[0] as {
86
- type: string;
87
- providerMetadata?: Record<string, unknown>;
88
- };
89
-
90
- // Both itemId and reasoningEncryptedContent should be stripped
91
- // Since no other openai fields remain, the openai key itself should be gone
92
- expect(textPart.providerMetadata?.openai).toBeUndefined();
93
-
94
- ws.close(1000);
95
- });
96
-
97
- it("removes empty reasoning parts from persisted messages", async () => {
98
- const room = crypto.randomUUID();
99
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
100
- await new Promise((r) => setTimeout(r, 50));
101
-
102
- const agentStub = await getAgentByName(env.TestChatAgent, room);
103
-
104
- const messageWithEmptyReasoning: ChatMessage = {
105
- id: "msg-sanitize-3",
106
- role: "assistant",
107
- parts: [
108
- { type: "reasoning", text: "", state: "done" },
109
- { type: "reasoning", text: " ", state: "done" },
110
- { type: "text", text: "Hello!" },
111
- { type: "reasoning", text: "I thought about this", state: "done" }
112
- ] as ChatMessage["parts"]
113
- };
114
-
115
- await agentStub.persistMessages([messageWithEmptyReasoning]);
116
-
117
- const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
118
- expect(persisted.length).toBe(1);
119
-
120
- // Empty reasoning parts should be filtered out, but non-empty ones kept
121
- const reasoningParts = persisted[0].parts.filter(
122
- (p) => p.type === "reasoning"
123
- );
124
- expect(reasoningParts.length).toBe(1);
125
- expect((reasoningParts[0] as { text: string }).text).toBe(
126
- "I thought about this"
127
- );
128
-
129
- // Text part should be preserved
130
- const textParts = persisted[0].parts.filter((p) => p.type === "text");
131
- expect(textParts.length).toBe(1);
132
-
133
- ws.close(1000);
134
- });
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
-
246
- it("strips callProviderMetadata from tool parts", async () => {
247
- const room = crypto.randomUUID();
248
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
249
- await new Promise((r) => setTimeout(r, 50));
250
-
251
- const agentStub = await getAgentByName(env.TestChatAgent, room);
252
-
253
- const messageWithToolMeta: ChatMessage = {
254
- id: "msg-sanitize-4",
255
- role: "assistant",
256
- parts: [
257
- {
258
- type: "tool-getWeather",
259
- toolCallId: "call_meta1",
260
- state: "output-available",
261
- input: { city: "London" },
262
- output: "Sunny",
263
- callProviderMetadata: {
264
- openai: {
265
- itemId: "item_tool_123"
266
- }
267
- }
268
- }
269
- ] as ChatMessage["parts"]
270
- };
271
-
272
- await agentStub.persistMessages([messageWithToolMeta]);
273
-
274
- const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
275
- const toolPart = persisted[0].parts[0] as Record<string, unknown>;
276
-
277
- // callProviderMetadata with only itemId should be completely removed
278
- expect(toolPart.callProviderMetadata).toBeUndefined();
279
-
280
- // Tool data should be preserved
281
- expect(toolPart.state).toBe("output-available");
282
- expect(toolPart.output).toBe("Sunny");
283
-
284
- ws.close(1000);
285
- });
286
-
287
- it("preserves messages without OpenAI metadata unchanged", async () => {
288
- const room = crypto.randomUUID();
289
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
290
- await new Promise((r) => setTimeout(r, 50));
291
-
292
- const agentStub = await getAgentByName(env.TestChatAgent, room);
293
-
294
- const plainMessage: ChatMessage = {
295
- id: "msg-sanitize-5",
296
- role: "assistant",
297
- parts: [
298
- { type: "text", text: "Just a plain message" },
299
- {
300
- type: "text",
301
- text: "With non-OpenAI metadata",
302
- providerMetadata: {
303
- anthropic: { cacheControl: "ephemeral" }
304
- }
305
- }
306
- ] as ChatMessage["parts"]
307
- };
308
-
309
- await agentStub.persistMessages([plainMessage]);
310
-
311
- const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
312
- expect(persisted.length).toBe(1);
313
- expect(persisted[0].parts.length).toBe(2);
314
-
315
- // Non-OpenAI metadata should be preserved
316
- const metaPart = persisted[0].parts[1] as {
317
- providerMetadata?: Record<string, unknown>;
318
- };
319
- expect(metaPart.providerMetadata?.anthropic).toEqual({
320
- cacheControl: "ephemeral"
321
- });
322
-
323
- ws.close(1000);
324
- });
325
- });