@cloudflare/ai-chat 0.0.8 → 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 +89 -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 +114 -76
- package/dist/index.js +745 -629
- 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 +244 -258
- 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 +831 -1137
- package/src/message-builder.ts +384 -0
- package/src/react-tests/use-agent-chat.test.tsx +738 -2
- package/src/react.tsx +385 -461
- 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 +3 -3
- 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 +3 -3
- 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 +59 -24
- package/src/types.ts +17 -1
- package/src/ws-chat-transport.ts +203 -0
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
import { UIMessage } from "ai";
|
|
2
2
|
|
|
3
3
|
//#region src/ai-chat-v5-migration.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
|
|
6
|
-
* Using exact types from the official AI SDK documentation
|
|
7
|
-
*/
|
|
8
4
|
/**
|
|
9
5
|
* AI SDK v5 Message Part types reference (from official AI SDK documentation)
|
|
10
6
|
*
|
|
@@ -94,11 +90,12 @@ type InputMessage = {
|
|
|
94
90
|
* @returns UIMessage in v5 format
|
|
95
91
|
*/
|
|
96
92
|
declare function autoTransformMessage(
|
|
97
|
-
message: InputMessage,
|
|
93
|
+
message: UIMessage | InputMessage,
|
|
98
94
|
index?: number
|
|
99
95
|
): UIMessage;
|
|
100
96
|
/**
|
|
101
|
-
* Legacy single message migration for backward compatibility
|
|
97
|
+
* Legacy single message migration for backward compatibility.
|
|
98
|
+
* @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.
|
|
102
99
|
*/
|
|
103
100
|
declare function migrateToUIMessage(message: MigratableMessage): UIMessage;
|
|
104
101
|
/**
|
|
@@ -108,23 +105,26 @@ declare function migrateToUIMessage(message: MigratableMessage): UIMessage;
|
|
|
108
105
|
*/
|
|
109
106
|
declare function autoTransformMessages(messages: unknown[]): UIMessage[];
|
|
110
107
|
/**
|
|
111
|
-
* Migrates an array of messages to UIMessage format (legacy compatibility)
|
|
108
|
+
* Migrates an array of messages to UIMessage format (legacy compatibility).
|
|
112
109
|
* @param messages - Array of messages in old or new format
|
|
113
110
|
* @returns Array of UIMessages in the new format
|
|
111
|
+
* @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.
|
|
114
112
|
*/
|
|
115
113
|
declare function migrateMessagesToUIFormat(
|
|
116
114
|
messages: MigratableMessage[]
|
|
117
115
|
): UIMessage[];
|
|
118
116
|
/**
|
|
119
|
-
* Checks if any messages in an array need migration
|
|
117
|
+
* Checks if any messages in an array need migration.
|
|
120
118
|
* @param messages - Array of messages to check
|
|
121
119
|
* @returns true if any messages are not in proper UIMessage format
|
|
120
|
+
* @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.
|
|
122
121
|
*/
|
|
123
122
|
declare function needsMigration(messages: unknown[]): boolean;
|
|
124
123
|
/**
|
|
125
|
-
* Analyzes the corruption types in a message array for debugging
|
|
124
|
+
* Analyzes the corruption types in a message array for debugging.
|
|
126
125
|
* @param messages - Array of messages to analyze
|
|
127
126
|
* @returns Statistics about corruption types found
|
|
127
|
+
* @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.
|
|
128
128
|
*/
|
|
129
129
|
declare function analyzeCorruption(messages: unknown[]): {
|
|
130
130
|
total: number;
|
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
//#region src/ai-chat-v5-migration.ts
|
|
2
2
|
/**
|
|
3
|
+
* AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
|
|
4
|
+
* Using exact types from the official AI SDK documentation
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* One-shot deprecation warnings (warns once per key per session).
|
|
8
|
+
*/
|
|
9
|
+
const _deprecationWarnings = /* @__PURE__ */ new Set();
|
|
10
|
+
function warnDeprecated(id, message) {
|
|
11
|
+
if (!_deprecationWarnings.has(id)) {
|
|
12
|
+
_deprecationWarnings.add(id);
|
|
13
|
+
console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
3
17
|
* Tool call state mapping for v4 to v5 migration
|
|
4
18
|
*/
|
|
5
19
|
const STATE_MAP = {
|
|
@@ -88,9 +102,11 @@ function autoTransformMessage(message, index = 0) {
|
|
|
88
102
|
};
|
|
89
103
|
}
|
|
90
104
|
/**
|
|
91
|
-
* Legacy single message migration for backward compatibility
|
|
105
|
+
* Legacy single message migration for backward compatibility.
|
|
106
|
+
* @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.
|
|
92
107
|
*/
|
|
93
108
|
function migrateToUIMessage(message) {
|
|
109
|
+
warnDeprecated("migrateToUIMessage", "migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version.");
|
|
94
110
|
return autoTransformMessage(message);
|
|
95
111
|
}
|
|
96
112
|
/**
|
|
@@ -102,19 +118,23 @@ function autoTransformMessages(messages) {
|
|
|
102
118
|
return messages.map((msg, i) => autoTransformMessage(msg, i));
|
|
103
119
|
}
|
|
104
120
|
/**
|
|
105
|
-
* Migrates an array of messages to UIMessage format (legacy compatibility)
|
|
121
|
+
* Migrates an array of messages to UIMessage format (legacy compatibility).
|
|
106
122
|
* @param messages - Array of messages in old or new format
|
|
107
123
|
* @returns Array of UIMessages in the new format
|
|
124
|
+
* @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.
|
|
108
125
|
*/
|
|
109
126
|
function migrateMessagesToUIFormat(messages) {
|
|
127
|
+
warnDeprecated("migrateMessagesToUIFormat", "migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version.");
|
|
110
128
|
return autoTransformMessages(messages);
|
|
111
129
|
}
|
|
112
130
|
/**
|
|
113
|
-
* Checks if any messages in an array need migration
|
|
131
|
+
* Checks if any messages in an array need migration.
|
|
114
132
|
* @param messages - Array of messages to check
|
|
115
133
|
* @returns true if any messages are not in proper UIMessage format
|
|
134
|
+
* @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.
|
|
116
135
|
*/
|
|
117
136
|
function needsMigration(messages) {
|
|
137
|
+
warnDeprecated("needsMigration", "needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version.");
|
|
118
138
|
return messages.some((message) => {
|
|
119
139
|
if (isUIMessage(message)) return false;
|
|
120
140
|
if (isCorruptArrayMessage(message)) return true;
|
|
@@ -123,9 +143,10 @@ function needsMigration(messages) {
|
|
|
123
143
|
});
|
|
124
144
|
}
|
|
125
145
|
/**
|
|
126
|
-
* Analyzes the corruption types in a message array for debugging
|
|
146
|
+
* Analyzes the corruption types in a message array for debugging.
|
|
127
147
|
* @param messages - Array of messages to analyze
|
|
128
148
|
* @returns Statistics about corruption types found
|
|
149
|
+
* @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.
|
|
129
150
|
*/
|
|
130
151
|
function analyzeCorruption(messages) {
|
|
131
152
|
const stats = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-chat-v5-migration.js","names":[],"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - 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 }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return message;\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return {\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n };\n}\n\n/**\n * Legacy single message migration for backward compatibility\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility)\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n */\nexport function needsMigration(messages: unknown[]): boolean {\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";;;;AAkFA,MAAM,YAAY;CAChB,gBAAgB;CAChB,MAAM;CACN,QAAQ;CACR,OAAO;CACR;;;;AAKD,SAAgB,YAAY,SAAwC;AAClE,QACE,OAAO,YAAY,YACnB,YAAY,QACZ,WAAW,WACX,MAAM,QAAS,QAA+B,MAAM;;;;;AAOxD,SAAS,gBAAgB,SAA4C;AACnE,QACE,OAAO,YAAY,YACnB,YAAY,Q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AS,eAAe;YAEvB,gBAAgB,QAAQ,EAAE;AACnC,QAAM;AACN,MAAI,CAAC,MAAM,SAAS,aAClB,OAAM,SAAS,eAAe;QAE3B;AACL,QAAM;AACN,MAAI,CAAC,MAAM,SAAS,QAClB,OAAM,SAAS,UAAU;;AAK/B,QAAO"}
|
|
1
|
+
{"version":3,"file":"ai-chat-v5-migration.js","names":[],"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - 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 }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: UIMessage | InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return message;\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return {\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n };\n}\n\n/**\n * Legacy single message migration for backward compatibility.\n * @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n warnDeprecated(\n \"migrateToUIMessage\",\n \"migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility).\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n * @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n warnDeprecated(\n \"migrateMessagesToUIFormat\",\n \"migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration.\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n * @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.\n */\nexport function needsMigration(messages: unknown[]): boolean {\n warnDeprecated(\n \"needsMigration\",\n \"needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version.\"\n );\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging.\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n * @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,uCAAuB,IAAI,KAAa;AAC9C,SAAS,eAAe,IAAY,SAAiB;AACnD,KAAI,CAAC,qBAAqB,IAAI,GAAG,EAAE;AACjC,uBAAqB,IAAI,GAAG;AAC5B,UAAQ,KAAK,qCAAqC,UAAU;;;;;;AA+EhE,MAAM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B,QAAO;AAIT,SAAO;GACP;;;;;;;;AASJ,SAAgB,kBAAkB,UAWhC;CACA,MAAM,QAAQ;EACZ,OAAO,SAAS;EAChB,OAAO;EACP,cAAc;EACd,cAAc;EACd,SAAS;EACT,UAAU,EAAE;EAKb;AAED,MAAK,MAAM,WAAW,SACpB,KAAI,YAAY,QAAQ,CACtB,OAAM;UACG,sBAAsB,QAAQ,EAAE;AACzC,QAAM;AACN,MAAI,CAAC,MAAM,SAAS,aAClB,OAAM,SAAS,eAAe;YAEvB,gBAAgB,QAAQ,EAAE;AACnC,QAAM;AACN,MAAI,CAAC,MAAM,SAAS,aAClB,OAAM,SAAS,eAAe;QAE3B;AACL,QAAM;AACN,MAAI,CAAC,MAAM,SAAS,QAClB,OAAM,SAAS,UAAU;;AAK/B,QAAO"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import "../resumable-stream-DqXxQVjf.js";
|
|
2
|
+
import { AIChatAgent } from "../index.js";
|
|
3
|
+
import * as agents from "agents";
|
|
4
|
+
|
|
5
|
+
//#region src/experimental/forever.d.ts
|
|
6
|
+
type Constructor<T = object> = new (...args: any[]) => T;
|
|
7
|
+
type AIChatAgentLike = Constructor<Pick<AIChatAgent, "scheduleEvery" | "cancelSchedule">>;
|
|
8
|
+
declare function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase): {
|
|
9
|
+
new (...args: any[]): {
|
|
10
|
+
/**
|
|
11
|
+
* No-op heartbeat callback. The schedule itself keeps the DO alive;
|
|
12
|
+
* the callback doesn't need to do anything.
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
_cf_streamKeepAlive(): void;
|
|
16
|
+
/**
|
|
17
|
+
* Keep the DO alive during streaming.
|
|
18
|
+
* Returns a disposer that cancels the heartbeat schedule.
|
|
19
|
+
*/
|
|
20
|
+
keepAlive(): Promise<() => void>;
|
|
21
|
+
scheduleEvery: <T = string>(intervalSeconds: number, callback: keyof AIChatAgent<Cloudflare.Env, unknown>, payload?: T | undefined, options?: {
|
|
22
|
+
retry?: agents.RetryOptions;
|
|
23
|
+
}) => Promise<agents.Schedule<T>>;
|
|
24
|
+
cancelSchedule: (id: string) => Promise<boolean>;
|
|
25
|
+
};
|
|
26
|
+
} & TBase;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { withDurableChat };
|
|
29
|
+
//# sourceMappingURL=forever.d.ts.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { keepAlive } from "agents/experimental/forever";
|
|
2
|
+
|
|
3
|
+
//#region src/experimental/forever.ts
|
|
4
|
+
/**
|
|
5
|
+
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|
6
|
+
* !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!
|
|
7
|
+
* !! !!
|
|
8
|
+
* !! This API is under active development and WILL break between !!
|
|
9
|
+
* !! releases. Method names, types, behavior, and the mixin signature !!
|
|
10
|
+
* !! are all subject to change without notice. !!
|
|
11
|
+
* !! !!
|
|
12
|
+
* !! If you use this, pin your @cloudflare/ai-chat version and expect !!
|
|
13
|
+
* !! to rewrite your code when upgrading. !!
|
|
14
|
+
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|
15
|
+
*
|
|
16
|
+
* Experimental mixin for durable chat streaming.
|
|
17
|
+
*
|
|
18
|
+
* Usage:
|
|
19
|
+
* import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
20
|
+
* import { withDurableChat } from "@cloudflare/ai-chat/experimental/forever";
|
|
21
|
+
*
|
|
22
|
+
* class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {
|
|
23
|
+
* async onChatMessage(onFinish, options) { ... }
|
|
24
|
+
* }
|
|
25
|
+
*
|
|
26
|
+
* This mixin adds:
|
|
27
|
+
* - keepAlive during streaming — DO stays alive while LLM generates
|
|
28
|
+
* - (planned) getPartialStreamText() — extract partial response from chunks
|
|
29
|
+
* - (planned) onStreamInterrupted() — hook for recovery after eviction
|
|
30
|
+
*
|
|
31
|
+
* @experimental This API is not yet stable and may change.
|
|
32
|
+
*/
|
|
33
|
+
console.warn("[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production.");
|
|
34
|
+
function withDurableChat(Base) {
|
|
35
|
+
class DurableChatAgent extends Base {
|
|
36
|
+
/**
|
|
37
|
+
* No-op heartbeat callback. The schedule itself keeps the DO alive;
|
|
38
|
+
* the callback doesn't need to do anything.
|
|
39
|
+
* @internal
|
|
40
|
+
*/
|
|
41
|
+
_cf_streamKeepAlive() {}
|
|
42
|
+
/**
|
|
43
|
+
* Keep the DO alive during streaming.
|
|
44
|
+
* Returns a disposer that cancels the heartbeat schedule.
|
|
45
|
+
*/
|
|
46
|
+
async keepAlive() {
|
|
47
|
+
return keepAlive(this, "_cf_streamKeepAlive");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return DurableChatAgent;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
//#endregion
|
|
54
|
+
export { withDurableChat };
|
|
55
|
+
//# sourceMappingURL=forever.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"forever.js","names":[],"sources":["../../src/experimental/forever.ts"],"sourcesContent":["/**\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n * !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!\n * !! !!\n * !! This API is under active development and WILL break between !!\n * !! releases. Method names, types, behavior, and the mixin signature !!\n * !! are all subject to change without notice. !!\n * !! !!\n * !! If you use this, pin your @cloudflare/ai-chat version and expect !!\n * !! to rewrite your code when upgrading. !!\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n *\n * Experimental mixin for durable chat streaming.\n *\n * Usage:\n * import { AIChatAgent } from \"@cloudflare/ai-chat\";\n * import { withDurableChat } from \"@cloudflare/ai-chat/experimental/forever\";\n *\n * class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {\n * async onChatMessage(onFinish, options) { ... }\n * }\n *\n * This mixin adds:\n * - keepAlive during streaming — DO stays alive while LLM generates\n * - (planned) getPartialStreamText() — extract partial response from chunks\n * - (planned) onStreamInterrupted() — hook for recovery after eviction\n *\n * @experimental This API is not yet stable and may change.\n */\nimport { keepAlive } from \"agents/experimental/forever\";\nimport type { AIChatAgent } from \"../index\";\n\nconsole.warn(\n \"[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production.\"\n);\n\n// ── Mixin ─────────────────────────────────────────────────────────────\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- mixin constructor constraint\ntype Constructor<T = object> = new (...args: any[]) => T;\n\ntype AIChatAgentLike = Constructor<\n Pick<AIChatAgent, \"scheduleEvery\" | \"cancelSchedule\">\n>;\n\nexport function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase) {\n class DurableChatAgent extends Base {\n /**\n * No-op heartbeat callback. The schedule itself keeps the DO alive;\n * the callback doesn't need to do anything.\n * @internal\n */\n // oxlint-disable-next-line @typescript-eslint/no-empty-function\n _cf_streamKeepAlive() {}\n\n /**\n * Keep the DO alive during streaming.\n * Returns a disposer that cancels the heartbeat schedule.\n */\n async keepAlive(): Promise<() => void> {\n return keepAlive(this, \"_cf_streamKeepAlive\");\n }\n }\n\n return DurableChatAgent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,QAAQ,KACN,oJACD;AAWD,SAAgB,gBAA+C,MAAa;CAC1E,MAAM,yBAAyB,KAAK;;;;;;EAOlC,sBAAsB;;;;;EAMtB,MAAM,YAAiC;AACrC,UAAO,UAAU,MAAM,sBAAsB;;;AAIjD,QAAO"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as ResumableStream } from "./resumable-stream-DqXxQVjf.js";
|
|
1
2
|
import {
|
|
2
3
|
JSONSchema7,
|
|
3
4
|
StreamTextOnFinishCallback,
|
|
@@ -44,6 +45,11 @@ type OnChatMessageOptions = {
|
|
|
44
45
|
*
|
|
45
46
|
* Contains all fields from the request body except `messages` and `clientTools`,
|
|
46
47
|
* which are handled separately.
|
|
48
|
+
*
|
|
49
|
+
* During tool continuations (auto-continue after client tool results), this
|
|
50
|
+
* contains the body from the most recent chat request. The value is persisted
|
|
51
|
+
* to SQLite so it survives Durable Object hibernation. It is cleared when the
|
|
52
|
+
* chat is cleared via `CF_AGENT_CHAT_CLEAR`.
|
|
47
53
|
*/
|
|
48
54
|
body?: Record<string, unknown>;
|
|
49
55
|
};
|
|
@@ -99,22 +105,23 @@ declare class AIChatAgent<
|
|
|
99
105
|
*/
|
|
100
106
|
private _chatMessageAbortControllers;
|
|
101
107
|
/**
|
|
102
|
-
*
|
|
103
|
-
* Stored in memory for quick access; persisted in stream_metadata table.
|
|
108
|
+
* Resumable stream manager -- handles chunk buffering, persistence, and replay.
|
|
104
109
|
* @internal Protected for testing purposes.
|
|
105
110
|
*/
|
|
106
|
-
protected
|
|
107
|
-
/**
|
|
108
|
-
* Request ID associated with the active stream.
|
|
109
|
-
* @internal Protected for testing purposes.
|
|
110
|
-
*/
|
|
111
|
-
protected _activeRequestId: string | null;
|
|
111
|
+
protected _resumableStream: ResumableStream;
|
|
112
112
|
/**
|
|
113
113
|
* The message currently being streamed. Used to apply tool results
|
|
114
114
|
* before the message is persisted.
|
|
115
115
|
* @internal
|
|
116
116
|
*/
|
|
117
117
|
private _streamingMessage;
|
|
118
|
+
/**
|
|
119
|
+
* Tracks the ID of a streaming message that was persisted early due to
|
|
120
|
+
* a tool entering approval-requested state. When set, stream completion
|
|
121
|
+
* updates the existing persisted message instead of appending a new one.
|
|
122
|
+
* @internal
|
|
123
|
+
*/
|
|
124
|
+
private _approvalPersistedMessageId;
|
|
118
125
|
/**
|
|
119
126
|
* Promise that resolves when the current stream completes.
|
|
120
127
|
* Used to wait for message persistence before continuing after tool results.
|
|
@@ -122,23 +129,6 @@ declare class AIChatAgent<
|
|
|
122
129
|
*/
|
|
123
130
|
private _streamCompletionPromise;
|
|
124
131
|
private _streamCompletionResolve;
|
|
125
|
-
/**
|
|
126
|
-
* Current chunk index for the active stream
|
|
127
|
-
*/
|
|
128
|
-
private _streamChunkIndex;
|
|
129
|
-
/**
|
|
130
|
-
* Buffer for stream chunks pending write to SQLite.
|
|
131
|
-
* Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
|
|
132
|
-
*/
|
|
133
|
-
private _chunkBuffer;
|
|
134
|
-
/**
|
|
135
|
-
* Lock to prevent concurrent flush operations
|
|
136
|
-
*/
|
|
137
|
-
private _isFlushingChunks;
|
|
138
|
-
/**
|
|
139
|
-
* Timestamp of the last cleanup operation for old streams
|
|
140
|
-
*/
|
|
141
|
-
private _lastCleanupTime;
|
|
142
132
|
/**
|
|
143
133
|
* Set of connection IDs that are pending stream resume.
|
|
144
134
|
* These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
|
|
@@ -152,62 +142,77 @@ declare class AIChatAgent<
|
|
|
152
142
|
* @internal
|
|
153
143
|
*/
|
|
154
144
|
private _lastClientTools;
|
|
145
|
+
/**
|
|
146
|
+
* Custom body data from the most recent chat request.
|
|
147
|
+
* Stored so it can be passed to onChatMessage during tool continuations.
|
|
148
|
+
* @internal
|
|
149
|
+
*/
|
|
150
|
+
private _lastBody;
|
|
151
|
+
/**
|
|
152
|
+
* Cache of last-persisted JSON for each message ID.
|
|
153
|
+
* Used for incremental persistence: skip SQL writes for unchanged messages.
|
|
154
|
+
* Lost on hibernation, repopulated from SQLite on wake.
|
|
155
|
+
* @internal
|
|
156
|
+
*/
|
|
157
|
+
private _persistedMessageCache;
|
|
158
|
+
/** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
|
|
159
|
+
private static ROW_MAX_BYTES;
|
|
160
|
+
/** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
|
|
161
|
+
private static _byteLength;
|
|
162
|
+
/**
|
|
163
|
+
* Maximum number of messages to keep in SQLite storage.
|
|
164
|
+
* When the conversation exceeds this limit, oldest messages are deleted
|
|
165
|
+
* after each persist. Set to `undefined` (default) for no limit.
|
|
166
|
+
*
|
|
167
|
+
* This controls storage only — it does not affect what's sent to the LLM.
|
|
168
|
+
* Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
|
|
169
|
+
* LLM context separately.
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```typescript
|
|
173
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
174
|
+
* maxPersistedMessages = 100; // Keep last 100 messages in storage
|
|
175
|
+
* }
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
maxPersistedMessages: number | undefined;
|
|
155
179
|
/** Array of chat messages for the current conversation */
|
|
156
180
|
messages: UIMessage[];
|
|
157
181
|
constructor(ctx: AgentContext, env: Env);
|
|
158
|
-
/**
|
|
159
|
-
* Restore active stream state if the agent was restarted during streaming.
|
|
160
|
-
* Called during construction to recover any interrupted streams.
|
|
161
|
-
* Validates stream freshness to avoid sending stale resume notifications.
|
|
162
|
-
* @internal Protected for testing purposes.
|
|
163
|
-
*/
|
|
164
|
-
protected _restoreActiveStream(): void;
|
|
165
182
|
/**
|
|
166
183
|
* Notify a connection about an active stream that can be resumed.
|
|
167
184
|
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
168
|
-
* Uses in-memory state for request ID - no extra DB lookup needed.
|
|
169
185
|
* @param connection - The WebSocket connection to notify
|
|
170
186
|
*/
|
|
171
187
|
private _notifyStreamResuming;
|
|
172
|
-
/**
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
* @param streamId - The stream this chunk belongs to
|
|
182
|
-
* @param body - The serialized chunk body
|
|
183
|
-
* @internal Protected for testing purposes.
|
|
184
|
-
*/
|
|
188
|
+
/** @internal Delegate to _resumableStream */
|
|
189
|
+
protected get _activeStreamId(): string | null;
|
|
190
|
+
/** @internal Delegate to _resumableStream */
|
|
191
|
+
protected get _activeRequestId(): string | null;
|
|
192
|
+
/** @internal Delegate to _resumableStream */
|
|
193
|
+
protected _startStream(requestId: string): string;
|
|
194
|
+
/** @internal Delegate to _resumableStream */
|
|
195
|
+
protected _completeStream(streamId: string): void;
|
|
196
|
+
/** @internal Delegate to _resumableStream */
|
|
185
197
|
protected _storeStreamChunk(streamId: string, body: string): void;
|
|
186
|
-
/**
|
|
187
|
-
* Flush buffered chunks to SQLite in a single batch.
|
|
188
|
-
* Uses a lock to prevent concurrent flush operations.
|
|
189
|
-
* @internal Protected for testing purposes.
|
|
190
|
-
*/
|
|
198
|
+
/** @internal Delegate to _resumableStream */
|
|
191
199
|
protected _flushChunkBuffer(): void;
|
|
200
|
+
/** @internal Delegate to _resumableStream */
|
|
201
|
+
protected _restoreActiveStream(): void;
|
|
202
|
+
/** @internal Delegate to _resumableStream */
|
|
203
|
+
protected _markStreamError(streamId: string): void;
|
|
192
204
|
/**
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
* @
|
|
196
|
-
* @returns The generated stream ID
|
|
197
|
-
* @internal Protected for testing purposes.
|
|
198
|
-
*/
|
|
199
|
-
protected _startStream(requestId: string): string;
|
|
200
|
-
/**
|
|
201
|
-
* Mark a stream as completed and flush any pending chunks.
|
|
202
|
-
* @param streamId - The stream to mark as completed
|
|
203
|
-
* @internal Protected for testing purposes.
|
|
205
|
+
* Restore _lastBody and _lastClientTools from SQLite.
|
|
206
|
+
* Called in the constructor so these values survive DO hibernation.
|
|
207
|
+
* @internal
|
|
204
208
|
*/
|
|
205
|
-
|
|
209
|
+
private _restoreRequestContext;
|
|
206
210
|
/**
|
|
207
|
-
*
|
|
208
|
-
*
|
|
211
|
+
* Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
|
|
212
|
+
* Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
|
|
213
|
+
* @internal
|
|
209
214
|
*/
|
|
210
|
-
private
|
|
215
|
+
private _persistRequestContext;
|
|
211
216
|
private _broadcastChatMessage;
|
|
212
217
|
/**
|
|
213
218
|
* Broadcasts a text event for non-SSE responses.
|
|
@@ -293,6 +298,48 @@ declare class AIChatAgent<
|
|
|
293
298
|
* Removes itemId and reasoningEncryptedContent while preserving other fields.
|
|
294
299
|
*/
|
|
295
300
|
private _stripOpenAIMetadata;
|
|
301
|
+
/**
|
|
302
|
+
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
303
|
+
* Called after each persist to keep storage bounded.
|
|
304
|
+
*/
|
|
305
|
+
private _enforceMaxPersistedMessages;
|
|
306
|
+
/**
|
|
307
|
+
* Enforces SQLite row size limits by compacting tool outputs and text parts
|
|
308
|
+
* when a serialized message exceeds the safety threshold (1.8MB).
|
|
309
|
+
*
|
|
310
|
+
* Only fires in pathological cases (extremely large tool outputs or text).
|
|
311
|
+
* Returns the message unchanged if it fits within limits.
|
|
312
|
+
*
|
|
313
|
+
* Compaction strategy:
|
|
314
|
+
* 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
|
|
315
|
+
* 2. If still too big, truncate text parts from oldest to newest
|
|
316
|
+
* 3. Add metadata so clients can detect compaction
|
|
317
|
+
*
|
|
318
|
+
* @param message - The message to check
|
|
319
|
+
* @returns The message, compacted if necessary
|
|
320
|
+
*/
|
|
321
|
+
private _enforceRowSizeLimit;
|
|
322
|
+
/**
|
|
323
|
+
* Truncates text parts in a message to fit within the row size limit.
|
|
324
|
+
* Truncates from the first text part forward, keeping the last text part
|
|
325
|
+
* as intact as possible (it is usually the most relevant).
|
|
326
|
+
*/
|
|
327
|
+
private _truncateTextParts;
|
|
328
|
+
/**
|
|
329
|
+
* Shared helper for finding a tool part by toolCallId and applying an update.
|
|
330
|
+
* Handles both streaming (in-memory) and persisted (SQLite) messages.
|
|
331
|
+
*
|
|
332
|
+
* Checks _streamingMessage first (tool results/approvals can arrive while
|
|
333
|
+
* the AI is still streaming), then retries persisted messages with backoff
|
|
334
|
+
* in case streaming completes between attempts.
|
|
335
|
+
*
|
|
336
|
+
* @param toolCallId - The tool call ID to find
|
|
337
|
+
* @param callerName - Name for log messages (e.g. "_applyToolResult")
|
|
338
|
+
* @param matchStates - Which tool part states to match
|
|
339
|
+
* @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
|
|
340
|
+
* @returns true if the update was applied, false if not found or state didn't match
|
|
341
|
+
*/
|
|
342
|
+
private _findAndUpdateToolPart;
|
|
296
343
|
/**
|
|
297
344
|
* Applies a tool result to an existing assistant message.
|
|
298
345
|
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
@@ -300,16 +347,13 @@ declare class AIChatAgent<
|
|
|
300
347
|
* the update to all clients.
|
|
301
348
|
*
|
|
302
349
|
* @param toolCallId - The tool call ID this result is for
|
|
303
|
-
* @param
|
|
350
|
+
* @param _toolName - The name of the tool (unused, kept for API compat)
|
|
304
351
|
* @param output - The output from the tool execution
|
|
305
352
|
* @returns true if the result was applied, false if the message was not found
|
|
306
353
|
*/
|
|
307
354
|
private _applyToolResult;
|
|
308
355
|
private _streamSSEReply;
|
|
309
356
|
private _sendPlaintextReply;
|
|
310
|
-
private updateDynamicToolPart;
|
|
311
|
-
private updateToolPart;
|
|
312
|
-
private updateMessageMetadata;
|
|
313
357
|
/**
|
|
314
358
|
* Applies a tool approval response from the client, updating the persisted message.
|
|
315
359
|
* This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
|
|
@@ -321,12 +365,6 @@ declare class AIChatAgent<
|
|
|
321
365
|
*/
|
|
322
366
|
private _applyToolApproval;
|
|
323
367
|
private _reply;
|
|
324
|
-
/**
|
|
325
|
-
* Mark a stream as errored and clean up state.
|
|
326
|
-
* @param streamId - The stream to mark as errored
|
|
327
|
-
* @internal Protected for testing purposes.
|
|
328
|
-
*/
|
|
329
|
-
protected _markStreamError(streamId: string): void;
|
|
330
368
|
/**
|
|
331
369
|
* For the given message id, look up its associated AbortController
|
|
332
370
|
* If the AbortController does not exist, create and store one in memory
|