agents 0.0.0-f6c26e4 → 0.0.0-f7bd395
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 +136 -6
- package/dist/ai-chat-agent.d.ts +12 -9
- package/dist/ai-chat-agent.js +142 -59
- 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 +62 -71
- 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-5YIRLLUX.js → chunk-IJPBZOSS.js} +137 -105
- package/dist/chunk-IJPBZOSS.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-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-MW5BQ2FW.js → chunk-VYENMKFS.js} +163 -20
- package/dist/chunk-VYENMKFS.js.map +1 -0
- package/dist/client-CcIORE73.d.ts +4607 -0
- package/dist/client.js +2 -1
- package/dist/index.d.ts +557 -32
- package/dist/index.js +7 -4
- package/dist/mcp/client.d.ts +9 -1053
- 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 +66 -53
- package/dist/mcp/index.js +850 -604
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +46 -12
- package/dist/observability/index.js +5 -4
- package/dist/react.d.ts +7 -3
- package/dist/react.js +7 -5
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +83 -9
- package/dist/schedule.js +15 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +19 -8
- package/src/index.ts +192 -123
- package/dist/chunk-5YIRLLUX.js.map +0 -1
- package/dist/chunk-KUH345EY.js.map +0 -1
- package/dist/chunk-MW5BQ2FW.js.map +0 -1
- package/dist/chunk-PVQZBKN7.js.map +0 -1
- package/dist/index-BIJvkfYt.d.ts +0 -614
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>
|
|
@@ -393,6 +417,112 @@ This creates:
|
|
|
393
417
|
- Intuitive input handling
|
|
394
418
|
- Easy conversation reset
|
|
395
419
|
|
|
420
|
+
### 🔗 MCP (Model Context Protocol) Integration
|
|
421
|
+
|
|
422
|
+
Agents can seamlessly integrate with the Model Context Protocol, allowing them to act as both MCP servers (providing tools to AI assistants) and MCP clients (using tools from other services).
|
|
423
|
+
|
|
424
|
+
#### Creating an MCP Server
|
|
425
|
+
|
|
426
|
+
```typescript
|
|
427
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
428
|
+
import { McpAgent } from "agents/mcp";
|
|
429
|
+
import { z } from "zod";
|
|
430
|
+
|
|
431
|
+
type Env = {
|
|
432
|
+
MyMCP: DurableObjectNamespace<MyMCP>;
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
type State = { counter: number };
|
|
436
|
+
|
|
437
|
+
export class MyMCP extends McpAgent<Env, State, {}> {
|
|
438
|
+
server = new McpServer({
|
|
439
|
+
name: "Demo",
|
|
440
|
+
version: "1.0.0"
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
initialState: State = {
|
|
444
|
+
counter: 1
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
async init() {
|
|
448
|
+
this.server.resource("counter", "mcp://resource/counter", (uri) => {
|
|
449
|
+
return {
|
|
450
|
+
contents: [{ text: String(this.state.counter), uri: uri.href }]
|
|
451
|
+
};
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
this.server.tool(
|
|
455
|
+
"add",
|
|
456
|
+
"Add to the counter, stored in the MCP",
|
|
457
|
+
{ a: z.number() },
|
|
458
|
+
async ({ a }) => {
|
|
459
|
+
this.setState({ ...this.state, counter: this.state.counter + a });
|
|
460
|
+
|
|
461
|
+
return {
|
|
462
|
+
content: [
|
|
463
|
+
{
|
|
464
|
+
text: String(`Added ${a}, total is now ${this.state.counter}`),
|
|
465
|
+
type: "text"
|
|
466
|
+
}
|
|
467
|
+
]
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
onStateUpdate(state: State) {
|
|
474
|
+
console.log({ stateUpdate: state });
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// HTTP Streamable transport (recommended)
|
|
479
|
+
export default MyMCP.serve("/mcp", {
|
|
480
|
+
binding: "MyMCP"
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
// Or SSE transport for legacy compatibility
|
|
484
|
+
// export default MyMCP.serveSSE("/mcp", { binding: "MyMCP" });
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
#### Using MCP Tools
|
|
488
|
+
|
|
489
|
+
```typescript
|
|
490
|
+
import { MCPClientManager } from "agents/mcp";
|
|
491
|
+
|
|
492
|
+
const client = new MCPClientManager("my-app", "1.0.0");
|
|
493
|
+
|
|
494
|
+
// Connect to an MCP server
|
|
495
|
+
await client.connect("https://weather-service.com/mcp", {
|
|
496
|
+
transport: { type: "streamable-http" }
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
// Use tools from the server
|
|
500
|
+
const weather = await client.callTool({
|
|
501
|
+
serverId: "weather-service",
|
|
502
|
+
name: "getWeather",
|
|
503
|
+
arguments: { location: "San Francisco" }
|
|
504
|
+
});
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
#### AI SDK Integration
|
|
508
|
+
|
|
509
|
+
```typescript
|
|
510
|
+
import { generateText } from "ai";
|
|
511
|
+
|
|
512
|
+
// Convert MCP tools for AI use
|
|
513
|
+
const result = await generateText({
|
|
514
|
+
model: openai("gpt-4"),
|
|
515
|
+
tools: client.getAITools(),
|
|
516
|
+
prompt: "What's the weather in Tokyo?"
|
|
517
|
+
});
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
**Transport Options:**
|
|
521
|
+
|
|
522
|
+
- **Auto**: Automatically determine the correct transport
|
|
523
|
+
- **HTTP Streamable**: Best performance, batch requests, session management
|
|
524
|
+
- **SSE**: Simple setup, legacy compatibility
|
|
525
|
+
|
|
396
526
|
### 💬 The Path Forward
|
|
397
527
|
|
|
398
528
|
We're developing new dimensions of agent capability:
|
|
@@ -418,8 +548,8 @@ Welcome to the future of intelligent agents. Create something meaningful. 🌟
|
|
|
418
548
|
Contributions are welcome, but are especially welcome when:
|
|
419
549
|
|
|
420
550
|
- You have opened an issue as a Request for Comment (RFC) to discuss your proposal, show your thinking, and iterate together.
|
|
421
|
-
-
|
|
422
|
-
- 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.
|
|
423
553
|
|
|
424
554
|
Small fixes, type bugs, and documentation improvements can be raised directly as PRs.
|
|
425
555
|
|
package/dist/ai-chat-agent.d.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { UIMessage, StreamTextOnFinishCallback, ToolSet } from "ai";
|
|
2
|
+
import { Agent, AgentContext } from "./index.js";
|
|
3
3
|
import { Connection, WSMessage } from "partyserver";
|
|
4
|
+
import "cloudflare:workers";
|
|
4
5
|
import "@modelcontextprotocol/sdk/client/index.js";
|
|
5
6
|
import "@modelcontextprotocol/sdk/types.js";
|
|
6
|
-
import "./
|
|
7
|
+
import "./client-CcIORE73.js";
|
|
7
8
|
import "zod";
|
|
8
|
-
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
9
9
|
import "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
10
|
+
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
11
|
+
import "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
10
12
|
import "./mcp/do-oauth-client-provider.js";
|
|
11
13
|
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
12
14
|
import "@modelcontextprotocol/sdk/shared/auth.js";
|
|
15
|
+
import "./observability/index.js";
|
|
16
|
+
import "./ai-types.js";
|
|
13
17
|
|
|
14
18
|
/**
|
|
15
19
|
* Extension of Agent with built-in chat capabilities
|
|
@@ -25,7 +29,7 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
25
29
|
*/
|
|
26
30
|
private _chatMessageAbortControllers;
|
|
27
31
|
/** Array of chat messages for the current conversation */
|
|
28
|
-
messages:
|
|
32
|
+
messages: UIMessage[];
|
|
29
33
|
constructor(ctx: AgentContext, env: Env);
|
|
30
34
|
private _broadcastChatMessage;
|
|
31
35
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
|
@@ -44,15 +48,14 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
44
48
|
}
|
|
45
49
|
): Promise<Response | undefined>;
|
|
46
50
|
/**
|
|
47
|
-
* Save messages on the server side
|
|
51
|
+
* Save messages on the server side
|
|
48
52
|
* @param messages Chat messages to save
|
|
49
53
|
*/
|
|
50
|
-
saveMessages(messages:
|
|
54
|
+
saveMessages(messages: UIMessage[]): Promise<void>;
|
|
51
55
|
persistMessages(
|
|
52
|
-
messages:
|
|
56
|
+
messages: UIMessage[],
|
|
53
57
|
excludeBroadcastIds?: string[]
|
|
54
58
|
): Promise<void>;
|
|
55
|
-
private _messagesNotAlreadyInAgent;
|
|
56
59
|
private _reply;
|
|
57
60
|
/**
|
|
58
61
|
* For the given message id, look up its associated AbortController
|
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-IJPBZOSS.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,22 +49,20 @@ 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
|
-
|
|
56
|
-
await this.persistMessages(messages, [connection.id]);
|
|
60
|
+
await this.persistMessages(transformedMessages, [connection.id]);
|
|
57
61
|
this.observability?.emit(
|
|
58
62
|
{
|
|
59
63
|
displayMessage: "Chat message request",
|
|
60
64
|
id: data.id,
|
|
61
|
-
payload: {
|
|
62
|
-
message: incomingMessages
|
|
63
|
-
},
|
|
65
|
+
payload: {},
|
|
64
66
|
timestamp: Date.now(),
|
|
65
67
|
type: "message:request"
|
|
66
68
|
},
|
|
@@ -70,21 +72,13 @@ var AIChatAgent = class extends Agent {
|
|
|
70
72
|
const abortSignal = this._getAbortSignal(chatMessageId);
|
|
71
73
|
return this._tryCatchChat(async () => {
|
|
72
74
|
const response = await this.onChatMessage(
|
|
73
|
-
async (
|
|
74
|
-
const finalMessages = appendResponseMessages({
|
|
75
|
-
messages,
|
|
76
|
-
responseMessages: response2.messages
|
|
77
|
-
});
|
|
78
|
-
const outgoingMessages = this._messagesNotAlreadyInAgent(finalMessages);
|
|
79
|
-
await this.persistMessages(finalMessages, [connection.id]);
|
|
75
|
+
async (_finishResult) => {
|
|
80
76
|
this._removeAbortController(chatMessageId);
|
|
81
77
|
this.observability?.emit(
|
|
82
78
|
{
|
|
83
79
|
displayMessage: "Chat message response",
|
|
84
80
|
id: data.id,
|
|
85
|
-
payload: {
|
|
86
|
-
message: outgoingMessages
|
|
87
|
-
},
|
|
81
|
+
payload: {},
|
|
88
82
|
timestamp: Date.now(),
|
|
89
83
|
type: "message:response"
|
|
90
84
|
},
|
|
@@ -104,26 +98,27 @@ var AIChatAgent = class extends Agent {
|
|
|
104
98
|
body: "No response was generated by the agent.",
|
|
105
99
|
done: true,
|
|
106
100
|
id: data.id,
|
|
107
|
-
type: "cf_agent_use_chat_response"
|
|
101
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
108
102
|
},
|
|
109
103
|
[connection.id]
|
|
110
104
|
);
|
|
111
105
|
}
|
|
112
106
|
});
|
|
113
107
|
}
|
|
114
|
-
if (data.type === "cf_agent_chat_clear") {
|
|
108
|
+
if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
|
|
115
109
|
this._destroyAbortControllers();
|
|
116
110
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
117
111
|
this.messages = [];
|
|
118
112
|
this._broadcastChatMessage(
|
|
119
113
|
{
|
|
120
|
-
type: "cf_agent_chat_clear"
|
|
114
|
+
type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
|
|
121
115
|
},
|
|
122
116
|
[connection.id]
|
|
123
117
|
);
|
|
124
|
-
} else if (data.type === "cf_agent_chat_messages") {
|
|
125
|
-
|
|
126
|
-
|
|
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 */) {
|
|
127
122
|
this._cancelChatRequest(data.id);
|
|
128
123
|
}
|
|
129
124
|
}
|
|
@@ -159,24 +154,11 @@ var AIChatAgent = class extends Agent {
|
|
|
159
154
|
);
|
|
160
155
|
}
|
|
161
156
|
/**
|
|
162
|
-
* Save messages on the server side
|
|
157
|
+
* Save messages on the server side
|
|
163
158
|
* @param messages Chat messages to save
|
|
164
159
|
*/
|
|
165
160
|
async saveMessages(messages) {
|
|
166
161
|
await this.persistMessages(messages);
|
|
167
|
-
const response = await this.onChatMessage(async ({ response: response2 }) => {
|
|
168
|
-
const finalMessages = appendResponseMessages({
|
|
169
|
-
messages,
|
|
170
|
-
responseMessages: response2.messages
|
|
171
|
-
});
|
|
172
|
-
await this.persistMessages(finalMessages, []);
|
|
173
|
-
});
|
|
174
|
-
if (response) {
|
|
175
|
-
for await (const chunk of response.body) {
|
|
176
|
-
decoder.decode(chunk);
|
|
177
|
-
}
|
|
178
|
-
response.body?.cancel();
|
|
179
|
-
}
|
|
180
162
|
}
|
|
181
163
|
async persistMessages(messages, excludeBroadcastIds = []) {
|
|
182
164
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
@@ -187,32 +169,133 @@ var AIChatAgent = class extends Agent {
|
|
|
187
169
|
this._broadcastChatMessage(
|
|
188
170
|
{
|
|
189
171
|
messages,
|
|
190
|
-
type: "cf_agent_chat_messages"
|
|
172
|
+
type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
|
|
191
173
|
},
|
|
192
174
|
excludeBroadcastIds
|
|
193
175
|
);
|
|
194
176
|
}
|
|
195
|
-
_messagesNotAlreadyInAgent(messages) {
|
|
196
|
-
const existingIds = new Set(this.messages.map((message) => message.id));
|
|
197
|
-
return messages.filter((message) => !existingIds.has(message.id));
|
|
198
|
-
}
|
|
199
177
|
async _reply(id, response) {
|
|
200
178
|
return this._tryCatchChat(async () => {
|
|
201
|
-
|
|
202
|
-
const body = decoder.decode(chunk);
|
|
179
|
+
if (!response.body) {
|
|
203
180
|
this._broadcastChatMessage({
|
|
204
|
-
body,
|
|
205
|
-
done:
|
|
181
|
+
body: "",
|
|
182
|
+
done: true,
|
|
206
183
|
id,
|
|
207
|
-
type: "cf_agent_use_chat_response"
|
|
184
|
+
type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
|
|
208
185
|
});
|
|
186
|
+
return;
|
|
209
187
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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();
|
|
281
|
+
}
|
|
282
|
+
const messageParts = [];
|
|
283
|
+
Array.from(toolCalls.values()).forEach((t) => {
|
|
284
|
+
messageParts.push(t);
|
|
215
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
|
+
}
|
|
216
299
|
});
|
|
217
300
|
}
|
|
218
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 const incomingMessages = this._messagesNotAlreadyInAgent(messages);\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 message: incomingMessages\n },\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 const outgoingMessages =\n this._messagesNotAlreadyInAgent(finalMessages);\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 message: outgoingMessages\n },\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 _messagesNotAlreadyInAgent(messages: ChatMessage[]) {\n const existingIds = new Set(this.messages.map((message) => message.id));\n return messages.filter((message) => !existingIds.has(message.id));\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,KAAU;AACvC,UAAM,KAAK,GAAG;AACd,SAAK;AAAA;AAAA;AAAA;AAAA;AAKL,SAAK,YACH,KAAK,gDAAgD,CAAC,GACtD,IAAI,CAAC,QAAQ;AACb,aAAO,KAAK,MAAM,IAAI,OAAiB;AAAA,IACzC,CAAC;AAED,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,Y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reamTextOnFinishCallback,\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,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