@cloudflare/ai-chat 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/experimental/forever.d.ts +4 -13
- package/dist/experimental/forever.js +1 -46
- package/dist/experimental/forever.js.map +1 -1
- package/dist/index.d.ts +59 -4
- package/dist/index.js +170 -28
- package/dist/index.js.map +1 -1
- package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
- package/dist/message-builder-uSvexDl2.js.map +1 -0
- package/dist/react.js +125 -31
- package/dist/react.js.map +1 -1
- package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
- package/dist/types.d.ts +2 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -3
- package/CHANGELOG.md +0 -244
- package/dist/message-builder-Bwc_Umye.js.map +0 -1
- package/e2e/chat.spec.ts +0 -1703
- package/e2e/client-tools.spec.ts +0 -504
- package/e2e/llm.spec.ts +0 -637
- package/e2e/playwright.config.ts +0 -27
- package/e2e/worker.ts +0 -174
- package/e2e/wrangler.jsonc +0 -23
- package/scripts/build.ts +0 -32
- package/src/ai-chat-v5-migration.ts +0 -403
- package/src/experimental/forever.ts +0 -66
- package/src/index.ts +0 -2269
- package/src/message-builder.ts +0 -384
- package/src/react-tests/setup.ts +0 -3
- package/src/react-tests/use-agent-chat.test.tsx +0 -1435
- package/src/react-tests/vitest.config.ts +0 -20
- package/src/react.tsx +0 -1447
- package/src/resumable-stream.ts +0 -441
- package/src/tests/cancel-request.test.ts +0 -280
- package/src/tests/chat-context.test.ts +0 -85
- package/src/tests/chat-persistence.test.ts +0 -426
- package/src/tests/clear-history.test.ts +0 -132
- package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
- package/src/tests/client-tools-broadcast.test.ts +0 -138
- package/src/tests/client-tools-continuation.test.ts +0 -314
- package/src/tests/client-tools-reconnect.test.ts +0 -143
- package/src/tests/cloudflare-test.d.ts +0 -5
- package/src/tests/custom-body-continuation.test.ts +0 -309
- package/src/tests/custom-body.test.ts +0 -186
- package/src/tests/destroy.test.ts +0 -57
- package/src/tests/get-messages-endpoint.test.ts +0 -153
- package/src/tests/max-persisted-messages.test.ts +0 -201
- package/src/tests/merge-server-state.test.ts +0 -343
- package/src/tests/message-builder.test.ts +0 -808
- package/src/tests/migration.test.ts +0 -282
- package/src/tests/non-sse-response.test.ts +0 -186
- package/src/tests/onfinish-cleanup.test.ts +0 -362
- package/src/tests/plaintext-response.test.ts +0 -87
- package/src/tests/request-id.test.ts +0 -312
- package/src/tests/resumable-streaming.test.ts +0 -758
- package/src/tests/row-size-guard.test.ts +0 -374
- package/src/tests/sanitize-messages.test.ts +0 -325
- package/src/tests/test-utils.ts +0 -39
- package/src/tests/tsconfig.json +0 -10
- package/src/tests/validate-messages.test.ts +0 -269
- package/src/tests/vitest.config.ts +0 -30
- package/src/tests/worker.ts +0 -456
- package/src/tests/wrangler.jsonc +0 -50
- package/src/types.ts +0 -152
- package/src/ws-chat-transport.ts +0 -203
- package/tsconfig.json +0 -4
- package/vitest.config.ts +0 -7
package/e2e/worker.ts
DELETED
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AIChatAgent,
|
|
3
|
-
type OnChatMessageOptions,
|
|
4
|
-
createToolsFromClientSchemas
|
|
5
|
-
} from "../src/index";
|
|
6
|
-
import { streamText, tool, convertToModelMessages, stepCountIs } from "ai";
|
|
7
|
-
import { createWorkersAI } from "workers-ai-provider";
|
|
8
|
-
import { createOpenAI } from "@ai-sdk/openai";
|
|
9
|
-
import { z } from "zod/v4";
|
|
10
|
-
import { routeAgentRequest } from "agents";
|
|
11
|
-
|
|
12
|
-
export type Env = {
|
|
13
|
-
ChatAgent: DurableObjectNamespace<ChatAgent>;
|
|
14
|
-
LlmChatAgent: DurableObjectNamespace<LlmChatAgent>;
|
|
15
|
-
ClientToolAgent: DurableObjectNamespace<ClientToolAgent>;
|
|
16
|
-
SlowAgent: DurableObjectNamespace<SlowAgent>;
|
|
17
|
-
BadKeyAgent: DurableObjectNamespace<BadKeyAgent>;
|
|
18
|
-
AI: Ai;
|
|
19
|
-
OPENAI_API_KEY: string;
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Simple agent that returns plain text — used by the basic protocol tests.
|
|
24
|
-
*/
|
|
25
|
-
export class ChatAgent extends AIChatAgent<Env> {
|
|
26
|
-
observability = undefined;
|
|
27
|
-
|
|
28
|
-
async onChatMessage() {
|
|
29
|
-
return new Response("Hello from e2e agent!", {
|
|
30
|
-
headers: { "Content-Type": "text/plain" }
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* LLM-backed agent using Workers AI with streamText.
|
|
37
|
-
* Used by the LLM e2e tests that verify real SSE streaming, tool calls, etc.
|
|
38
|
-
*/
|
|
39
|
-
export class LlmChatAgent extends AIChatAgent<Env> {
|
|
40
|
-
observability = undefined;
|
|
41
|
-
|
|
42
|
-
async onChatMessage(_onFinish?: unknown, options?: OnChatMessageOptions) {
|
|
43
|
-
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
44
|
-
|
|
45
|
-
const tools = {
|
|
46
|
-
getWeather: tool({
|
|
47
|
-
description: "Get the current weather for a city",
|
|
48
|
-
inputSchema: z.object({
|
|
49
|
-
city: z.string().describe("The city name")
|
|
50
|
-
}),
|
|
51
|
-
execute: async ({ city }) => ({
|
|
52
|
-
city,
|
|
53
|
-
temperature: 22,
|
|
54
|
-
condition: "Sunny"
|
|
55
|
-
})
|
|
56
|
-
}),
|
|
57
|
-
addNumbers: tool({
|
|
58
|
-
description: "Add two numbers together",
|
|
59
|
-
inputSchema: z.object({
|
|
60
|
-
a: z.number().describe("First number"),
|
|
61
|
-
b: z.number().describe("Second number")
|
|
62
|
-
}),
|
|
63
|
-
execute: async ({ a, b }) => ({
|
|
64
|
-
result: a + b
|
|
65
|
-
})
|
|
66
|
-
}),
|
|
67
|
-
...createToolsFromClientSchemas(options?.clientTools)
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
const result = streamText({
|
|
71
|
-
model: workersai("@cf/zai-org/glm-4.7-flash"),
|
|
72
|
-
system:
|
|
73
|
-
"You are a helpful test assistant. Keep responses very short (1-2 sentences max). " +
|
|
74
|
-
"When asked about the weather, use the getWeather tool. " +
|
|
75
|
-
"When asked to add numbers, use the addNumbers tool.",
|
|
76
|
-
messages: await convertToModelMessages(this.messages),
|
|
77
|
-
tools,
|
|
78
|
-
stopWhen: stepCountIs(3)
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
return result.toUIMessageStreamResponse();
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Agent with a client-side tool (no execute function).
|
|
87
|
-
* The LLM calls the tool, the stream pauses at tool-input-available,
|
|
88
|
-
* and the test must send CF_AGENT_TOOL_RESULT to continue.
|
|
89
|
-
*/
|
|
90
|
-
export class ClientToolAgent extends AIChatAgent<Env> {
|
|
91
|
-
observability = undefined;
|
|
92
|
-
|
|
93
|
-
async onChatMessage() {
|
|
94
|
-
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
95
|
-
|
|
96
|
-
const result = streamText({
|
|
97
|
-
model: workersai("@cf/zai-org/glm-4.7-flash"),
|
|
98
|
-
system:
|
|
99
|
-
"You are a test assistant. Always use the getUserLocation tool when asked about location.",
|
|
100
|
-
messages: await convertToModelMessages(this.messages),
|
|
101
|
-
tools: {
|
|
102
|
-
getUserLocation: tool({
|
|
103
|
-
description: "Get the user's current location from the browser",
|
|
104
|
-
inputSchema: z.object({})
|
|
105
|
-
// No execute — client must handle via CF_AGENT_TOOL_RESULT
|
|
106
|
-
})
|
|
107
|
-
},
|
|
108
|
-
stopWhen: stepCountIs(3)
|
|
109
|
-
});
|
|
110
|
-
|
|
111
|
-
return result.toUIMessageStreamResponse();
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Agent that returns a slow, multi-chunk plain text response.
|
|
117
|
-
* Used to test stream resumption by disconnecting mid-stream.
|
|
118
|
-
*/
|
|
119
|
-
export class SlowAgent extends AIChatAgent<Env> {
|
|
120
|
-
observability = undefined;
|
|
121
|
-
|
|
122
|
-
async onChatMessage() {
|
|
123
|
-
// Create a stream that sends chunks with delays
|
|
124
|
-
const encoder = new TextEncoder();
|
|
125
|
-
const stream = new ReadableStream({
|
|
126
|
-
async start(controller) {
|
|
127
|
-
const chunks = [
|
|
128
|
-
"chunk-1 ",
|
|
129
|
-
"chunk-2 ",
|
|
130
|
-
"chunk-3 ",
|
|
131
|
-
"chunk-4 ",
|
|
132
|
-
"chunk-5"
|
|
133
|
-
];
|
|
134
|
-
for (const chunk of chunks) {
|
|
135
|
-
controller.enqueue(encoder.encode(chunk));
|
|
136
|
-
await new Promise((r) => setTimeout(r, 400));
|
|
137
|
-
}
|
|
138
|
-
controller.close();
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
return new Response(stream, {
|
|
143
|
-
headers: { "Content-Type": "text/plain" }
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Agent configured with a bad API key to test error handling.
|
|
150
|
-
*/
|
|
151
|
-
export class BadKeyAgent extends AIChatAgent<Env> {
|
|
152
|
-
observability = undefined;
|
|
153
|
-
|
|
154
|
-
async onChatMessage() {
|
|
155
|
-
const openai = createOpenAI({ apiKey: "sk-invalid-key-for-testing" });
|
|
156
|
-
|
|
157
|
-
const result = streamText({
|
|
158
|
-
model: openai.chat("gpt-4o-mini"),
|
|
159
|
-
system: "You are a test assistant.",
|
|
160
|
-
messages: await convertToModelMessages(this.messages)
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
return result.toUIMessageStreamResponse();
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
export default {
|
|
168
|
-
async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
|
|
169
|
-
return (
|
|
170
|
-
(await routeAgentRequest(request, env)) ||
|
|
171
|
-
new Response("Not found", { status: 404 })
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
};
|
package/e2e/wrangler.jsonc
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"ai": { "binding": "AI", "remote": true },
|
|
3
|
-
"compatibility_date": "2026-01-28",
|
|
4
|
-
"compatibility_flags": ["nodejs_compat"],
|
|
5
|
-
"durable_objects": {
|
|
6
|
-
"bindings": [
|
|
7
|
-
{ "class_name": "ChatAgent", "name": "ChatAgent" },
|
|
8
|
-
{ "class_name": "LlmChatAgent", "name": "LlmChatAgent" },
|
|
9
|
-
{ "class_name": "ClientToolAgent", "name": "ClientToolAgent" },
|
|
10
|
-
{ "class_name": "SlowAgent", "name": "SlowAgent" },
|
|
11
|
-
{ "class_name": "BadKeyAgent", "name": "BadKeyAgent" }
|
|
12
|
-
]
|
|
13
|
-
},
|
|
14
|
-
"main": "worker.ts",
|
|
15
|
-
"migrations": [
|
|
16
|
-
{ "new_sqlite_classes": ["ChatAgent"], "tag": "v1" },
|
|
17
|
-
{ "new_sqlite_classes": ["LlmChatAgent"], "tag": "v2" },
|
|
18
|
-
{
|
|
19
|
-
"new_sqlite_classes": ["ClientToolAgent", "SlowAgent", "BadKeyAgent"],
|
|
20
|
-
"tag": "v3"
|
|
21
|
-
}
|
|
22
|
-
]
|
|
23
|
-
}
|
package/scripts/build.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { execSync } from "node:child_process";
|
|
2
|
-
import { build } from "tsdown";
|
|
3
|
-
|
|
4
|
-
async function main() {
|
|
5
|
-
await build({
|
|
6
|
-
clean: true,
|
|
7
|
-
dts: true,
|
|
8
|
-
entry: [
|
|
9
|
-
"src/index.ts",
|
|
10
|
-
"src/react.tsx",
|
|
11
|
-
"src/types.ts",
|
|
12
|
-
"src/ai-chat-v5-migration.ts",
|
|
13
|
-
"src/experimental/forever.ts"
|
|
14
|
-
],
|
|
15
|
-
skipNodeModulesBundle: true,
|
|
16
|
-
external: ["cloudflare:workers", "cloudflare:email"],
|
|
17
|
-
format: "esm",
|
|
18
|
-
sourcemap: true,
|
|
19
|
-
fixedExtension: false
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
// then run oxfmt on the generated .d.ts files
|
|
23
|
-
execSync("oxfmt --write ./dist/*.d.ts");
|
|
24
|
-
|
|
25
|
-
process.exit(0);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
main().catch((err) => {
|
|
29
|
-
// Build failures should fail
|
|
30
|
-
console.error(err);
|
|
31
|
-
process.exit(1);
|
|
32
|
-
});
|
|
@@ -1,403 +0,0 @@
|
|
|
1
|
-
import type { UIMessage } from "ai";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
|
|
5
|
-
* Using exact types from the official AI SDK documentation
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* One-shot deprecation warnings (warns once per key per session).
|
|
10
|
-
*/
|
|
11
|
-
const _deprecationWarnings = new Set<string>();
|
|
12
|
-
function warnDeprecated(id: string, message: string) {
|
|
13
|
-
if (!_deprecationWarnings.has(id)) {
|
|
14
|
-
_deprecationWarnings.add(id);
|
|
15
|
-
console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* AI SDK v5 Message Part types reference (from official AI SDK documentation)
|
|
21
|
-
*
|
|
22
|
-
* The migration logic below transforms legacy messages to match these official AI SDK v5 formats:
|
|
23
|
-
* - TextUIPart: { type: "text", text: string, state?: "streaming" | "done" }
|
|
24
|
-
* - ReasoningUIPart: { type: "reasoning", text: string, state?: "streaming" | "done", providerMetadata?: Record<string, unknown> }
|
|
25
|
-
* - FileUIPart: { type: "file", mediaType: string, filename?: string, url: string }
|
|
26
|
-
* - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: "input-streaming" | "input-available" | "output-available" | "output-error", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }
|
|
27
|
-
*/
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Tool invocation from v4 format
|
|
31
|
-
*/
|
|
32
|
-
type ToolInvocation = {
|
|
33
|
-
toolCallId: string;
|
|
34
|
-
toolName: string;
|
|
35
|
-
args: Record<string, unknown>;
|
|
36
|
-
result?: unknown;
|
|
37
|
-
state: "partial-call" | "call" | "result" | "error";
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Legacy part from v4 format
|
|
42
|
-
*/
|
|
43
|
-
type LegacyPart = {
|
|
44
|
-
type: string;
|
|
45
|
-
text?: string;
|
|
46
|
-
url?: string;
|
|
47
|
-
data?: string;
|
|
48
|
-
mimeType?: string;
|
|
49
|
-
mediaType?: string;
|
|
50
|
-
filename?: string;
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Legacy message format from AI SDK v4
|
|
55
|
-
*/
|
|
56
|
-
export type LegacyMessage = {
|
|
57
|
-
id?: string;
|
|
58
|
-
role: string;
|
|
59
|
-
content: string;
|
|
60
|
-
reasoning?: string;
|
|
61
|
-
toolInvocations?: ToolInvocation[];
|
|
62
|
-
parts?: LegacyPart[];
|
|
63
|
-
[key: string]: unknown;
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Corrupt content item
|
|
68
|
-
*/
|
|
69
|
-
type CorruptContentItem = {
|
|
70
|
-
type: string;
|
|
71
|
-
text: string;
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Corrupted message format - has content as array instead of parts
|
|
76
|
-
*/
|
|
77
|
-
export type CorruptArrayMessage = {
|
|
78
|
-
id?: string;
|
|
79
|
-
role: string;
|
|
80
|
-
content: CorruptContentItem[];
|
|
81
|
-
reasoning?: string;
|
|
82
|
-
toolInvocations?: ToolInvocation[];
|
|
83
|
-
[key: string]: unknown;
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Union type for messages that could be in any format
|
|
88
|
-
*/
|
|
89
|
-
export type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Tool call state mapping for v4 to v5 migration
|
|
93
|
-
*/
|
|
94
|
-
const STATE_MAP = {
|
|
95
|
-
"partial-call": "input-streaming",
|
|
96
|
-
call: "input-available",
|
|
97
|
-
result: "output-available",
|
|
98
|
-
error: "output-error"
|
|
99
|
-
} as const;
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Checks if a message is already in the UIMessage format (has parts array)
|
|
103
|
-
*/
|
|
104
|
-
export function isUIMessage(message: unknown): message is UIMessage {
|
|
105
|
-
return (
|
|
106
|
-
typeof message === "object" &&
|
|
107
|
-
message !== null &&
|
|
108
|
-
"parts" in message &&
|
|
109
|
-
Array.isArray((message as { parts: unknown }).parts)
|
|
110
|
-
);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Type guard to check if a message is in legacy format (content as string)
|
|
115
|
-
*/
|
|
116
|
-
function isLegacyMessage(message: unknown): message is LegacyMessage {
|
|
117
|
-
return (
|
|
118
|
-
typeof message === "object" &&
|
|
119
|
-
message !== null &&
|
|
120
|
-
"role" in message &&
|
|
121
|
-
"content" in message &&
|
|
122
|
-
typeof (message as { role: unknown }).role === "string" &&
|
|
123
|
-
typeof (message as { content: unknown }).content === "string"
|
|
124
|
-
);
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Type guard to check if a message has corrupted array content format
|
|
129
|
-
* Detects: {role: "user", content: [{type: "text", text: "..."}]}
|
|
130
|
-
*/
|
|
131
|
-
function isCorruptArrayMessage(
|
|
132
|
-
message: unknown
|
|
133
|
-
): message is CorruptArrayMessage {
|
|
134
|
-
return (
|
|
135
|
-
typeof message === "object" &&
|
|
136
|
-
message !== null &&
|
|
137
|
-
"role" in message &&
|
|
138
|
-
"content" in message &&
|
|
139
|
-
typeof (message as { role: unknown }).role === "string" &&
|
|
140
|
-
Array.isArray((message as { content: unknown }).content) &&
|
|
141
|
-
!("parts" in message) // Ensure it's not already a UIMessage
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Internal message part type for transformation
|
|
147
|
-
*/
|
|
148
|
-
type TransformMessagePart = {
|
|
149
|
-
type: string;
|
|
150
|
-
text?: string;
|
|
151
|
-
toolCallId?: string;
|
|
152
|
-
state?: string;
|
|
153
|
-
input?: Record<string, unknown>;
|
|
154
|
-
output?: unknown;
|
|
155
|
-
url?: string;
|
|
156
|
-
mediaType?: string;
|
|
157
|
-
errorText?: string;
|
|
158
|
-
filename?: string;
|
|
159
|
-
};
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* Input message that could be in any format - using unknown for flexibility
|
|
163
|
-
*/
|
|
164
|
-
type InputMessage = {
|
|
165
|
-
id?: string;
|
|
166
|
-
role?: string;
|
|
167
|
-
content?: unknown;
|
|
168
|
-
reasoning?: string;
|
|
169
|
-
toolInvocations?: unknown[];
|
|
170
|
-
parts?: unknown[];
|
|
171
|
-
[key: string]: unknown;
|
|
172
|
-
};
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* Automatic message transformer following the blog post pattern
|
|
176
|
-
* Handles comprehensive migration from AI SDK v4 to v5 format
|
|
177
|
-
* @param message - Message in any legacy format
|
|
178
|
-
* @param index - Index for ID generation fallback
|
|
179
|
-
* @returns UIMessage in v5 format
|
|
180
|
-
*/
|
|
181
|
-
export function autoTransformMessage(
|
|
182
|
-
message: UIMessage | InputMessage,
|
|
183
|
-
index = 0
|
|
184
|
-
): UIMessage {
|
|
185
|
-
// Already in v5 format
|
|
186
|
-
if (isUIMessage(message)) {
|
|
187
|
-
return message;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const parts: TransformMessagePart[] = [];
|
|
191
|
-
|
|
192
|
-
// Handle reasoning transformation
|
|
193
|
-
if (message.reasoning) {
|
|
194
|
-
parts.push({
|
|
195
|
-
type: "reasoning",
|
|
196
|
-
text: message.reasoning
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// Handle tool invocations transformation
|
|
201
|
-
if (message.toolInvocations && Array.isArray(message.toolInvocations)) {
|
|
202
|
-
message.toolInvocations.forEach((inv: unknown) => {
|
|
203
|
-
if (typeof inv === "object" && inv !== null && "toolName" in inv) {
|
|
204
|
-
const invObj = inv as ToolInvocation;
|
|
205
|
-
parts.push({
|
|
206
|
-
type: `tool-${invObj.toolName}`,
|
|
207
|
-
toolCallId: invObj.toolCallId,
|
|
208
|
-
state:
|
|
209
|
-
STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||
|
|
210
|
-
"input-available",
|
|
211
|
-
input: invObj.args,
|
|
212
|
-
output: invObj.result !== undefined ? invObj.result : null
|
|
213
|
-
});
|
|
214
|
-
}
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// Handle file parts transformation
|
|
219
|
-
if (message.parts && Array.isArray(message.parts)) {
|
|
220
|
-
message.parts.forEach((part: unknown) => {
|
|
221
|
-
if (typeof part === "object" && part !== null && "type" in part) {
|
|
222
|
-
const partObj = part as LegacyPart;
|
|
223
|
-
if (partObj.type === "file") {
|
|
224
|
-
parts.push({
|
|
225
|
-
type: "file",
|
|
226
|
-
url:
|
|
227
|
-
partObj.url ||
|
|
228
|
-
(partObj.data
|
|
229
|
-
? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`
|
|
230
|
-
: undefined),
|
|
231
|
-
mediaType: partObj.mediaType || partObj.mimeType,
|
|
232
|
-
filename: partObj.filename
|
|
233
|
-
});
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// Handle corrupt array format: {role: "user", content: [{type: "text", text: "..."}]}
|
|
240
|
-
if (Array.isArray(message.content)) {
|
|
241
|
-
message.content.forEach((item: unknown) => {
|
|
242
|
-
if (typeof item === "object" && item !== null && "text" in item) {
|
|
243
|
-
const itemObj = item as CorruptContentItem;
|
|
244
|
-
parts.push({
|
|
245
|
-
type: itemObj.type || "text",
|
|
246
|
-
text: itemObj.text || ""
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// Fallback: convert plain content to text part
|
|
253
|
-
if (!parts.length && message.content !== undefined) {
|
|
254
|
-
parts.push({
|
|
255
|
-
type: "text",
|
|
256
|
-
text:
|
|
257
|
-
typeof message.content === "string"
|
|
258
|
-
? message.content
|
|
259
|
-
: JSON.stringify(message.content)
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// If still no parts, create a default text part
|
|
264
|
-
if (!parts.length) {
|
|
265
|
-
parts.push({
|
|
266
|
-
type: "text",
|
|
267
|
-
text: typeof message === "string" ? message : JSON.stringify(message)
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
return {
|
|
272
|
-
id: message.id || `msg-${index}`,
|
|
273
|
-
role:
|
|
274
|
-
message.role === "data"
|
|
275
|
-
? "system"
|
|
276
|
-
: (message.role as "user" | "assistant" | "system") || "user",
|
|
277
|
-
parts: parts as UIMessage["parts"]
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
* Legacy single message migration for backward compatibility.
|
|
283
|
-
* @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.
|
|
284
|
-
*/
|
|
285
|
-
export function migrateToUIMessage(message: MigratableMessage): UIMessage {
|
|
286
|
-
warnDeprecated(
|
|
287
|
-
"migrateToUIMessage",
|
|
288
|
-
"migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version."
|
|
289
|
-
);
|
|
290
|
-
return autoTransformMessage(message as InputMessage);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* Automatic message transformer for arrays following the blog post pattern
|
|
295
|
-
* @param messages - Array of messages in any format
|
|
296
|
-
* @returns Array of UIMessages in v5 format
|
|
297
|
-
*/
|
|
298
|
-
export function autoTransformMessages(messages: unknown[]): UIMessage[] {
|
|
299
|
-
return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Migrates an array of messages to UIMessage format (legacy compatibility).
|
|
304
|
-
* @param messages - Array of messages in old or new format
|
|
305
|
-
* @returns Array of UIMessages in the new format
|
|
306
|
-
* @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.
|
|
307
|
-
*/
|
|
308
|
-
export function migrateMessagesToUIFormat(
|
|
309
|
-
messages: MigratableMessage[]
|
|
310
|
-
): UIMessage[] {
|
|
311
|
-
warnDeprecated(
|
|
312
|
-
"migrateMessagesToUIFormat",
|
|
313
|
-
"migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version."
|
|
314
|
-
);
|
|
315
|
-
return autoTransformMessages(messages as InputMessage[]);
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/**
|
|
319
|
-
* Checks if any messages in an array need migration.
|
|
320
|
-
* @param messages - Array of messages to check
|
|
321
|
-
* @returns true if any messages are not in proper UIMessage format
|
|
322
|
-
* @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.
|
|
323
|
-
*/
|
|
324
|
-
export function needsMigration(messages: unknown[]): boolean {
|
|
325
|
-
warnDeprecated(
|
|
326
|
-
"needsMigration",
|
|
327
|
-
"needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version."
|
|
328
|
-
);
|
|
329
|
-
return messages.some((message) => {
|
|
330
|
-
// If it's already a UIMessage, no migration needed
|
|
331
|
-
if (isUIMessage(message)) {
|
|
332
|
-
return false;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// Check for corrupt array format specifically
|
|
336
|
-
if (isCorruptArrayMessage(message)) {
|
|
337
|
-
return true;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
// Check for legacy string format
|
|
341
|
-
if (isLegacyMessage(message)) {
|
|
342
|
-
return true;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// Any other format needs migration
|
|
346
|
-
return true;
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* Analyzes the corruption types in a message array for debugging.
|
|
352
|
-
* @param messages - Array of messages to analyze
|
|
353
|
-
* @returns Statistics about corruption types found
|
|
354
|
-
* @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.
|
|
355
|
-
*/
|
|
356
|
-
export function analyzeCorruption(messages: unknown[]): {
|
|
357
|
-
total: number;
|
|
358
|
-
clean: number;
|
|
359
|
-
legacyString: number;
|
|
360
|
-
corruptArray: number;
|
|
361
|
-
unknown: number;
|
|
362
|
-
examples: {
|
|
363
|
-
legacyString?: unknown;
|
|
364
|
-
corruptArray?: unknown;
|
|
365
|
-
unknown?: unknown;
|
|
366
|
-
};
|
|
367
|
-
} {
|
|
368
|
-
const stats = {
|
|
369
|
-
total: messages.length,
|
|
370
|
-
clean: 0,
|
|
371
|
-
legacyString: 0,
|
|
372
|
-
corruptArray: 0,
|
|
373
|
-
unknown: 0,
|
|
374
|
-
examples: {} as {
|
|
375
|
-
legacyString?: unknown;
|
|
376
|
-
corruptArray?: unknown;
|
|
377
|
-
unknown?: unknown;
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
|
|
381
|
-
for (const message of messages) {
|
|
382
|
-
if (isUIMessage(message)) {
|
|
383
|
-
stats.clean++;
|
|
384
|
-
} else if (isCorruptArrayMessage(message)) {
|
|
385
|
-
stats.corruptArray++;
|
|
386
|
-
if (!stats.examples.corruptArray) {
|
|
387
|
-
stats.examples.corruptArray = message;
|
|
388
|
-
}
|
|
389
|
-
} else if (isLegacyMessage(message)) {
|
|
390
|
-
stats.legacyString++;
|
|
391
|
-
if (!stats.examples.legacyString) {
|
|
392
|
-
stats.examples.legacyString = message;
|
|
393
|
-
}
|
|
394
|
-
} else {
|
|
395
|
-
stats.unknown++;
|
|
396
|
-
if (!stats.examples.unknown) {
|
|
397
|
-
stats.examples.unknown = message;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
return stats;
|
|
403
|
-
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|
3
|
-
* !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!
|
|
4
|
-
* !! !!
|
|
5
|
-
* !! This API is under active development and WILL break between !!
|
|
6
|
-
* !! releases. Method names, types, behavior, and the mixin signature !!
|
|
7
|
-
* !! are all subject to change without notice. !!
|
|
8
|
-
* !! !!
|
|
9
|
-
* !! If you use this, pin your @cloudflare/ai-chat version and expect !!
|
|
10
|
-
* !! to rewrite your code when upgrading. !!
|
|
11
|
-
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|
12
|
-
*
|
|
13
|
-
* Experimental mixin for durable chat streaming.
|
|
14
|
-
*
|
|
15
|
-
* Usage:
|
|
16
|
-
* import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
17
|
-
* import { withDurableChat } from "@cloudflare/ai-chat/experimental/forever";
|
|
18
|
-
*
|
|
19
|
-
* class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {
|
|
20
|
-
* async onChatMessage(onFinish, options) { ... }
|
|
21
|
-
* }
|
|
22
|
-
*
|
|
23
|
-
* This mixin adds:
|
|
24
|
-
* - keepAlive during streaming — DO stays alive while LLM generates
|
|
25
|
-
* - (planned) getPartialStreamText() — extract partial response from chunks
|
|
26
|
-
* - (planned) onStreamInterrupted() — hook for recovery after eviction
|
|
27
|
-
*
|
|
28
|
-
* @experimental This API is not yet stable and may change.
|
|
29
|
-
*/
|
|
30
|
-
import { keepAlive } from "agents/experimental/forever";
|
|
31
|
-
import type { AIChatAgent } from "../index";
|
|
32
|
-
|
|
33
|
-
console.warn(
|
|
34
|
-
"[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production."
|
|
35
|
-
);
|
|
36
|
-
|
|
37
|
-
// ── Mixin ─────────────────────────────────────────────────────────────
|
|
38
|
-
|
|
39
|
-
// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- mixin constructor constraint
|
|
40
|
-
type Constructor<T = object> = new (...args: any[]) => T;
|
|
41
|
-
|
|
42
|
-
type AIChatAgentLike = Constructor<
|
|
43
|
-
Pick<AIChatAgent, "scheduleEvery" | "cancelSchedule">
|
|
44
|
-
>;
|
|
45
|
-
|
|
46
|
-
export function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase) {
|
|
47
|
-
class DurableChatAgent extends Base {
|
|
48
|
-
/**
|
|
49
|
-
* No-op heartbeat callback. The schedule itself keeps the DO alive;
|
|
50
|
-
* the callback doesn't need to do anything.
|
|
51
|
-
* @internal
|
|
52
|
-
*/
|
|
53
|
-
// oxlint-disable-next-line @typescript-eslint/no-empty-function
|
|
54
|
-
_cf_streamKeepAlive() {}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Keep the DO alive during streaming.
|
|
58
|
-
* Returns a disposer that cancels the heartbeat schedule.
|
|
59
|
-
*/
|
|
60
|
-
async keepAlive(): Promise<() => void> {
|
|
61
|
-
return keepAlive(this, "_cf_streamKeepAlive");
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
return DurableChatAgent;
|
|
66
|
-
}
|