agents 0.0.113 → 0.1.1
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/README.md +31 -7
- package/dist/ai-chat-agent.d.ts +7 -6
- package/dist/ai-chat-agent.js +140 -47
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration.d.ts +152 -0
- package/dist/ai-chat-v5-migration.js +19 -0
- package/dist/ai-chat-v5-migration.js.map +1 -0
- package/dist/ai-react.d.ts +57 -69
- package/dist/ai-react.js +144 -37
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +36 -19
- package/dist/ai-types.js +6 -0
- package/dist/chunk-AVYJQSLW.js +17 -0
- package/dist/chunk-AVYJQSLW.js.map +1 -0
- package/dist/{chunk-PVQZBKN7.js → chunk-LL2AFX7V.js} +5 -2
- package/dist/chunk-LL2AFX7V.js.map +1 -0
- package/dist/{chunk-DQJFYHG3.js → chunk-PNF6ZMUA.js} +69 -63
- package/dist/chunk-PNF6ZMUA.js.map +1 -0
- package/dist/{chunk-KUH345EY.js → chunk-QEVM4BVL.js} +5 -5
- package/dist/chunk-QEVM4BVL.js.map +1 -0
- package/dist/chunk-UJVEAURM.js +150 -0
- package/dist/chunk-UJVEAURM.js.map +1 -0
- package/dist/{chunk-EM3J4KV7.js → chunk-VYENMKFS.js} +17 -3
- package/dist/chunk-VYENMKFS.js.map +1 -0
- package/dist/{client-DgyzBU_8.d.ts → client-CcIORE73.d.ts} +17 -11
- package/dist/client.js +2 -1
- package/dist/index.d.ts +13 -5
- package/dist/index.js +7 -4
- package/dist/mcp/client.d.ts +1 -1
- package/dist/mcp/client.js +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
- package/dist/mcp/do-oauth-client-provider.js +1 -1
- package/dist/mcp/index.d.ts +2 -2
- package/dist/mcp/index.js +5 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.js +5 -4
- package/dist/react.d.ts +2 -1
- package/dist/react.js +7 -5
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +76 -2
- package/dist/schedule.js +15 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +10 -5
- package/src/index.ts +89 -71
- package/dist/chunk-DQJFYHG3.js.map +0 -1
- package/dist/chunk-EM3J4KV7.js.map +0 -1
- package/dist/chunk-KUH345EY.js.map +0 -1
- package/dist/chunk-PVQZBKN7.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
### 🧠 `agents` - A Framework for Digital Intelligence
|
|
2
2
|
|
|
3
|
-

|
|
4
4
|
|
|
5
5
|
Welcome to a new chapter in software development, where AI agents persist, think, and act with purpose. The `agents` framework creates an environment where artificial intelligence can flourish - maintaining state, engaging in meaningful interactions, and evolving over time.
|
|
6
6
|
|
|
@@ -166,7 +166,7 @@ export class DialogueAgent extends Agent {
|
|
|
166
166
|
}
|
|
167
167
|
```
|
|
168
168
|
|
|
169
|
-
#### Client
|
|
169
|
+
#### Client Communication
|
|
170
170
|
|
|
171
171
|
For direct connection to your agent:
|
|
172
172
|
|
|
@@ -317,20 +317,37 @@ Create meaningful conversations with intelligence:
|
|
|
317
317
|
```ts
|
|
318
318
|
import { AIChatAgent } from "agents/ai-chat-agent";
|
|
319
319
|
import { openai } from "@ai-sdk/openai";
|
|
320
|
+
import { streamText, generateText, createDataStreamResponse } from "ai";
|
|
320
321
|
|
|
321
322
|
export class DialogueAgent extends AIChatAgent {
|
|
322
323
|
async onChatMessage(onFinish) {
|
|
324
|
+
// Option 1: Streaming responses (recommended for real-time interaction)
|
|
323
325
|
return createDataStreamResponse({
|
|
324
326
|
execute: async (dataStream) => {
|
|
325
327
|
const stream = streamText({
|
|
326
328
|
model: openai("gpt-4o"),
|
|
327
329
|
messages: this.messages,
|
|
328
|
-
|
|
330
|
+
// Optional: onFinish is invoked by the AI SDK when generation completes.
|
|
331
|
+
// Persistence is handled automatically by AIChatAgent after streaming completes.
|
|
332
|
+
onFinish
|
|
329
333
|
});
|
|
330
334
|
|
|
331
335
|
stream.mergeIntoDataStream(dataStream);
|
|
332
336
|
}
|
|
333
337
|
});
|
|
338
|
+
|
|
339
|
+
// Option 2: Non-streaming responses (simpler, but no real-time updates)
|
|
340
|
+
// const result = await generateText({
|
|
341
|
+
// model: openai("gpt-4o"),
|
|
342
|
+
// messages: this.messages,
|
|
343
|
+
// });
|
|
344
|
+
//
|
|
345
|
+
// // Optional: you can call onFinish here for custom side effects. Message
|
|
346
|
+
// // persistence is still handled automatically by AIChatAgent.
|
|
347
|
+
// await onFinish?.(result);
|
|
348
|
+
// return new Response(result.text, {
|
|
349
|
+
// headers: { 'Content-Type': 'text/plain' }
|
|
350
|
+
// });
|
|
334
351
|
}
|
|
335
352
|
}
|
|
336
353
|
```
|
|
@@ -363,7 +380,14 @@ function ChatInterface() {
|
|
|
363
380
|
{messages.map((message) => (
|
|
364
381
|
<div key={message.id} className="message">
|
|
365
382
|
<div className="role">{message.role}</div>
|
|
366
|
-
<div className="content">
|
|
383
|
+
<div className="content">
|
|
384
|
+
{message.parts.map((part, i) => {
|
|
385
|
+
if (part.type === "text")
|
|
386
|
+
return <span key={i}>{part.text}</span>;
|
|
387
|
+
// Render other part types (e.g., files, tool calls) as desired
|
|
388
|
+
return null;
|
|
389
|
+
})}
|
|
390
|
+
</div>
|
|
367
391
|
</div>
|
|
368
392
|
))}
|
|
369
393
|
</div>
|
|
@@ -488,7 +512,7 @@ import { generateText } from "ai";
|
|
|
488
512
|
// Convert MCP tools for AI use
|
|
489
513
|
const result = await generateText({
|
|
490
514
|
model: openai("gpt-4"),
|
|
491
|
-
tools: client.
|
|
515
|
+
tools: client.getAITools(),
|
|
492
516
|
prompt: "What's the weather in Tokyo?"
|
|
493
517
|
});
|
|
494
518
|
```
|
|
@@ -524,8 +548,8 @@ Welcome to the future of intelligent agents. Create something meaningful. 🌟
|
|
|
524
548
|
Contributions are welcome, but are especially welcome when:
|
|
525
549
|
|
|
526
550
|
- You have opened an issue as a Request for Comment (RFC) to discuss your proposal, show your thinking, and iterate together.
|
|
527
|
-
-
|
|
528
|
-
- You're willing to accept feedback and make sure the changes fit the goals of the `agents`
|
|
551
|
+
- Not "AI slop": LLMs are powerful tools, but contributions entirely authored by vibe coding are unlikely to meet the quality bar, and will be rejected.
|
|
552
|
+
- You're willing to accept feedback and make sure the changes fit the goals of the `agents` SDK. Not everything will, and that's OK.
|
|
529
553
|
|
|
530
554
|
Small fixes, type bugs, and documentation improvements can be raised directly as PRs.
|
|
531
555
|
|
package/dist/ai-chat-agent.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { UIMessage, StreamTextOnFinishCallback, ToolSet } from "ai";
|
|
2
2
|
import { Agent, AgentContext } from "./index.js";
|
|
3
3
|
import { Connection, WSMessage } from "partyserver";
|
|
4
4
|
import "cloudflare:workers";
|
|
5
5
|
import "@modelcontextprotocol/sdk/client/index.js";
|
|
6
6
|
import "@modelcontextprotocol/sdk/types.js";
|
|
7
|
-
import "./client-
|
|
7
|
+
import "./client-CcIORE73.js";
|
|
8
8
|
import "zod";
|
|
9
9
|
import "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
10
10
|
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
@@ -13,6 +13,7 @@ import "./mcp/do-oauth-client-provider.js";
|
|
|
13
13
|
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
14
14
|
import "@modelcontextprotocol/sdk/shared/auth.js";
|
|
15
15
|
import "./observability/index.js";
|
|
16
|
+
import "./ai-types.js";
|
|
16
17
|
|
|
17
18
|
/**
|
|
18
19
|
* Extension of Agent with built-in chat capabilities
|
|
@@ -28,7 +29,7 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
28
29
|
*/
|
|
29
30
|
private _chatMessageAbortControllers;
|
|
30
31
|
/** Array of chat messages for the current conversation */
|
|
31
|
-
messages:
|
|
32
|
+
messages: UIMessage[];
|
|
32
33
|
constructor(ctx: AgentContext, env: Env);
|
|
33
34
|
private _broadcastChatMessage;
|
|
34
35
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
|
@@ -47,12 +48,12 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
47
48
|
}
|
|
48
49
|
): Promise<Response | undefined>;
|
|
49
50
|
/**
|
|
50
|
-
* Save messages on the server side
|
|
51
|
+
* Save messages on the server side
|
|
51
52
|
* @param messages Chat messages to save
|
|
52
53
|
*/
|
|
53
|
-
saveMessages(messages:
|
|
54
|
+
saveMessages(messages: UIMessage[]): Promise<void>;
|
|
54
55
|
persistMessages(
|
|
55
|
-
messages:
|
|
56
|
+
messages: UIMessage[],
|
|
56
57
|
excludeBroadcastIds?: string[]
|
|
57
58
|
): Promise<void>;
|
|
58
59
|
private _reply;
|
package/dist/ai-chat-agent.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
autoTransformMessages
|
|
3
|
+
} from "./chunk-UJVEAURM.js";
|
|
1
4
|
import {
|
|
2
5
|
Agent
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-PNF6ZMUA.js";
|
|
7
|
+
import "./chunk-VYENMKFS.js";
|
|
8
|
+
import "./chunk-LL2AFX7V.js";
|
|
9
|
+
import "./chunk-QEVM4BVL.js";
|
|
10
|
+
import "./chunk-AVYJQSLW.js";
|
|
7
11
|
|
|
8
12
|
// src/ai-chat-agent.ts
|
|
9
|
-
import { appendResponseMessages } from "ai";
|
|
10
13
|
var decoder = new TextDecoder();
|
|
11
14
|
var AIChatAgent = class extends Agent {
|
|
12
15
|
constructor(ctx, env) {
|
|
@@ -16,9 +19,10 @@ var AIChatAgent = class extends Agent {
|
|
|
16
19
|
message text not null,
|
|
17
20
|
created_at datetime default current_timestamp
|
|
18
21
|
)`;
|
|
19
|
-
|
|
22
|
+
const rawMessages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
|
|
20
23
|
return JSON.parse(row.message);
|
|
21
24
|
});
|
|
25
|
+
this.messages = autoTransformMessages(rawMessages);
|
|
22
26
|
this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
|
|
23
27
|
}
|
|
24
28
|
_broadcastChatMessage(message, exclude) {
|
|
@@ -32,7 +36,7 @@ var AIChatAgent = class extends Agent {
|
|
|
32
36
|
} catch (_error) {
|
|
33
37
|
return;
|
|
34
38
|
}
|
|
35
|
-
if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
|
|
39
|
+
if (data.type === "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */ && data.init.method === "POST") {
|
|
36
40
|
const {
|
|
37
41
|
// method,
|
|
38
42
|
// keepalive,
|
|
@@ -45,14 +49,15 @@ var AIChatAgent = class extends Agent {
|
|
|
45
49
|
// duplex
|
|
46
50
|
} = data.init;
|
|
47
51
|
const { messages } = JSON.parse(body);
|
|
52
|
+
const transformedMessages = autoTransformMessages(messages);
|
|
48
53
|
this._broadcastChatMessage(
|
|
49
54
|
{
|
|
50
|
-
messages,
|
|
51
|
-
type: "cf_agent_chat_messages"
|
|
55
|
+
messages: transformedMessages,
|
|
56
|
+
type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
|
|
52
57
|
},
|
|
53
58
|
[connection.id]
|
|
54
59
|
);
|
|
55
|
-
await this.persistMessages(
|
|
60
|
+
await this.persistMessages(transformedMessages, [connection.id]);
|
|
56
61
|
this.observability?.emit(
|
|
57
62
|
{
|
|
58
63
|
displayMessage: "Chat message request",
|
|
@@ -67,12 +72,7 @@ var AIChatAgent = class extends Agent {
|
|
|
67
72
|
const abortSignal = this._getAbortSignal(chatMessageId);
|
|
68
73
|
return this._tryCatchChat(async () => {
|
|
69
74
|
const response = await this.onChatMessage(
|
|
70
|
-
async (
|
|
71
|
-
const finalMessages = appendResponseMessages({
|
|
72
|
-
messages,
|
|
73
|
-
responseMessages: response2.messages
|
|
74
|
-
});
|
|
75
|
-
await this.persistMessages(finalMessages, [connection.id]);
|
|
75
|
+
async (_finishResult) => {
|
|
76
76
|
this._removeAbortController(chatMessageId);
|
|
77
77
|
this.observability?.emit(
|
|
78
78
|
{
|
|
@@ -98,26 +98,27 @@ var AIChatAgent = class extends Agent {
|
|
|
98
98
|
body: "No response was generated by the agent.",
|
|
99
99
|
done: true,
|
|
100
100
|
id: data.id,
|
|
101
|
-
type: "cf_agent_use_chat_response"
|
|
101
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
102
102
|
},
|
|
103
103
|
[connection.id]
|
|
104
104
|
);
|
|
105
105
|
}
|
|
106
106
|
});
|
|
107
107
|
}
|
|
108
|
-
if (data.type === "cf_agent_chat_clear") {
|
|
108
|
+
if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
|
|
109
109
|
this._destroyAbortControllers();
|
|
110
110
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
111
111
|
this.messages = [];
|
|
112
112
|
this._broadcastChatMessage(
|
|
113
113
|
{
|
|
114
|
-
type: "cf_agent_chat_clear"
|
|
114
|
+
type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
|
|
115
115
|
},
|
|
116
116
|
[connection.id]
|
|
117
117
|
);
|
|
118
|
-
} else if (data.type === "cf_agent_chat_messages") {
|
|
119
|
-
|
|
120
|
-
|
|
118
|
+
} else if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
|
|
119
|
+
const transformedMessages = autoTransformMessages(data.messages);
|
|
120
|
+
await this.persistMessages(transformedMessages, [connection.id]);
|
|
121
|
+
} else if (data.type === "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */) {
|
|
121
122
|
this._cancelChatRequest(data.id);
|
|
122
123
|
}
|
|
123
124
|
}
|
|
@@ -153,24 +154,11 @@ var AIChatAgent = class extends Agent {
|
|
|
153
154
|
);
|
|
154
155
|
}
|
|
155
156
|
/**
|
|
156
|
-
* Save messages on the server side
|
|
157
|
+
* Save messages on the server side
|
|
157
158
|
* @param messages Chat messages to save
|
|
158
159
|
*/
|
|
159
160
|
async saveMessages(messages) {
|
|
160
161
|
await this.persistMessages(messages);
|
|
161
|
-
const response = await this.onChatMessage(async ({ response: response2 }) => {
|
|
162
|
-
const finalMessages = appendResponseMessages({
|
|
163
|
-
messages,
|
|
164
|
-
responseMessages: response2.messages
|
|
165
|
-
});
|
|
166
|
-
await this.persistMessages(finalMessages, []);
|
|
167
|
-
});
|
|
168
|
-
if (response) {
|
|
169
|
-
for await (const chunk of response.body) {
|
|
170
|
-
decoder.decode(chunk);
|
|
171
|
-
}
|
|
172
|
-
response.body?.cancel();
|
|
173
|
-
}
|
|
174
162
|
}
|
|
175
163
|
async persistMessages(messages, excludeBroadcastIds = []) {
|
|
176
164
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
@@ -181,28 +169,133 @@ var AIChatAgent = class extends Agent {
|
|
|
181
169
|
this._broadcastChatMessage(
|
|
182
170
|
{
|
|
183
171
|
messages,
|
|
184
|
-
type: "cf_agent_chat_messages"
|
|
172
|
+
type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
|
|
185
173
|
},
|
|
186
174
|
excludeBroadcastIds
|
|
187
175
|
);
|
|
188
176
|
}
|
|
189
177
|
async _reply(id, response) {
|
|
190
178
|
return this._tryCatchChat(async () => {
|
|
191
|
-
|
|
192
|
-
const body = decoder.decode(chunk);
|
|
179
|
+
if (!response.body) {
|
|
193
180
|
this._broadcastChatMessage({
|
|
194
|
-
body,
|
|
195
|
-
done:
|
|
181
|
+
body: "",
|
|
182
|
+
done: true,
|
|
196
183
|
id,
|
|
197
|
-
type: "cf_agent_use_chat_response"
|
|
184
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
198
185
|
});
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const reader = response.body.getReader();
|
|
189
|
+
let fullResponseText = "";
|
|
190
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
191
|
+
try {
|
|
192
|
+
while (true) {
|
|
193
|
+
const { done, value } = await reader.read();
|
|
194
|
+
if (done) {
|
|
195
|
+
this._broadcastChatMessage({
|
|
196
|
+
body: "",
|
|
197
|
+
done: true,
|
|
198
|
+
id,
|
|
199
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
200
|
+
});
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
const chunk = decoder.decode(value);
|
|
204
|
+
const contentType = response.headers.get("content-type") || "";
|
|
205
|
+
const isSSE = contentType.includes("text/event-stream");
|
|
206
|
+
if (isSSE) {
|
|
207
|
+
const lines = chunk.split("\n");
|
|
208
|
+
for (const line of lines) {
|
|
209
|
+
if (line.startsWith("data: ") && line !== "data: [DONE]") {
|
|
210
|
+
try {
|
|
211
|
+
const data = JSON.parse(line.slice(6));
|
|
212
|
+
switch (data.type) {
|
|
213
|
+
// SSE event signaling the tool input is ready. We track by
|
|
214
|
+
// `toolCallId` so we can persist it as a tool part in the message.
|
|
215
|
+
case "tool-input-available": {
|
|
216
|
+
const { toolCallId, toolName, input } = data;
|
|
217
|
+
toolCalls.set(toolCallId, {
|
|
218
|
+
toolCallId,
|
|
219
|
+
toolName,
|
|
220
|
+
input,
|
|
221
|
+
type: toolName ? `tool-${toolName}` : "dynamic-tool",
|
|
222
|
+
state: "input-available"
|
|
223
|
+
});
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
// SSE event signaling the tool output is ready. We should've
|
|
227
|
+
// already received the input in a previous event so an entry
|
|
228
|
+
// with `toolCallId` should already be present
|
|
229
|
+
case "tool-output-available": {
|
|
230
|
+
const { toolCallId, output, isError, errorText } = data;
|
|
231
|
+
const toolPart = toolCalls.get(toolCallId);
|
|
232
|
+
if (toolPart)
|
|
233
|
+
toolCalls.set(toolCallId, {
|
|
234
|
+
...toolPart,
|
|
235
|
+
output,
|
|
236
|
+
isError,
|
|
237
|
+
errorText,
|
|
238
|
+
state: "output-available"
|
|
239
|
+
});
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
case "error": {
|
|
243
|
+
this._broadcastChatMessage({
|
|
244
|
+
error: true,
|
|
245
|
+
body: data.errorText ?? JSON.stringify(data),
|
|
246
|
+
done: false,
|
|
247
|
+
id,
|
|
248
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
249
|
+
});
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
case "text-delta": {
|
|
253
|
+
if (data.delta) fullResponseText += data.delta;
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
this._broadcastChatMessage({
|
|
258
|
+
body: JSON.stringify(data),
|
|
259
|
+
done: false,
|
|
260
|
+
id,
|
|
261
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
262
|
+
});
|
|
263
|
+
} catch (_e) {
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
if (chunk.length > 0) {
|
|
269
|
+
fullResponseText += chunk;
|
|
270
|
+
this._broadcastChatMessage({
|
|
271
|
+
body: JSON.stringify({ type: "text-delta", delta: chunk }),
|
|
272
|
+
done: false,
|
|
273
|
+
id,
|
|
274
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
} finally {
|
|
280
|
+
reader.releaseLock();
|
|
199
281
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
id,
|
|
204
|
-
type: "cf_agent_use_chat_response"
|
|
282
|
+
const messageParts = [];
|
|
283
|
+
Array.from(toolCalls.values()).forEach((t) => {
|
|
284
|
+
messageParts.push(t);
|
|
205
285
|
});
|
|
286
|
+
if (fullResponseText.trim()) {
|
|
287
|
+
messageParts.push({ type: "text", text: fullResponseText });
|
|
288
|
+
}
|
|
289
|
+
if (messageParts.length > 0) {
|
|
290
|
+
await this.persistMessages([
|
|
291
|
+
...this.messages,
|
|
292
|
+
{
|
|
293
|
+
id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
|
|
294
|
+
role: "assistant",
|
|
295
|
+
parts: messageParts
|
|
296
|
+
}
|
|
297
|
+
]);
|
|
298
|
+
}
|
|
206
299
|
});
|
|
207
300
|
}
|
|
208
301
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-chat-agent.ts"],"sourcesContent":["import type {\n Message as ChatMessage,\n StreamTextOnFinishCallback,\n ToolSet\n} from \"ai\";\nimport { appendResponseMessages } from \"ai\";\nimport { Agent, type AgentContext, type Connection, type WSMessage } from \"./\";\nimport type { IncomingMessage, OutgoingMessage } from \"./ai-types\";\n\nconst decoder = new TextDecoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<Env = unknown, State = unknown> extends Agent<\n Env,\n State\n> {\n /**\n * Map of message `id`s to `AbortController`s\n * useful to propagate request cancellation signals for any external calls made by the agent\n */\n private _chatMessageAbortControllers: Map<string, AbortController>;\n /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n this.messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n\n this._chatMessageAbortControllers = new Map();\n }\n\n private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n override async onMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (\n data.type === \"cf_agent_use_chat_request\" &&\n data.init.method === \"POST\"\n ) {\n const {\n // method,\n // keepalive,\n // headers,\n body // we're reading this\n //\n // // these might not exist?\n // dispatcher,\n // duplex\n } = data.init;\n const { messages } = JSON.parse(body as string);\n this._broadcastChatMessage(\n {\n messages,\n type: \"cf_agent_chat_messages\"\n },\n [connection.id]\n );\n\n await this.persistMessages(messages, [connection.id]);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message request\",\n id: data.id,\n payload: {},\n timestamp: Date.now(),\n type: \"message:request\"\n },\n this.ctx\n );\n\n const chatMessageId = data.id;\n const abortSignal = this._getAbortSignal(chatMessageId);\n\n return this._tryCatchChat(async () => {\n const response = await this.onChatMessage(\n async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages\n });\n\n await this.persistMessages(finalMessages, [connection.id]);\n this._removeAbortController(chatMessageId);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message response\",\n id: data.id,\n payload: {},\n timestamp: Date.now(),\n type: \"message:response\"\n },\n this.ctx\n );\n },\n abortSignal ? { abortSignal } : undefined\n );\n\n if (response) {\n await this._reply(data.id, response);\n } else {\n // Log a warning for observability\n console.warn(\n `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`\n );\n // Send a fallback message to the client\n this._broadcastChatMessage(\n {\n body: \"No response was generated by the agent.\",\n done: true,\n id: data.id,\n type: \"cf_agent_use_chat_response\"\n },\n [connection.id]\n );\n }\n });\n }\n if (data.type === \"cf_agent_chat_clear\") {\n this._destroyAbortControllers();\n this.sql`delete from cf_ai_chat_agent_messages`;\n this.messages = [];\n this._broadcastChatMessage(\n {\n type: \"cf_agent_chat_clear\"\n },\n [connection.id]\n );\n } else if (data.type === \"cf_agent_chat_messages\") {\n // replace the messages with the new ones\n await this.persistMessages(data.messages, [connection.id]);\n } else if (data.type === \"cf_agent_chat_request_cancel\") {\n // propagate an abort signal for the associated request\n this._cancelChatRequest(data.id);\n }\n }\n }\n\n override async onRequest(request: Request): Promise<Response> {\n return this._tryCatchChat(() => {\n const url = new URL(request.url);\n if (url.pathname.endsWith(\"/get-messages\")) {\n const messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n return Response.json(messages);\n }\n return super.onRequest(request);\n });\n }\n\n private async _tryCatchChat<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @param options.signal A signal to pass to any child requests which can be used to cancel them\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onFinish: StreamTextOnFinishCallback<ToolSet>,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n options?: { abortSignal: AbortSignal | undefined }\n ): Promise<Response | undefined> {\n throw new Error(\n \"recieved a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Save messages on the server side and trigger AI response\n * @param messages Chat messages to save\n */\n async saveMessages(messages: ChatMessage[]) {\n await this.persistMessages(messages);\n const response = await this.onChatMessage(async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages\n });\n\n await this.persistMessages(finalMessages, []);\n });\n if (response) {\n // we're just going to drain the body\n // @ts-ignore TODO: fix this type error\n for await (const chunk of response.body!) {\n decoder.decode(chunk);\n }\n response.body?.cancel();\n }\n }\n\n async persistMessages(\n messages: ChatMessage[],\n excludeBroadcastIds: string[] = []\n ) {\n this.sql`delete from cf_ai_chat_agent_messages`;\n for (const message of messages) {\n this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${\n message.id\n },${JSON.stringify(message)})`;\n }\n this.messages = messages;\n this._broadcastChatMessage(\n {\n messages: messages,\n type: \"cf_agent_chat_messages\"\n },\n excludeBroadcastIds\n );\n }\n\n private async _reply(id: string, response: Response) {\n // now take chunks out from dataStreamResponse and send them to the client\n return this._tryCatchChat(async () => {\n // @ts-expect-error TODO: fix this type error\n for await (const chunk of response.body!) {\n const body = decoder.decode(chunk);\n\n this._broadcastChatMessage({\n body,\n done: false,\n id,\n type: \"cf_agent_use_chat_response\"\n });\n }\n\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: \"cf_agent_use_chat_response\"\n });\n });\n }\n\n /**\n * For the given message id, look up its associated AbortController\n * If the AbortController does not exist, create and store one in memory\n *\n * returns the AbortSignal associated with the AbortController\n */\n private _getAbortSignal(id: string): AbortSignal | undefined {\n // Defensive check, since we're coercing message types at the moment\n if (typeof id !== \"string\") {\n return undefined;\n }\n\n if (!this._chatMessageAbortControllers.has(id)) {\n this._chatMessageAbortControllers.set(id, new AbortController());\n }\n\n return this._chatMessageAbortControllers.get(id)?.signal;\n }\n\n /**\n * Remove an abort controller from the cache of pending message responses\n */\n private _removeAbortController(id: string) {\n this._chatMessageAbortControllers.delete(id);\n }\n\n /**\n * Propagate an abort signal for any requests associated with the given message id\n */\n private _cancelChatRequest(id: string) {\n if (this._chatMessageAbortControllers.has(id)) {\n const abortController = this._chatMessageAbortControllers.get(id);\n abortController?.abort();\n }\n }\n\n /**\n * Abort all pending requests and clear the cache of AbortControllers\n */\n private _destroyAbortControllers() {\n for (const controller of this._chatMessageAbortControllers.values()) {\n controller?.abort();\n }\n this._chatMessageAbortControllers.clear();\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests\n */\n async destroy() {\n this._destroyAbortControllers();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAS,8BAA8B;AAIvC,IAAM,UAAU,IAAI,YAAY;AAMzB,IAAM,cAAN,cAA0D,MAG/D;AAAA,EAQA,YAAY,KAAmB,KA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../src/ai-chat-agent.ts"],"sourcesContent":["import type {\n UIMessage as ChatMessage,\n StreamTextOnFinishCallback,\n ToolSet\n} from \"ai\";\nimport { Agent, type AgentContext, type Connection, type WSMessage } from \"./\";\nimport {\n MessageType,\n type IncomingMessage,\n type OutgoingMessage\n} from \"./ai-types\";\nimport { autoTransformMessages } from \"./ai-chat-v5-migration\";\n\nconst decoder = new TextDecoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<Env = unknown, State = unknown> extends Agent<\n Env,\n State\n> {\n /**\n * Map of message `id`s to `AbortController`s\n * useful to propagate request cancellation signals for any external calls made by the agent\n */\n private _chatMessageAbortControllers: Map<string, AbortController>;\n /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n\n // Load messages and automatically transform them to v5 format\n const rawMessages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n\n // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n this.messages = autoTransformMessages(rawMessages);\n\n this._chatMessageAbortControllers = new Map();\n }\n\n private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n override async onMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (\n data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST &&\n data.init.method === \"POST\"\n ) {\n const {\n // method,\n // keepalive,\n // headers,\n body // we're reading this\n //\n // // these might not exist?\n // dispatcher,\n // duplex\n } = data.init;\n const { messages } = JSON.parse(body as string);\n\n // Automatically transform any incoming messages\n const transformedMessages = autoTransformMessages(messages);\n\n this._broadcastChatMessage(\n {\n messages: transformedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n [connection.id]\n );\n\n await this.persistMessages(transformedMessages, [connection.id]);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message request\",\n id: data.id,\n payload: {},\n timestamp: Date.now(),\n type: \"message:request\"\n },\n this.ctx\n );\n\n const chatMessageId = data.id;\n const abortSignal = this._getAbortSignal(chatMessageId);\n\n return this._tryCatchChat(async () => {\n const response = await this.onChatMessage(\n async (_finishResult) => {\n this._removeAbortController(chatMessageId);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message response\",\n id: data.id,\n payload: {},\n timestamp: Date.now(),\n type: \"message:response\"\n },\n this.ctx\n );\n\n // Note: Message persistence now happens in the _reply method\n // after the complete response text has been accumulated\n },\n abortSignal ? { abortSignal } : undefined\n );\n\n if (response) {\n await this._reply(data.id, response);\n } else {\n // Log a warning for observability\n console.warn(\n `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`\n );\n // Send a fallback message to the client\n this._broadcastChatMessage(\n {\n body: \"No response was generated by the agent.\",\n done: true,\n id: data.id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n },\n [connection.id]\n );\n }\n });\n }\n if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {\n this._destroyAbortControllers();\n this.sql`delete from cf_ai_chat_agent_messages`;\n this.messages = [];\n this._broadcastChatMessage(\n {\n type: MessageType.CF_AGENT_CHAT_CLEAR\n },\n [connection.id]\n );\n } else if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {\n // replace the messages with the new ones, automatically transformed\n const transformedMessages = autoTransformMessages(data.messages);\n await this.persistMessages(transformedMessages, [connection.id]);\n } else if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {\n // propagate an abort signal for the associated request\n this._cancelChatRequest(data.id);\n }\n }\n }\n\n override async onRequest(request: Request): Promise<Response> {\n return this._tryCatchChat(() => {\n const url = new URL(request.url);\n if (url.pathname.endsWith(\"/get-messages\")) {\n const messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n return Response.json(messages);\n }\n return super.onRequest(request);\n });\n }\n\n private async _tryCatchChat<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @param options.signal A signal to pass to any child requests which can be used to cancel them\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onFinish: StreamTextOnFinishCallback<ToolSet>,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n options?: { abortSignal: AbortSignal | undefined }\n ): Promise<Response | undefined> {\n throw new Error(\n \"recieved a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Save messages on the server side\n * @param messages Chat messages to save\n */\n async saveMessages(messages: ChatMessage[]) {\n await this.persistMessages(messages);\n }\n\n async persistMessages(\n messages: ChatMessage[],\n excludeBroadcastIds: string[] = []\n ) {\n this.sql`delete from cf_ai_chat_agent_messages`;\n for (const message of messages) {\n this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${\n message.id\n },${JSON.stringify(message)})`;\n }\n this.messages = messages;\n this._broadcastChatMessage(\n {\n messages: messages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n excludeBroadcastIds\n );\n }\n\n private async _reply(id: string, response: Response) {\n return this._tryCatchChat(async () => {\n if (!response.body) {\n // Send empty response if no body\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n return;\n }\n\n const reader = response.body.getReader();\n let fullResponseText = \"\"; // Accumulate the assistant's response text\n // Track tool calls by toolCallid, so we can persist them as parts later\n const toolCalls = new Map<\n string,\n {\n type: string;\n state: string;\n toolCallId: string;\n toolName: string;\n input?: unknown;\n output?: unknown;\n isError?: boolean;\n errorText?: string;\n }\n >();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // Send final completion signal\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n break;\n }\n\n const chunk = decoder.decode(value);\n\n // Determine response format based on content-type\n const contentType = response.headers.get(\"content-type\") || \"\";\n const isSSE = contentType.includes(\"text/event-stream\");\n\n if (isSSE) {\n // Parse AI SDK v5 SSE format and extract text deltas\n const lines = chunk.split(\"\\n\");\n for (const line of lines) {\n if (line.startsWith(\"data: \") && line !== \"data: [DONE]\") {\n try {\n const data = JSON.parse(line.slice(6)); // Remove 'data: ' prefix\n\n switch (data.type) {\n // SSE event signaling the tool input is ready. We track by\n // `toolCallId` so we can persist it as a tool part in the message.\n case \"tool-input-available\": {\n const { toolCallId, toolName, input } = data;\n toolCalls.set(toolCallId, {\n toolCallId,\n toolName,\n input,\n type: toolName ? `tool-${toolName}` : \"dynamic-tool\",\n state: \"input-available\"\n });\n break;\n }\n\n // SSE event signaling the tool output is ready. We should've\n // already received the input in a previous event so an entry\n // with `toolCallId` should already be present\n case \"tool-output-available\": {\n const { toolCallId, output, isError, errorText } = data;\n const toolPart = toolCalls.get(toolCallId);\n if (toolPart)\n toolCalls.set(toolCallId, {\n ...toolPart,\n output,\n isError,\n errorText,\n state: \"output-available\"\n });\n break;\n }\n\n case \"error\": {\n // Non-tool errors, we set `error: true` and terminate early\n this._broadcastChatMessage({\n error: true,\n body: data.errorText ?? JSON.stringify(data),\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n return;\n }\n\n case \"text-delta\": {\n if (data.delta) fullResponseText += data.delta;\n break;\n }\n }\n\n // Always forward the raw part to the client\n this._broadcastChatMessage({\n body: JSON.stringify(data),\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n } catch (_e) {\n // Skip malformed JSON lines silently\n }\n }\n }\n } else {\n // Handle plain text responses (e.g., from generateText)\n // Treat the entire chunk as a text delta to preserve exact formatting\n if (chunk.length > 0) {\n fullResponseText += chunk;\n // Synthesize a text-delta event so clients can stream-render\n this._broadcastChatMessage({\n body: JSON.stringify({ type: \"text-delta\", delta: chunk }),\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n // After streaming is complete, persist the complete assistant's response\n const messageParts: ChatMessage[\"parts\"] = [];\n\n Array.from(toolCalls.values()).forEach((t) => {\n messageParts.push(t as ChatMessage[\"parts\"][number]);\n });\n\n if (fullResponseText.trim()) {\n messageParts.push({ type: \"text\", text: fullResponseText });\n }\n\n if (messageParts.length > 0) {\n await this.persistMessages([\n ...this.messages,\n {\n id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,\n role: \"assistant\",\n parts: messageParts\n }\n ]);\n }\n });\n }\n\n /**\n * For the given message id, look up its associated AbortController\n * If the AbortController does not exist, create and store one in memory\n *\n * returns the AbortSignal associated with the AbortController\n */\n private _getAbortSignal(id: string): AbortSignal | undefined {\n // Defensive check, since we're coercing message types at the moment\n if (typeof id !== \"string\") {\n return undefined;\n }\n\n if (!this._chatMessageAbortControllers.has(id)) {\n this._chatMessageAbortControllers.set(id, new AbortController());\n }\n\n return this._chatMessageAbortControllers.get(id)?.signal;\n }\n\n /**\n * Remove an abort controller from the cache of pending message responses\n */\n private _removeAbortController(id: string) {\n this._chatMessageAbortControllers.delete(id);\n }\n\n /**\n * Propagate an abort signal for any requests associated with the given message id\n */\n private _cancelChatRequest(id: string) {\n if (this._chatMessageAbortControllers.has(id)) {\n const abortController = this._chatMessageAbortControllers.get(id);\n abortController?.abort();\n }\n }\n\n /**\n * Abort all pending requests and clear the cache of AbortControllers\n */\n private _destroyAbortControllers() {\n for (const controller of this._chatMessageAbortControllers.values()) {\n controller?.abort();\n }\n this._chatMessageAbortControllers.clear();\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests\n */\n async destroy() {\n this._destroyAbortControllers();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAaA,IAAM,UAAU,IAAI,YAAY;AAMzB,IAAM,cAAN,cAA0D,MAG/D;AAAA,EAQA,YAAY,KAAmB,KAAU;AACvC,UAAM,KAAK,GAAG;AACd,SAAK;AAAA;AAAA;AAAA;AAAA;AAOL,UAAM,eACJ,KAAK,gDAAgD,CAAC,GACtD,IAAI,CAAC,QAAQ;AACb,aAAO,KAAK,MAAM,IAAI,OAAiB;AAAA,IACzC,CAAC;AAGD,SAAK,WAAW,sBAAsB,WAAW;AAEjD,SAAK,+BAA+B,oBAAI,IAAI;AAAA,EAC9C;AAAA,EAEQ,sBAAsB,SAA0B,SAAoB;AAC1E,SAAK,UAAU,KAAK,UAAU,OAAO,GAAG,OAAO;AAAA,EACjD;AAAA,EAEA,MAAe,UAAU,YAAwB,SAAoB;AACnE,QAAI,OAAO,YAAY,UAAU;AAC/B,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,OAAO;AAAA,MAC3B,SAAS,QAAQ;AAGf;AAAA,MACF;AACA,UACE,KAAK,wEACL,KAAK,KAAK,WAAW,QACrB;AACA,cAAM;AAAA;AAAA;AAAA;AAAA,UAIJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAKF,IAAI,KAAK;AACT,cAAM,EAAE,SAAS,IAAI,KAAK,MAAM,IAAc;AAG9C,cAAM,sBAAsB,sBAAsB,QAAQ;AAE1D,aAAK;AAAA,UACH;AAAA,YACE,UAAU;AAAA,YACV;AAAA,UACF;AAAA,UACA,CAAC,WAAW,EAAE;AAAA,QAChB;AAEA,cAAM,KAAK,gBAAgB,qBAAqB,CAAC,WAAW,EAAE,CAAC;AAE/D,aAAK,eAAe;AAAA,UAClB;AAAA,YACE,gBAAgB;AAAA,YAChB,IAAI,KAAK;AAAA,YACT,SAA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H;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,gBAAgB,IAAqC;AAE3D,QAAI,OAAO,OAAO,UAAU;AAC1B,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,KAAK,6BAA6B,IAAI,EAAE,GAAG;AAC9C,WAAK,6BAA6B,IAAI,IAAI,IAAI,gBAAgB,CAAC;AAAA,IACjE;AAEA,WAAO,KAAK,6BAA6B,IAAI,EAAE,GAAG;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKQ,uBAAuB,IAAY;AACzC,SAAK,6BAA6B,OAAO,EAAE;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA,EAKQ,mBAAmB,IAAY;AACrC,QAAI,KAAK,6BAA6B,IAAI,EAAE,GAAG;AAC7C,YAAM,kBAAkB,KAAK,6BAA6B,IAAI,EAAE;AAChE,uBAAiB,MAAM;AAAA,IACzB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,2BAA2B;AACjC,eAAW,cAAc,KAAK,6BAA6B,OAAO,GAAG;AACnE,kBAAY,MAAM;AAAA,IACpB;AACA,SAAK,6BAA6B,MAAM;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAU;AACd,SAAK,yBAAyB;AAC9B,UAAM,MAAM,QAAQ;AAAA,EACtB;AACF;","names":[]}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { 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
|
+
* AI SDK v5 Message Part types reference (from official AI SDK documentation)
|
|
9
|
+
*
|
|
10
|
+
* The migration logic below transforms legacy messages to match these official AI SDK v5 formats:
|
|
11
|
+
* - TextUIPart: { type: "text", text: string, state?: "streaming" | "done" }
|
|
12
|
+
* - ReasoningUIPart: { type: "reasoning", text: string, state?: "streaming" | "done", providerMetadata?: Record<string, unknown> }
|
|
13
|
+
* - FileUIPart: { type: "file", mediaType: string, filename?: string, url: string }
|
|
14
|
+
* - 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 }
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Tool invocation from v4 format
|
|
18
|
+
*/
|
|
19
|
+
type ToolInvocation = {
|
|
20
|
+
toolCallId: string;
|
|
21
|
+
toolName: string;
|
|
22
|
+
args: Record<string, unknown>;
|
|
23
|
+
result?: unknown;
|
|
24
|
+
state: "partial-call" | "call" | "result" | "error";
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Legacy part from v4 format
|
|
28
|
+
*/
|
|
29
|
+
type LegacyPart = {
|
|
30
|
+
type: string;
|
|
31
|
+
text?: string;
|
|
32
|
+
url?: string;
|
|
33
|
+
data?: string;
|
|
34
|
+
mimeType?: string;
|
|
35
|
+
mediaType?: string;
|
|
36
|
+
filename?: string;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Legacy message format from AI SDK v4
|
|
40
|
+
*/
|
|
41
|
+
type LegacyMessage = {
|
|
42
|
+
id?: string;
|
|
43
|
+
role: string;
|
|
44
|
+
content: string;
|
|
45
|
+
reasoning?: string;
|
|
46
|
+
toolInvocations?: ToolInvocation[];
|
|
47
|
+
parts?: LegacyPart[];
|
|
48
|
+
[key: string]: unknown;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Corrupt content item
|
|
52
|
+
*/
|
|
53
|
+
type CorruptContentItem = {
|
|
54
|
+
type: string;
|
|
55
|
+
text: string;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Corrupted message format - has content as array instead of parts
|
|
59
|
+
*/
|
|
60
|
+
type CorruptArrayMessage = {
|
|
61
|
+
id?: string;
|
|
62
|
+
role: string;
|
|
63
|
+
content: CorruptContentItem[];
|
|
64
|
+
reasoning?: string;
|
|
65
|
+
toolInvocations?: ToolInvocation[];
|
|
66
|
+
[key: string]: unknown;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Union type for messages that could be in any format
|
|
70
|
+
*/
|
|
71
|
+
type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;
|
|
72
|
+
/**
|
|
73
|
+
* Checks if a message is already in the UIMessage format (has parts array)
|
|
74
|
+
*/
|
|
75
|
+
declare function isUIMessage(message: unknown): message is UIMessage;
|
|
76
|
+
/**
|
|
77
|
+
* Input message that could be in any format - using unknown for flexibility
|
|
78
|
+
*/
|
|
79
|
+
type InputMessage = {
|
|
80
|
+
id?: string;
|
|
81
|
+
role?: string;
|
|
82
|
+
content?: unknown;
|
|
83
|
+
reasoning?: string;
|
|
84
|
+
toolInvocations?: unknown[];
|
|
85
|
+
parts?: unknown[];
|
|
86
|
+
[key: string]: unknown;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Automatic message transformer following the blog post pattern
|
|
90
|
+
* Handles comprehensive migration from AI SDK v4 to v5 format
|
|
91
|
+
* @param message - Message in any legacy format
|
|
92
|
+
* @param index - Index for ID generation fallback
|
|
93
|
+
* @returns UIMessage in v5 format
|
|
94
|
+
*/
|
|
95
|
+
declare function autoTransformMessage(
|
|
96
|
+
message: InputMessage,
|
|
97
|
+
index?: number
|
|
98
|
+
): UIMessage;
|
|
99
|
+
/**
|
|
100
|
+
* Legacy single message migration for backward compatibility
|
|
101
|
+
*/
|
|
102
|
+
declare function migrateToUIMessage(message: MigratableMessage): UIMessage;
|
|
103
|
+
/**
|
|
104
|
+
* Automatic message transformer for arrays following the blog post pattern
|
|
105
|
+
* @param messages - Array of messages in any format
|
|
106
|
+
* @returns Array of UIMessages in v5 format
|
|
107
|
+
*/
|
|
108
|
+
declare function autoTransformMessages(messages: unknown[]): UIMessage[];
|
|
109
|
+
/**
|
|
110
|
+
* Migrates an array of messages to UIMessage format (legacy compatibility)
|
|
111
|
+
* @param messages - Array of messages in old or new format
|
|
112
|
+
* @returns Array of UIMessages in the new format
|
|
113
|
+
*/
|
|
114
|
+
declare function migrateMessagesToUIFormat(
|
|
115
|
+
messages: MigratableMessage[]
|
|
116
|
+
): UIMessage[];
|
|
117
|
+
/**
|
|
118
|
+
* Checks if any messages in an array need migration
|
|
119
|
+
* @param messages - Array of messages to check
|
|
120
|
+
* @returns true if any messages are not in proper UIMessage format
|
|
121
|
+
*/
|
|
122
|
+
declare function needsMigration(messages: unknown[]): boolean;
|
|
123
|
+
/**
|
|
124
|
+
* Analyzes the corruption types in a message array for debugging
|
|
125
|
+
* @param messages - Array of messages to analyze
|
|
126
|
+
* @returns Statistics about corruption types found
|
|
127
|
+
*/
|
|
128
|
+
declare function analyzeCorruption(messages: unknown[]): {
|
|
129
|
+
total: number;
|
|
130
|
+
clean: number;
|
|
131
|
+
legacyString: number;
|
|
132
|
+
corruptArray: number;
|
|
133
|
+
unknown: number;
|
|
134
|
+
examples: {
|
|
135
|
+
legacyString?: unknown;
|
|
136
|
+
corruptArray?: unknown;
|
|
137
|
+
unknown?: unknown;
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export {
|
|
142
|
+
type CorruptArrayMessage,
|
|
143
|
+
type LegacyMessage,
|
|
144
|
+
type MigratableMessage,
|
|
145
|
+
analyzeCorruption,
|
|
146
|
+
autoTransformMessage,
|
|
147
|
+
autoTransformMessages,
|
|
148
|
+
isUIMessage,
|
|
149
|
+
migrateMessagesToUIFormat,
|
|
150
|
+
migrateToUIMessage,
|
|
151
|
+
needsMigration
|
|
152
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
analyzeCorruption,
|
|
3
|
+
autoTransformMessage,
|
|
4
|
+
autoTransformMessages,
|
|
5
|
+
isUIMessage,
|
|
6
|
+
migrateMessagesToUIFormat,
|
|
7
|
+
migrateToUIMessage,
|
|
8
|
+
needsMigration
|
|
9
|
+
} from "./chunk-UJVEAURM.js";
|
|
10
|
+
export {
|
|
11
|
+
analyzeCorruption,
|
|
12
|
+
autoTransformMessage,
|
|
13
|
+
autoTransformMessages,
|
|
14
|
+
isUIMessage,
|
|
15
|
+
migrateMessagesToUIFormat,
|
|
16
|
+
migrateToUIMessage,
|
|
17
|
+
needsMigration
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=ai-chat-v5-migration.js.map
|