@cloudflare/ai-chat 0.0.7 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -0
- package/README.md +225 -459
- package/dist/ai-chat-v5-migration.d.ts +9 -9
- package/dist/ai-chat-v5-migration.js +25 -4
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +29 -0
- package/dist/experimental/forever.js +55 -0
- package/dist/experimental/forever.js.map +1 -0
- package/dist/index.d.ts +126 -74
- package/dist/index.js +753 -632
- package/dist/index.js.map +1 -1
- package/dist/message-builder-Bwc_Umye.js +231 -0
- package/dist/message-builder-Bwc_Umye.js.map +1 -0
- package/dist/react.d.ts +27 -9
- package/dist/react.js +248 -259
- package/dist/react.js.map +1 -1
- package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
- package/dist/types.d.ts +16 -4
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/e2e/chat.spec.ts +1703 -0
- package/e2e/client-tools.spec.ts +504 -0
- package/e2e/llm.spec.ts +637 -0
- package/e2e/playwright.config.ts +24 -0
- package/e2e/worker.ts +176 -0
- package/e2e/wrangler.jsonc +23 -0
- package/package.json +12 -5
- package/scripts/build.ts +2 -1
- package/src/ai-chat-v5-migration.ts +32 -5
- package/src/experimental/forever.ts +66 -0
- package/src/index.ts +850 -1132
- package/src/message-builder.ts +384 -0
- package/src/react-tests/use-agent-chat.test.tsx +738 -2
- package/src/react.tsx +396 -462
- package/src/resumable-stream.ts +441 -0
- package/src/tests/chat-context.test.ts +1 -1
- package/src/tests/chat-persistence.test.ts +5 -5
- package/src/tests/clear-history.test.ts +132 -0
- package/src/tests/client-tool-duplicate-message.test.ts +457 -14
- package/src/tests/client-tools-broadcast.test.ts +2 -2
- package/src/tests/client-tools-continuation.test.ts +314 -0
- package/src/tests/client-tools-reconnect.test.ts +143 -0
- package/src/tests/custom-body-continuation.test.ts +309 -0
- package/src/tests/custom-body.test.ts +186 -0
- package/src/tests/destroy.test.ts +57 -0
- package/src/tests/get-messages-endpoint.test.ts +79 -0
- package/src/tests/max-persisted-messages.test.ts +201 -0
- package/src/tests/merge-server-state.test.ts +106 -0
- package/src/tests/message-builder.test.ts +808 -0
- package/src/tests/migration.test.ts +282 -0
- package/src/tests/non-sse-response.test.ts +2 -2
- package/src/tests/onfinish-cleanup.test.ts +362 -0
- package/src/tests/plaintext-response.test.ts +87 -0
- package/src/tests/resumable-streaming.test.ts +220 -14
- package/src/tests/row-size-guard.test.ts +374 -0
- package/src/tests/sanitize-messages.test.ts +215 -0
- package/src/tests/validate-messages.test.ts +269 -0
- package/src/tests/worker.ts +85 -23
- package/src/types.ts +17 -1
- package/src/ws-chat-transport.ts +203 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { createExecutionContext, env } from "cloudflare:test";
|
|
2
|
+
import { describe, it, expect } from "vitest";
|
|
3
|
+
import worker from "./worker";
|
|
4
|
+
import type { UIMessage as ChatMessage } from "ai";
|
|
5
|
+
import { getAgentByName } from "agents";
|
|
6
|
+
|
|
7
|
+
describe("Message Structural Validation", () => {
|
|
8
|
+
async function setupAgent(room: string) {
|
|
9
|
+
const ctx = createExecutionContext();
|
|
10
|
+
const req = new Request(
|
|
11
|
+
`http://example.com/agents/test-chat-agent/${room}`,
|
|
12
|
+
{ headers: { Upgrade: "websocket" } }
|
|
13
|
+
);
|
|
14
|
+
const res = await worker.fetch(req, env, ctx);
|
|
15
|
+
expect(res.status).toBe(101);
|
|
16
|
+
const ws = res.webSocket as WebSocket;
|
|
17
|
+
ws.accept();
|
|
18
|
+
await ctx.waitUntil(Promise.resolve());
|
|
19
|
+
|
|
20
|
+
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
21
|
+
return { ws, agentStub };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Fetch messages via the /get-messages HTTP endpoint, which goes through
|
|
26
|
+
* _loadMessagesFromDb() and applies structural validation.
|
|
27
|
+
*/
|
|
28
|
+
async function getValidatedMessages(room: string): Promise<ChatMessage[]> {
|
|
29
|
+
const getMessagesReq = new Request(
|
|
30
|
+
`http://example.com/agents/test-chat-agent/${room}/get-messages`
|
|
31
|
+
);
|
|
32
|
+
const getMessagesRes = await worker.fetch(
|
|
33
|
+
getMessagesReq,
|
|
34
|
+
env,
|
|
35
|
+
createExecutionContext()
|
|
36
|
+
);
|
|
37
|
+
expect(getMessagesRes.status).toBe(200);
|
|
38
|
+
return (await getMessagesRes.json()) as ChatMessage[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
it("loads valid messages without filtering", async () => {
|
|
42
|
+
const room = crypto.randomUUID();
|
|
43
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
44
|
+
|
|
45
|
+
const messages: ChatMessage[] = [
|
|
46
|
+
{ id: "msg1", role: "user", parts: [{ type: "text", text: "Hello" }] },
|
|
47
|
+
{
|
|
48
|
+
id: "msg2",
|
|
49
|
+
role: "assistant",
|
|
50
|
+
parts: [{ type: "text", text: "Hi!" }]
|
|
51
|
+
}
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
await agentStub.persistMessages(messages);
|
|
55
|
+
|
|
56
|
+
const persisted = await getValidatedMessages(room);
|
|
57
|
+
expect(persisted.length).toBe(2);
|
|
58
|
+
expect(persisted[0].id).toBe("msg1");
|
|
59
|
+
expect(persisted[1].id).toBe("msg2");
|
|
60
|
+
|
|
61
|
+
ws.close(1000);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("filters out messages with missing id", async () => {
|
|
65
|
+
const room = crypto.randomUUID();
|
|
66
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
67
|
+
|
|
68
|
+
await agentStub.persistMessages([
|
|
69
|
+
{ id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
// Manually insert a malformed message (no id field)
|
|
73
|
+
agentStub.insertRawMessage(
|
|
74
|
+
"bad-no-id",
|
|
75
|
+
JSON.stringify({
|
|
76
|
+
role: "user",
|
|
77
|
+
parts: [{ type: "text", text: "bad" }]
|
|
78
|
+
})
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
const persisted = await getValidatedMessages(room);
|
|
82
|
+
expect(persisted.length).toBe(1);
|
|
83
|
+
expect(persisted[0].id).toBe("valid1");
|
|
84
|
+
|
|
85
|
+
ws.close(1000);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("filters out messages with invalid role", async () => {
|
|
89
|
+
const room = crypto.randomUUID();
|
|
90
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
91
|
+
|
|
92
|
+
await agentStub.persistMessages([
|
|
93
|
+
{ id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
|
|
94
|
+
]);
|
|
95
|
+
|
|
96
|
+
agentStub.insertRawMessage(
|
|
97
|
+
"bad-role",
|
|
98
|
+
JSON.stringify({
|
|
99
|
+
id: "bad-role",
|
|
100
|
+
role: "invalid-role",
|
|
101
|
+
parts: [{ type: "text", text: "bad" }]
|
|
102
|
+
})
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
const persisted = await getValidatedMessages(room);
|
|
106
|
+
expect(persisted.length).toBe(1);
|
|
107
|
+
expect(persisted[0].id).toBe("valid1");
|
|
108
|
+
|
|
109
|
+
ws.close(1000);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("filters out messages with non-array parts", async () => {
|
|
113
|
+
const room = crypto.randomUUID();
|
|
114
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
115
|
+
|
|
116
|
+
await agentStub.persistMessages([
|
|
117
|
+
{ id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
|
|
118
|
+
]);
|
|
119
|
+
|
|
120
|
+
agentStub.insertRawMessage(
|
|
121
|
+
"bad-parts",
|
|
122
|
+
JSON.stringify({
|
|
123
|
+
id: "bad-parts",
|
|
124
|
+
role: "user",
|
|
125
|
+
parts: "not an array"
|
|
126
|
+
})
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
const persisted = await getValidatedMessages(room);
|
|
130
|
+
expect(persisted.length).toBe(1);
|
|
131
|
+
expect(persisted[0].id).toBe("valid1");
|
|
132
|
+
|
|
133
|
+
ws.close(1000);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("filters out messages with empty id", async () => {
|
|
137
|
+
const room = crypto.randomUUID();
|
|
138
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
139
|
+
|
|
140
|
+
await agentStub.persistMessages([
|
|
141
|
+
{ id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
|
|
142
|
+
]);
|
|
143
|
+
|
|
144
|
+
agentStub.insertRawMessage(
|
|
145
|
+
"bad-empty-id",
|
|
146
|
+
JSON.stringify({
|
|
147
|
+
id: "",
|
|
148
|
+
role: "user",
|
|
149
|
+
parts: [{ type: "text", text: "bad" }]
|
|
150
|
+
})
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
const persisted = await getValidatedMessages(room);
|
|
154
|
+
expect(persisted.length).toBe(1);
|
|
155
|
+
expect(persisted[0].id).toBe("valid1");
|
|
156
|
+
|
|
157
|
+
ws.close(1000);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it("keeps messages with empty parts array (lenient)", async () => {
|
|
161
|
+
const room = crypto.randomUUID();
|
|
162
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
163
|
+
|
|
164
|
+
await agentStub.persistMessages([
|
|
165
|
+
{ id: "empty-parts", role: "assistant", parts: [] }
|
|
166
|
+
]);
|
|
167
|
+
|
|
168
|
+
const persisted = await getValidatedMessages(room);
|
|
169
|
+
expect(persisted.length).toBe(1);
|
|
170
|
+
expect(persisted[0].id).toBe("empty-parts");
|
|
171
|
+
expect(persisted[0].parts).toEqual([]);
|
|
172
|
+
|
|
173
|
+
ws.close(1000);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("filters out non-object values stored as messages", async () => {
|
|
177
|
+
const room = crypto.randomUUID();
|
|
178
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
179
|
+
|
|
180
|
+
await agentStub.persistMessages([
|
|
181
|
+
{ id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
|
|
182
|
+
]);
|
|
183
|
+
|
|
184
|
+
// Raw string value (not a JSON object)
|
|
185
|
+
agentStub.insertRawMessage("bad-string", JSON.stringify("just a string"));
|
|
186
|
+
|
|
187
|
+
// null value
|
|
188
|
+
agentStub.insertRawMessage("bad-null", "null");
|
|
189
|
+
|
|
190
|
+
const persisted = await getValidatedMessages(room);
|
|
191
|
+
expect(persisted.length).toBe(1);
|
|
192
|
+
expect(persisted[0].id).toBe("valid1");
|
|
193
|
+
|
|
194
|
+
ws.close(1000);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("preserves messages with metadata", async () => {
|
|
198
|
+
const room = crypto.randomUUID();
|
|
199
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
200
|
+
|
|
201
|
+
const messageWithMeta: ChatMessage = {
|
|
202
|
+
id: "meta1",
|
|
203
|
+
role: "assistant",
|
|
204
|
+
parts: [{ type: "text", text: "Response" }],
|
|
205
|
+
metadata: { model: "gpt-4o", totalTokens: 150 }
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
await agentStub.persistMessages([messageWithMeta]);
|
|
209
|
+
|
|
210
|
+
const persisted = await getValidatedMessages(room);
|
|
211
|
+
expect(persisted.length).toBe(1);
|
|
212
|
+
expect(persisted[0].id).toBe("meta1");
|
|
213
|
+
expect(persisted[0].metadata).toEqual({
|
|
214
|
+
model: "gpt-4o",
|
|
215
|
+
totalTokens: 150
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
ws.close(1000);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("filters out completely unparseable JSON", async () => {
|
|
222
|
+
const room = crypto.randomUUID();
|
|
223
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
224
|
+
|
|
225
|
+
await agentStub.persistMessages([
|
|
226
|
+
{ id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
|
|
227
|
+
]);
|
|
228
|
+
|
|
229
|
+
// Insert raw broken JSON that will fail JSON.parse
|
|
230
|
+
agentStub.insertRawMessage("bad-json", "{broken json!!!");
|
|
231
|
+
|
|
232
|
+
const persisted = await getValidatedMessages(room);
|
|
233
|
+
expect(persisted.length).toBe(1);
|
|
234
|
+
expect(persisted[0].id).toBe("valid1");
|
|
235
|
+
|
|
236
|
+
ws.close(1000);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("accepts all valid roles: user, assistant, system", async () => {
|
|
240
|
+
const room = crypto.randomUUID();
|
|
241
|
+
const { ws, agentStub } = await setupAgent(room);
|
|
242
|
+
|
|
243
|
+
const messages: ChatMessage[] = [
|
|
244
|
+
{
|
|
245
|
+
id: "sys1",
|
|
246
|
+
role: "system",
|
|
247
|
+
parts: [{ type: "text", text: "You are helpful" }]
|
|
248
|
+
},
|
|
249
|
+
{ id: "usr1", role: "user", parts: [{ type: "text", text: "Hello" }] },
|
|
250
|
+
{
|
|
251
|
+
id: "ast1",
|
|
252
|
+
role: "assistant",
|
|
253
|
+
parts: [{ type: "text", text: "Hi!" }]
|
|
254
|
+
}
|
|
255
|
+
];
|
|
256
|
+
|
|
257
|
+
await agentStub.persistMessages(messages);
|
|
258
|
+
|
|
259
|
+
const persisted = await getValidatedMessages(room);
|
|
260
|
+
expect(persisted.length).toBe(3);
|
|
261
|
+
expect(persisted.map((m) => m.role)).toEqual([
|
|
262
|
+
"system",
|
|
263
|
+
"user",
|
|
264
|
+
"assistant"
|
|
265
|
+
]);
|
|
266
|
+
|
|
267
|
+
ws.close(1000);
|
|
268
|
+
});
|
|
269
|
+
});
|
package/src/tests/worker.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import { AIChatAgent } from "../";
|
|
2
|
-
import type {
|
|
3
|
-
|
|
1
|
+
import { AIChatAgent, type OnChatMessageOptions } from "../";
|
|
2
|
+
import type {
|
|
3
|
+
UIMessage as ChatMessage,
|
|
4
|
+
StreamTextOnFinishCallback,
|
|
5
|
+
ToolSet
|
|
6
|
+
} from "ai";
|
|
7
|
+
import { getCurrentAgent, routeAgentRequest } from "agents";
|
|
4
8
|
import { MessageType, type OutgoingMessage } from "../types";
|
|
9
|
+
import type { ClientToolSchema } from "../";
|
|
5
10
|
|
|
6
11
|
// Type helper for tool call parts - extracts from ChatMessage parts
|
|
7
12
|
type TestToolCallPart = Extract<
|
|
@@ -27,8 +32,19 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
27
32
|
hasConnection: boolean;
|
|
28
33
|
connectionId: string | undefined;
|
|
29
34
|
} | null = null;
|
|
35
|
+
// Store captured body from onChatMessage options for testing
|
|
36
|
+
private _capturedBody: Record<string, unknown> | undefined = undefined;
|
|
37
|
+
// Store captured clientTools from onChatMessage options for testing
|
|
38
|
+
private _capturedClientTools: ClientToolSchema[] | undefined = undefined;
|
|
39
|
+
|
|
40
|
+
async onChatMessage(
|
|
41
|
+
_onFinish: StreamTextOnFinishCallback<ToolSet>,
|
|
42
|
+
options?: OnChatMessageOptions
|
|
43
|
+
) {
|
|
44
|
+
// Capture the body and clientTools from options for testing
|
|
45
|
+
this._capturedBody = options?.body;
|
|
46
|
+
this._capturedClientTools = options?.clientTools;
|
|
30
47
|
|
|
31
|
-
async onChatMessage() {
|
|
32
48
|
// Capture getCurrentAgent() context for testing
|
|
33
49
|
const { agent, connection } = getCurrentAgent();
|
|
34
50
|
this._capturedContext = {
|
|
@@ -61,7 +77,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
61
77
|
};
|
|
62
78
|
}
|
|
63
79
|
|
|
64
|
-
@callable()
|
|
65
80
|
getCapturedContext(): {
|
|
66
81
|
hasAgent: boolean;
|
|
67
82
|
hasConnection: boolean;
|
|
@@ -70,7 +85,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
70
85
|
return this._capturedContext;
|
|
71
86
|
}
|
|
72
87
|
|
|
73
|
-
@callable()
|
|
74
88
|
getNestedContext(): {
|
|
75
89
|
hasAgent: boolean;
|
|
76
90
|
hasConnection: boolean;
|
|
@@ -79,13 +93,21 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
79
93
|
return this._nestedContext;
|
|
80
94
|
}
|
|
81
95
|
|
|
82
|
-
@callable()
|
|
83
96
|
clearCapturedContext(): void {
|
|
84
97
|
this._capturedContext = null;
|
|
85
98
|
this._nestedContext = null;
|
|
99
|
+
this._capturedBody = undefined;
|
|
100
|
+
this._capturedClientTools = undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
getCapturedBody(): Record<string, unknown> | undefined {
|
|
104
|
+
return this._capturedBody;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
getCapturedClientTools(): ClientToolSchema[] | undefined {
|
|
108
|
+
return this._capturedClientTools;
|
|
86
109
|
}
|
|
87
110
|
|
|
88
|
-
@callable()
|
|
89
111
|
getPersistedMessages(): ChatMessage[] {
|
|
90
112
|
const rawMessages = (
|
|
91
113
|
this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
|
|
@@ -96,7 +118,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
96
118
|
return rawMessages;
|
|
97
119
|
}
|
|
98
120
|
|
|
99
|
-
@callable()
|
|
100
121
|
async testPersistToolCall(messageId: string, toolName: string) {
|
|
101
122
|
const toolCallPart: TestToolCallPart = {
|
|
102
123
|
type: `tool-${toolName}`,
|
|
@@ -114,7 +135,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
114
135
|
return messageWithToolCall;
|
|
115
136
|
}
|
|
116
137
|
|
|
117
|
-
@callable()
|
|
118
138
|
async testPersistToolResult(
|
|
119
139
|
messageId: string,
|
|
120
140
|
toolName: string,
|
|
@@ -139,17 +159,14 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
139
159
|
|
|
140
160
|
// Resumable streaming test helpers
|
|
141
161
|
|
|
142
|
-
@callable()
|
|
143
162
|
testStartStream(requestId: string): string {
|
|
144
163
|
return this._startStream(requestId);
|
|
145
164
|
}
|
|
146
165
|
|
|
147
|
-
@callable()
|
|
148
166
|
testStoreStreamChunk(streamId: string, body: string): void {
|
|
149
167
|
this._storeStreamChunk(streamId, body);
|
|
150
168
|
}
|
|
151
169
|
|
|
152
|
-
@callable()
|
|
153
170
|
testBroadcastLiveChunk(
|
|
154
171
|
requestId: string,
|
|
155
172
|
streamId: string,
|
|
@@ -172,32 +189,26 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
172
189
|
)._broadcastChatMessage(message);
|
|
173
190
|
}
|
|
174
191
|
|
|
175
|
-
@callable()
|
|
176
192
|
testFlushChunkBuffer(): void {
|
|
177
193
|
this._flushChunkBuffer();
|
|
178
194
|
}
|
|
179
195
|
|
|
180
|
-
@callable()
|
|
181
196
|
testCompleteStream(streamId: string): void {
|
|
182
197
|
this._completeStream(streamId);
|
|
183
198
|
}
|
|
184
199
|
|
|
185
|
-
@callable()
|
|
186
200
|
testMarkStreamError(streamId: string): void {
|
|
187
201
|
this._markStreamError(streamId);
|
|
188
202
|
}
|
|
189
203
|
|
|
190
|
-
@callable()
|
|
191
204
|
getActiveStreamId(): string | null {
|
|
192
205
|
return this._activeStreamId;
|
|
193
206
|
}
|
|
194
207
|
|
|
195
|
-
@callable()
|
|
196
208
|
getActiveRequestId(): string | null {
|
|
197
209
|
return this._activeRequestId;
|
|
198
210
|
}
|
|
199
211
|
|
|
200
|
-
@callable()
|
|
201
212
|
getStreamChunks(
|
|
202
213
|
streamId: string
|
|
203
214
|
): Array<{ body: string; chunk_index: number }> {
|
|
@@ -210,7 +221,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
210
221
|
);
|
|
211
222
|
}
|
|
212
223
|
|
|
213
|
-
@callable()
|
|
214
224
|
getStreamMetadata(
|
|
215
225
|
streamId: string
|
|
216
226
|
): { status: string; request_id: string } | null {
|
|
@@ -221,7 +231,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
221
231
|
return result && result.length > 0 ? result[0] : null;
|
|
222
232
|
}
|
|
223
233
|
|
|
224
|
-
@callable()
|
|
225
234
|
getAllStreamMetadata(): Array<{
|
|
226
235
|
id: string;
|
|
227
236
|
status: string;
|
|
@@ -239,7 +248,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
239
248
|
);
|
|
240
249
|
}
|
|
241
250
|
|
|
242
|
-
@callable()
|
|
243
251
|
testInsertStaleStream(
|
|
244
252
|
streamId: string,
|
|
245
253
|
requestId: string,
|
|
@@ -252,10 +260,64 @@ export class TestChatAgent extends AIChatAgent<Env> {
|
|
|
252
260
|
`;
|
|
253
261
|
}
|
|
254
262
|
|
|
255
|
-
|
|
263
|
+
testInsertOldErroredStream(
|
|
264
|
+
streamId: string,
|
|
265
|
+
requestId: string,
|
|
266
|
+
ageMs: number
|
|
267
|
+
): void {
|
|
268
|
+
const createdAt = Date.now() - ageMs;
|
|
269
|
+
const completedAt = createdAt + 1000;
|
|
270
|
+
this.sql`
|
|
271
|
+
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at, completed_at)
|
|
272
|
+
values (${streamId}, ${requestId}, 'error', ${createdAt}, ${completedAt})
|
|
273
|
+
`;
|
|
274
|
+
}
|
|
275
|
+
|
|
256
276
|
testRestoreActiveStream(): void {
|
|
257
277
|
this._restoreActiveStream();
|
|
258
278
|
}
|
|
279
|
+
|
|
280
|
+
testTriggerStreamCleanup(): void {
|
|
281
|
+
// Force the cleanup interval to 0 so the next completeStream triggers it
|
|
282
|
+
// We do this by starting and immediately completing a dummy stream
|
|
283
|
+
const dummyId = this._startStream("cleanup-trigger");
|
|
284
|
+
this._completeStream(dummyId);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Insert a raw JSON string as a message directly into SQLite.
|
|
289
|
+
* Used to test validation of malformed/corrupt messages.
|
|
290
|
+
*/
|
|
291
|
+
insertRawMessage(rowId: string, rawJson: string): void {
|
|
292
|
+
this.sql`
|
|
293
|
+
insert into cf_ai_chat_agent_messages (id, message)
|
|
294
|
+
values (${rowId}, ${rawJson})
|
|
295
|
+
`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
setMaxPersistedMessages(max: number | null): void {
|
|
299
|
+
this.maxPersistedMessages = max ?? undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
getMessageCount(): number {
|
|
303
|
+
const result = this.sql<{ cnt: number }>`
|
|
304
|
+
select count(*) as cnt from cf_ai_chat_agent_messages
|
|
305
|
+
`;
|
|
306
|
+
return result?.[0]?.cnt ?? 0;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Returns the number of active abort controllers.
|
|
311
|
+
* Used to verify that cleanup happens after stream completion.
|
|
312
|
+
* If controllers leak, this count grows with each request.
|
|
313
|
+
*/
|
|
314
|
+
getAbortControllerCount(): number {
|
|
315
|
+
return (
|
|
316
|
+
this as unknown as {
|
|
317
|
+
_chatMessageAbortControllers: Map<string, unknown>;
|
|
318
|
+
}
|
|
319
|
+
)._chatMessageAbortControllers.size;
|
|
320
|
+
}
|
|
259
321
|
}
|
|
260
322
|
|
|
261
323
|
export default {
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { UIMessage } from "ai";
|
|
1
|
+
import type { JSONSchema7, UIMessage } from "ai";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Enum for message types to improve type safety and maintainability
|
|
@@ -14,6 +14,8 @@ export enum MessageType {
|
|
|
14
14
|
CF_AGENT_STREAM_RESUMING = "cf_agent_stream_resuming",
|
|
15
15
|
/** Sent by client to acknowledge stream resuming notification and request chunks */
|
|
16
16
|
CF_AGENT_STREAM_RESUME_ACK = "cf_agent_stream_resume_ack",
|
|
17
|
+
/** Sent by client after message handler is ready, requesting stream resume check */
|
|
18
|
+
CF_AGENT_STREAM_RESUME_REQUEST = "cf_agent_stream_resume_request",
|
|
17
19
|
|
|
18
20
|
/** Client sends tool result to server (for client-side tools) */
|
|
19
21
|
CF_AGENT_TOOL_RESULT = "cf_agent_tool_result",
|
|
@@ -50,6 +52,8 @@ export type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =
|
|
|
50
52
|
error?: boolean;
|
|
51
53
|
/** Whether this is a continuation (append to last assistant message) */
|
|
52
54
|
continuation?: boolean;
|
|
55
|
+
/** Whether this chunk is being replayed from storage (stream resumption) */
|
|
56
|
+
replay?: boolean;
|
|
53
57
|
}
|
|
54
58
|
| {
|
|
55
59
|
/** Indicates the server is resuming an active stream */
|
|
@@ -110,6 +114,10 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
|
|
|
110
114
|
/** The request ID of the stream being resumed */
|
|
111
115
|
id: string;
|
|
112
116
|
}
|
|
117
|
+
| {
|
|
118
|
+
/** Client requests stream resume check after message handler is registered */
|
|
119
|
+
type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST;
|
|
120
|
+
}
|
|
113
121
|
| {
|
|
114
122
|
/** Client sends tool result to server (for client-side tools) */
|
|
115
123
|
type: MessageType.CF_AGENT_TOOL_RESULT;
|
|
@@ -121,6 +129,12 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
|
|
|
121
129
|
output: unknown;
|
|
122
130
|
/** Whether server should auto-continue the conversation after applying result */
|
|
123
131
|
autoContinue?: boolean;
|
|
132
|
+
/** Client tool schemas for continuation (client is source of truth) */
|
|
133
|
+
clientTools?: Array<{
|
|
134
|
+
name: string;
|
|
135
|
+
description?: string;
|
|
136
|
+
parameters?: JSONSchema7;
|
|
137
|
+
}>;
|
|
124
138
|
}
|
|
125
139
|
| {
|
|
126
140
|
/** Client sends tool approval response to server (for tools with needsApproval) */
|
|
@@ -129,4 +143,6 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
|
|
|
129
143
|
toolCallId: string;
|
|
130
144
|
/** Whether the tool execution was approved */
|
|
131
145
|
approved: boolean;
|
|
146
|
+
/** Whether server should auto-continue the conversation after applying approval */
|
|
147
|
+
autoContinue?: boolean;
|
|
132
148
|
};
|