agents 0.0.0-2d0d2e1 → 0.0.0-2e73791
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 +229 -8
- package/dist/ai-chat-agent.d.ts +236 -28
- package/dist/ai-chat-agent.js +1118 -351
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
- package/dist/ai-chat-v5-migration-DguhuLKF.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +7 -4
- package/dist/ai-chat-v5-migration.js +3 -19
- package/dist/ai-react.d.ts +154 -28
- package/dist/ai-react.js +572 -304
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types-DEtF_8Km.js +28 -0
- package/dist/ai-types-DEtF_8Km.js.map +1 -0
- package/dist/ai-types-U8lYA0o8.d.ts +127 -0
- package/dist/ai-types.d.ts +6 -91
- package/dist/ai-types.js +3 -7
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +28 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/client-Cfw92Wb_.d.ts +834 -0
- package/dist/client-ClORm6f0.d.ts +104 -0
- package/dist/client-DjTPRM8-.js +117 -0
- package/dist/client-DjTPRM8-.js.map +1 -0
- package/dist/client-QZa2Rq0l.js +1105 -0
- package/dist/client-QZa2Rq0l.js.map +1 -0
- package/dist/client.d.ts +11 -92
- package/dist/client.js +4 -12
- package/dist/codemode/ai.d.ts +27 -0
- package/dist/codemode/ai.js +152 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/context-BkKbAa1R.js +8 -0
- package/dist/context-BkKbAa1R.js.map +1 -0
- package/dist/context-_sPQqJWv.d.ts +24 -0
- package/dist/context.d.ts +6 -0
- package/dist/context.js +3 -0
- package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
- package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
- package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
- package/dist/index-CyDpAVHZ.d.ts +58 -0
- package/dist/index-xIS9I1YX.d.ts +576 -0
- package/dist/index.d.ts +56 -550
- package/dist/index.js +8 -31
- package/dist/mcp/client.d.ts +4 -11
- package/dist/mcp/client.js +4 -9
- package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
- package/dist/mcp/do-oauth-client-provider.js +3 -7
- package/dist/mcp/index.d.ts +199 -93
- package/dist/mcp/index.js +1425 -1008
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +34 -0
- package/dist/mcp/x402.js +198 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/mcp-CzbSsLfc.d.ts +61 -0
- package/dist/observability/index.d.ts +3 -46
- package/dist/observability/index.js +8 -11
- package/dist/react-ElpIreHg.d.ts +131 -0
- package/dist/react.d.ts +15 -123
- package/dist/react.js +183 -112
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +13 -10
- package/dist/schedule.js +43 -31
- package/dist/schedule.js.map +1 -1
- package/dist/serializable-C4GLimgv.d.ts +39 -0
- package/dist/serializable.d.ts +7 -32
- package/dist/serializable.js +1 -1
- package/dist/src-BZDh910Z.js +1181 -0
- package/dist/src-BZDh910Z.js.map +1 -0
- package/package.json +74 -34
- package/dist/ai-chat-v5-migration.js.map +0 -1
- package/dist/ai-types.js.map +0 -1
- package/dist/chunk-AVYJQSLW.js +0 -17
- package/dist/chunk-AVYJQSLW.js.map +0 -1
- package/dist/chunk-LL2AFX7V.js +0 -109
- package/dist/chunk-LL2AFX7V.js.map +0 -1
- package/dist/chunk-MH46VMM4.js +0 -612
- package/dist/chunk-MH46VMM4.js.map +0 -1
- package/dist/chunk-QEVM4BVL.js +0 -116
- package/dist/chunk-QEVM4BVL.js.map +0 -1
- package/dist/chunk-UJVEAURM.js +0 -150
- package/dist/chunk-UJVEAURM.js.map +0 -1
- package/dist/chunk-YDUDMOL6.js +0 -1296
- package/dist/chunk-YDUDMOL6.js.map +0 -1
- package/dist/client-CvaJdLQA.d.ts +0 -5015
- package/dist/client.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp/client.js.map +0 -1
- package/dist/mcp/do-oauth-client-provider.js.map +0 -1
- package/dist/observability/index.js.map +0 -1
- package/dist/serializable.js.map +0 -1
- package/src/index.ts +0 -1947
package/README.md
CHANGED
|
@@ -342,16 +342,114 @@ export class DialogueAgent extends AIChatAgent {
|
|
|
342
342
|
// messages: this.messages,
|
|
343
343
|
// });
|
|
344
344
|
//
|
|
345
|
-
// //
|
|
346
|
-
//
|
|
347
|
-
//
|
|
348
|
-
//
|
|
349
|
-
//
|
|
345
|
+
// // For non-streaming with metadata, use toUIMessage:
|
|
346
|
+
// const message = result.toUIMessage({
|
|
347
|
+
// metadata: {
|
|
348
|
+
// model: 'gpt-4o',
|
|
349
|
+
// totalTokens: result.usage?.totalTokens,
|
|
350
|
+
// }
|
|
351
|
+
// });
|
|
352
|
+
//
|
|
353
|
+
// return new Response(JSON.stringify(message), {
|
|
354
|
+
// headers: { 'Content-Type': 'application/json' }
|
|
350
355
|
// });
|
|
351
356
|
}
|
|
352
357
|
}
|
|
353
358
|
```
|
|
354
359
|
|
|
360
|
+
#### Metadata Support
|
|
361
|
+
|
|
362
|
+
The AI SDK provides native support for message metadata through the `messageMetadata` callback. This allows you to attach custom information to messages at the message level.
|
|
363
|
+
|
|
364
|
+
##### AIChatAgent Integration
|
|
365
|
+
|
|
366
|
+
In the context of `AIChatAgent`, you can use metadata like this:
|
|
367
|
+
|
|
368
|
+
```typescript
|
|
369
|
+
import { AIChatAgent } from "agents/ai-chat-agent";
|
|
370
|
+
import { streamText } from "ai";
|
|
371
|
+
import { openai } from "@ai-sdk/openai";
|
|
372
|
+
|
|
373
|
+
export class MyAgent extends AIChatAgent<Env> {
|
|
374
|
+
async onChatMessage(onFinish) {
|
|
375
|
+
const startTime = Date.now();
|
|
376
|
+
|
|
377
|
+
const result = streamText({
|
|
378
|
+
model: openai("gpt-4o"),
|
|
379
|
+
messages: this.messages,
|
|
380
|
+
onFinish
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
return result.toUIMessageStreamResponse({
|
|
384
|
+
messageMetadata: ({ part }) => {
|
|
385
|
+
if (part.type === "start") {
|
|
386
|
+
return {
|
|
387
|
+
model: "gpt-4o",
|
|
388
|
+
createdAt: Date.now(),
|
|
389
|
+
messageCount: this.messages.length
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (part.type === "finish") {
|
|
393
|
+
return {
|
|
394
|
+
responseTime: Date.now() - startTime,
|
|
395
|
+
totalTokens: part.totalUsage?.totalTokens
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
##### Accessing Metadata on the Client
|
|
405
|
+
|
|
406
|
+
Access metadata through the `message.metadata` property:
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
'use client';
|
|
410
|
+
|
|
411
|
+
import { useChat } from '@ai-sdk/react';
|
|
412
|
+
import { DefaultChatTransport } from 'ai';
|
|
413
|
+
import type { MyUIMessage } from '@/types';
|
|
414
|
+
|
|
415
|
+
export default function Chat() {
|
|
416
|
+
const { messages } = useChat<MyUIMessage>({
|
|
417
|
+
transport: new DefaultChatTransport({
|
|
418
|
+
api: '/api/chat',
|
|
419
|
+
}),
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
return (
|
|
423
|
+
<div>
|
|
424
|
+
{messages.map(message => (
|
|
425
|
+
<div key={message.id}>
|
|
426
|
+
<div>
|
|
427
|
+
{message.role === 'user' ? 'User: ' : 'AI: '}
|
|
428
|
+
{message.metadata?.createdAt && (
|
|
429
|
+
<span className="text-sm text-gray-500">
|
|
430
|
+
{new Date(message.metadata.createdAt).toLocaleTimeString()}
|
|
431
|
+
</span>
|
|
432
|
+
)}
|
|
433
|
+
</div>
|
|
434
|
+
{/* Render message content */}
|
|
435
|
+
{message.parts.map((part, index) =>
|
|
436
|
+
part.type === 'text' ? <div key={index}>{part.text}</div> : null,
|
|
437
|
+
)}
|
|
438
|
+
{/* Display additional metadata */}
|
|
439
|
+
{message.metadata?.totalTokens && (
|
|
440
|
+
<div className="text-xs text-gray-400">
|
|
441
|
+
{message.metadata.totalTokens} tokens
|
|
442
|
+
</div>
|
|
443
|
+
)}
|
|
444
|
+
</div>
|
|
445
|
+
))}
|
|
446
|
+
</div>
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
For more details, see the [AI SDK Message Metadata documentation](https://ai-sdk.dev/docs/ai-sdk-ui/message-metadata).
|
|
452
|
+
|
|
355
453
|
#### Creating the Interface
|
|
356
454
|
|
|
357
455
|
Connect with your agent through a React interface:
|
|
@@ -417,6 +515,127 @@ This creates:
|
|
|
417
515
|
- Intuitive input handling
|
|
418
516
|
- Easy conversation reset
|
|
419
517
|
|
|
518
|
+
#### Client-Defined Tools
|
|
519
|
+
|
|
520
|
+
For scenarios where each client needs to register its own tools dynamically (e.g., embeddable chat widgets), use the `tools` option with `execute` functions.
|
|
521
|
+
|
|
522
|
+
Tools with an `execute` function are automatically:
|
|
523
|
+
|
|
524
|
+
1. Sent to the server as schemas with each request
|
|
525
|
+
2. Executed on the client when the AI model calls them
|
|
526
|
+
|
|
527
|
+
##### Client-Side Tool Definition
|
|
528
|
+
|
|
529
|
+
```tsx
|
|
530
|
+
import { useAgent } from "agents/react";
|
|
531
|
+
import { useAgentChat, type AITool } from "agents/ai-react";
|
|
532
|
+
|
|
533
|
+
// Define tools outside component to avoid recreation on every render
|
|
534
|
+
const tools: Record<string, AITool> = {
|
|
535
|
+
showAlert: {
|
|
536
|
+
description: "Shows an alert dialog to the user",
|
|
537
|
+
parameters: {
|
|
538
|
+
type: "object",
|
|
539
|
+
properties: { message: { type: "string" } },
|
|
540
|
+
required: ["message"]
|
|
541
|
+
},
|
|
542
|
+
execute: async (input) => {
|
|
543
|
+
const { message } = input as { message: string };
|
|
544
|
+
alert(message);
|
|
545
|
+
return { success: true };
|
|
546
|
+
}
|
|
547
|
+
},
|
|
548
|
+
changeBackgroundColor: {
|
|
549
|
+
description: "Changes the page background color",
|
|
550
|
+
parameters: {
|
|
551
|
+
type: "object",
|
|
552
|
+
properties: { color: { type: "string" } }
|
|
553
|
+
},
|
|
554
|
+
execute: async (input) => {
|
|
555
|
+
const { color } = input as { color: string };
|
|
556
|
+
document.body.style.backgroundColor = color;
|
|
557
|
+
return { success: true, color };
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
|
|
562
|
+
function EmbeddableChat() {
|
|
563
|
+
const agent = useAgent({ agent: "chat-widget" });
|
|
564
|
+
|
|
565
|
+
const { messages, input, handleInputChange, handleSubmit } = useAgentChat({
|
|
566
|
+
agent,
|
|
567
|
+
tools // Schema + execute in one place
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
return (
|
|
571
|
+
<div className="chat-widget">
|
|
572
|
+
{messages.map((message) => (
|
|
573
|
+
<div key={message.id}>{/* Render message */}</div>
|
|
574
|
+
))}
|
|
575
|
+
<form onSubmit={handleSubmit}>
|
|
576
|
+
<input value={input} onChange={handleInputChange} />
|
|
577
|
+
</form>
|
|
578
|
+
</div>
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
##### Server-Side Tool Handling
|
|
584
|
+
|
|
585
|
+
On the server, use `createToolsFromClientSchemas` to convert client tool schemas to AI SDK format:
|
|
586
|
+
|
|
587
|
+
```typescript
|
|
588
|
+
import {
|
|
589
|
+
AIChatAgent,
|
|
590
|
+
createToolsFromClientSchemas
|
|
591
|
+
} from "agents/ai-chat-agent";
|
|
592
|
+
import { openai } from "@ai-sdk/openai";
|
|
593
|
+
import { streamText, convertToModelMessages } from "ai";
|
|
594
|
+
|
|
595
|
+
export class ChatWidget extends AIChatAgent {
|
|
596
|
+
async onChatMessage(onFinish, options) {
|
|
597
|
+
const result = streamText({
|
|
598
|
+
model: openai("gpt-4o"),
|
|
599
|
+
messages: convertToModelMessages(this.messages),
|
|
600
|
+
tools: {
|
|
601
|
+
// Server-side tools (execute on server)
|
|
602
|
+
getWeather: tool({
|
|
603
|
+
description: "Get weather for a city",
|
|
604
|
+
parameters: z.object({ city: z.string() }),
|
|
605
|
+
execute: async ({ city }) => fetchWeather(city)
|
|
606
|
+
}),
|
|
607
|
+
// Client-side tools (sent back to client for execution)
|
|
608
|
+
...createToolsFromClientSchemas(options?.clientTools)
|
|
609
|
+
},
|
|
610
|
+
onFinish
|
|
611
|
+
});
|
|
612
|
+
return result.toUIMessageStreamResponse();
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
##### Advanced: Custom Request Data
|
|
618
|
+
|
|
619
|
+
For additional control (custom headers, dynamic context), use `prepareSendMessagesRequest`:
|
|
620
|
+
|
|
621
|
+
```tsx
|
|
622
|
+
const { messages, handleSubmit } = useAgentChat({
|
|
623
|
+
agent,
|
|
624
|
+
tools, // Tool schemas auto-extracted and sent
|
|
625
|
+
prepareSendMessagesRequest: ({ id, messages }) => ({
|
|
626
|
+
body: {
|
|
627
|
+
// Add dynamic context alongside auto-extracted tool schemas
|
|
628
|
+
currentUrl: window.location.href,
|
|
629
|
+
userTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
630
|
+
},
|
|
631
|
+
headers: {
|
|
632
|
+
"X-Widget-Version": "1.0.0",
|
|
633
|
+
"X-Request-ID": crypto.randomUUID()
|
|
634
|
+
}
|
|
635
|
+
})
|
|
636
|
+
});
|
|
637
|
+
```
|
|
638
|
+
|
|
420
639
|
### 🔗 MCP (Model Context Protocol) Integration
|
|
421
640
|
|
|
422
641
|
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).
|
|
@@ -451,10 +670,12 @@ export class MyMCP extends McpAgent<Env, State, {}> {
|
|
|
451
670
|
};
|
|
452
671
|
});
|
|
453
672
|
|
|
454
|
-
this.server.
|
|
673
|
+
this.server.registerTool(
|
|
455
674
|
"add",
|
|
456
|
-
|
|
457
|
-
|
|
675
|
+
{
|
|
676
|
+
description: "Add to the counter, stored in the MCP",
|
|
677
|
+
inputSchema: { a: z.number() }
|
|
678
|
+
},
|
|
458
679
|
async ({ a }) => {
|
|
459
680
|
this.setState({ ...this.state, counter: this.state.counter + a });
|
|
460
681
|
|
package/dist/ai-chat-agent.d.ts
CHANGED
|
@@ -1,51 +1,182 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import "
|
|
5
|
-
import "
|
|
6
|
-
import "
|
|
7
|
-
import "./
|
|
8
|
-
import
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
import "./observability/index.js";
|
|
16
|
-
import "./ai-types.js";
|
|
1
|
+
import "./context-_sPQqJWv.js";
|
|
2
|
+
import "./client-Cfw92Wb_.js";
|
|
3
|
+
import "./mcp-CzbSsLfc.js";
|
|
4
|
+
import "./do-oauth-client-provider-B-ryFIPr.js";
|
|
5
|
+
import "./index-CyDpAVHZ.js";
|
|
6
|
+
import "./ai-types-U8lYA0o8.js";
|
|
7
|
+
import { n as AgentContext, t as Agent } from "./index-xIS9I1YX.js";
|
|
8
|
+
import {
|
|
9
|
+
JSONSchema7,
|
|
10
|
+
StreamTextOnFinishCallback,
|
|
11
|
+
Tool,
|
|
12
|
+
ToolSet,
|
|
13
|
+
UIMessage
|
|
14
|
+
} from "ai";
|
|
17
15
|
|
|
16
|
+
//#region src/ai-chat-agent.d.ts
|
|
17
|
+
/**
|
|
18
|
+
* Schema for a client-defined tool sent from the browser.
|
|
19
|
+
* These tools are executed on the client, not the server.
|
|
20
|
+
*
|
|
21
|
+
* Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)
|
|
22
|
+
* because this is the wire format. Zod schemas cannot be serialized.
|
|
23
|
+
*/
|
|
24
|
+
type ClientToolSchema = {
|
|
25
|
+
/** Unique name for the tool */
|
|
26
|
+
name: string;
|
|
27
|
+
/** Human-readable description of what the tool does */
|
|
28
|
+
description?: Tool["description"];
|
|
29
|
+
/** JSON Schema defining the tool's input parameters */
|
|
30
|
+
parameters?: JSONSchema7;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Options passed to the onChatMessage handler.
|
|
34
|
+
*/
|
|
35
|
+
type OnChatMessageOptions = {
|
|
36
|
+
/** AbortSignal for cancelling the request */
|
|
37
|
+
abortSignal?: AbortSignal;
|
|
38
|
+
/**
|
|
39
|
+
* Tool schemas sent from the client for dynamic tool registration.
|
|
40
|
+
* These represent tools that will be executed on the client side.
|
|
41
|
+
* Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
|
|
42
|
+
*/
|
|
43
|
+
clientTools?: ClientToolSchema[];
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Converts client tool schemas to AI SDK tool format.
|
|
47
|
+
*
|
|
48
|
+
* These tools have no `execute` function - when the AI model calls them,
|
|
49
|
+
* the tool call is sent back to the client for execution.
|
|
50
|
+
*
|
|
51
|
+
* @param clientTools - Array of tool schemas from the client
|
|
52
|
+
* @returns Record of AI SDK tools that can be spread into your tools object
|
|
53
|
+
*/
|
|
54
|
+
declare function createToolsFromClientSchemas(
|
|
55
|
+
clientTools?: ClientToolSchema[]
|
|
56
|
+
): ToolSet;
|
|
18
57
|
/**
|
|
19
58
|
* Extension of Agent with built-in chat capabilities
|
|
20
59
|
* @template Env Environment type containing bindings
|
|
21
60
|
*/
|
|
22
|
-
declare class AIChatAgent<
|
|
23
|
-
Env,
|
|
24
|
-
State
|
|
25
|
-
> {
|
|
61
|
+
declare class AIChatAgent<
|
|
62
|
+
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
63
|
+
State = unknown
|
|
64
|
+
> extends Agent<Env, State> {
|
|
26
65
|
/**
|
|
27
66
|
* Map of message `id`s to `AbortController`s
|
|
28
67
|
* useful to propagate request cancellation signals for any external calls made by the agent
|
|
29
68
|
*/
|
|
30
69
|
private _chatMessageAbortControllers;
|
|
70
|
+
/**
|
|
71
|
+
* Currently active stream ID for resumable streaming.
|
|
72
|
+
* Stored in memory for quick access; persisted in stream_metadata table.
|
|
73
|
+
* @internal Protected for testing purposes.
|
|
74
|
+
*/
|
|
75
|
+
protected _activeStreamId: string | null;
|
|
76
|
+
/**
|
|
77
|
+
* Request ID associated with the active stream.
|
|
78
|
+
* @internal Protected for testing purposes.
|
|
79
|
+
*/
|
|
80
|
+
protected _activeRequestId: string | null;
|
|
81
|
+
/**
|
|
82
|
+
* The message currently being streamed. Used to apply tool results
|
|
83
|
+
* before the message is persisted.
|
|
84
|
+
* @internal
|
|
85
|
+
*/
|
|
86
|
+
private _streamingMessage;
|
|
87
|
+
/**
|
|
88
|
+
* Promise that resolves when the current stream completes.
|
|
89
|
+
* Used to wait for message persistence before continuing after tool results.
|
|
90
|
+
* @internal
|
|
91
|
+
*/
|
|
92
|
+
private _streamCompletionPromise;
|
|
93
|
+
private _streamCompletionResolve;
|
|
94
|
+
/**
|
|
95
|
+
* Current chunk index for the active stream
|
|
96
|
+
*/
|
|
97
|
+
private _streamChunkIndex;
|
|
98
|
+
/**
|
|
99
|
+
* Buffer for stream chunks pending write to SQLite.
|
|
100
|
+
* Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
|
|
101
|
+
*/
|
|
102
|
+
private _chunkBuffer;
|
|
103
|
+
/**
|
|
104
|
+
* Lock to prevent concurrent flush operations
|
|
105
|
+
*/
|
|
106
|
+
private _isFlushingChunks;
|
|
107
|
+
/**
|
|
108
|
+
* Timestamp of the last cleanup operation for old streams
|
|
109
|
+
*/
|
|
110
|
+
private _lastCleanupTime;
|
|
31
111
|
/** Array of chat messages for the current conversation */
|
|
32
112
|
messages: UIMessage[];
|
|
33
113
|
constructor(ctx: AgentContext, env: Env);
|
|
114
|
+
/**
|
|
115
|
+
* Restore active stream state if the agent was restarted during streaming.
|
|
116
|
+
* Called during construction to recover any interrupted streams.
|
|
117
|
+
* Validates stream freshness to avoid sending stale resume notifications.
|
|
118
|
+
* @internal Protected for testing purposes.
|
|
119
|
+
*/
|
|
120
|
+
protected _restoreActiveStream(): void;
|
|
121
|
+
/**
|
|
122
|
+
* Notify a connection about an active stream that can be resumed.
|
|
123
|
+
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
124
|
+
* Uses in-memory state for request ID - no extra DB lookup needed.
|
|
125
|
+
* @param connection - The WebSocket connection to notify
|
|
126
|
+
*/
|
|
127
|
+
private _notifyStreamResuming;
|
|
128
|
+
/**
|
|
129
|
+
* Send stream chunks to a connection after receiving ACK.
|
|
130
|
+
* @param connection - The WebSocket connection
|
|
131
|
+
* @param streamId - The stream to replay
|
|
132
|
+
* @param requestId - The original request ID
|
|
133
|
+
*/
|
|
134
|
+
private _sendStreamChunks;
|
|
135
|
+
/**
|
|
136
|
+
* Buffer a stream chunk for batch write to SQLite.
|
|
137
|
+
* @param streamId - The stream this chunk belongs to
|
|
138
|
+
* @param body - The serialized chunk body
|
|
139
|
+
* @internal Protected for testing purposes.
|
|
140
|
+
*/
|
|
141
|
+
protected _storeStreamChunk(streamId: string, body: string): void;
|
|
142
|
+
/**
|
|
143
|
+
* Flush buffered chunks to SQLite in a single batch.
|
|
144
|
+
* Uses a lock to prevent concurrent flush operations.
|
|
145
|
+
* @internal Protected for testing purposes.
|
|
146
|
+
*/
|
|
147
|
+
protected _flushChunkBuffer(): void;
|
|
148
|
+
/**
|
|
149
|
+
* Start tracking a new stream for resumable streaming.
|
|
150
|
+
* Creates metadata entry in SQLite and sets up tracking state.
|
|
151
|
+
* @param requestId - The unique ID of the chat request
|
|
152
|
+
* @returns The generated stream ID
|
|
153
|
+
* @internal Protected for testing purposes.
|
|
154
|
+
*/
|
|
155
|
+
protected _startStream(requestId: string): string;
|
|
156
|
+
/**
|
|
157
|
+
* Mark a stream as completed and flush any pending chunks.
|
|
158
|
+
* @param streamId - The stream to mark as completed
|
|
159
|
+
* @internal Protected for testing purposes.
|
|
160
|
+
*/
|
|
161
|
+
protected _completeStream(streamId: string): void;
|
|
162
|
+
/**
|
|
163
|
+
* Clean up old completed streams if enough time has passed since last cleanup.
|
|
164
|
+
* This prevents database growth while avoiding cleanup overhead on every stream completion.
|
|
165
|
+
*/
|
|
166
|
+
private _maybeCleanupOldStreams;
|
|
34
167
|
private _broadcastChatMessage;
|
|
35
|
-
|
|
168
|
+
private _loadMessagesFromDb;
|
|
36
169
|
onRequest(request: Request): Promise<Response>;
|
|
37
170
|
private _tryCatchChat;
|
|
38
171
|
/**
|
|
39
172
|
* Handle incoming chat messages and generate a response
|
|
40
173
|
* @param onFinish Callback to be called when the response is finished
|
|
41
|
-
* @param options
|
|
174
|
+
* @param options Options including abort signal and client-defined tools
|
|
42
175
|
* @returns Response to send to the client or undefined
|
|
43
176
|
*/
|
|
44
177
|
onChatMessage(
|
|
45
178
|
onFinish: StreamTextOnFinishCallback<ToolSet>,
|
|
46
|
-
options?:
|
|
47
|
-
abortSignal: AbortSignal | undefined;
|
|
48
|
-
}
|
|
179
|
+
options?: OnChatMessageOptions
|
|
49
180
|
): Promise<Response | undefined>;
|
|
50
181
|
/**
|
|
51
182
|
* Save messages on the server side
|
|
@@ -56,7 +187,78 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
56
187
|
messages: UIMessage[],
|
|
57
188
|
excludeBroadcastIds?: string[]
|
|
58
189
|
): Promise<void>;
|
|
190
|
+
/**
|
|
191
|
+
* Merges incoming messages with existing server state.
|
|
192
|
+
* This preserves tool outputs that the server has (via _applyToolResult)
|
|
193
|
+
* but the client doesn't have yet.
|
|
194
|
+
*
|
|
195
|
+
* @param incomingMessages - Messages from the client
|
|
196
|
+
* @returns Messages with server's tool outputs preserved
|
|
197
|
+
*/
|
|
198
|
+
private _mergeIncomingWithServerState;
|
|
199
|
+
/**
|
|
200
|
+
* Resolves a message for persistence, handling tool result merging.
|
|
201
|
+
* If the message contains tool parts with output-available state, checks if there's
|
|
202
|
+
* an existing message with the same toolCallId that should be updated instead of
|
|
203
|
+
* creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
|
|
204
|
+
* when client-side tool results arrive in a new request.
|
|
205
|
+
*
|
|
206
|
+
* @param message - The message to potentially merge
|
|
207
|
+
* @returns The message with the correct ID (either original or merged)
|
|
208
|
+
*/
|
|
209
|
+
private _resolveMessageForToolMerge;
|
|
210
|
+
/**
|
|
211
|
+
* Finds an existing assistant message that contains a tool part with the given toolCallId.
|
|
212
|
+
* Used to detect when a tool result should update an existing message rather than
|
|
213
|
+
* creating a new one.
|
|
214
|
+
*
|
|
215
|
+
* @param toolCallId - The tool call ID to search for
|
|
216
|
+
* @returns The existing message if found, undefined otherwise
|
|
217
|
+
*/
|
|
218
|
+
private _findMessageByToolCallId;
|
|
219
|
+
/**
|
|
220
|
+
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
221
|
+
* data that should not be stored or sent back in subsequent requests.
|
|
222
|
+
*
|
|
223
|
+
* This handles two issues with the OpenAI Responses API:
|
|
224
|
+
*
|
|
225
|
+
* 1. **Duplicate item IDs**: The AI SDK's @ai-sdk/openai provider (v2.0.x+)
|
|
226
|
+
* defaults to using OpenAI's Responses API which assigns unique itemIds
|
|
227
|
+
* to each message part. When these IDs are persisted and sent back,
|
|
228
|
+
* OpenAI rejects them as duplicates.
|
|
229
|
+
*
|
|
230
|
+
* 2. **Empty reasoning parts**: OpenAI may return reasoning parts with empty
|
|
231
|
+
* text and encrypted content. These cause "Non-OpenAI reasoning parts are
|
|
232
|
+
* not supported" warnings when sent back via convertToModelMessages().
|
|
233
|
+
*
|
|
234
|
+
* @param message - The message to sanitize
|
|
235
|
+
* @returns A new message with ephemeral provider data removed
|
|
236
|
+
*/
|
|
237
|
+
private _sanitizeMessageForPersistence;
|
|
238
|
+
/**
|
|
239
|
+
* Helper to strip OpenAI-specific ephemeral fields from a metadata object.
|
|
240
|
+
* Removes itemId and reasoningEncryptedContent while preserving other fields.
|
|
241
|
+
*/
|
|
242
|
+
private _stripOpenAIMetadata;
|
|
243
|
+
/**
|
|
244
|
+
* Applies a tool result to an existing assistant message.
|
|
245
|
+
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
246
|
+
* The server is the source of truth, so we update the message here and broadcast
|
|
247
|
+
* the update to all clients.
|
|
248
|
+
*
|
|
249
|
+
* @param toolCallId - The tool call ID this result is for
|
|
250
|
+
* @param toolName - The name of the tool
|
|
251
|
+
* @param output - The output from the tool execution
|
|
252
|
+
* @returns true if the result was applied, false if the message was not found
|
|
253
|
+
*/
|
|
254
|
+
private _applyToolResult;
|
|
59
255
|
private _reply;
|
|
256
|
+
/**
|
|
257
|
+
* Mark a stream as errored and clean up state.
|
|
258
|
+
* @param streamId - The stream to mark as errored
|
|
259
|
+
* @internal Protected for testing purposes.
|
|
260
|
+
*/
|
|
261
|
+
protected _markStreamError(streamId: string): void;
|
|
60
262
|
/**
|
|
61
263
|
* For the given message id, look up its associated AbortController
|
|
62
264
|
* If the AbortController does not exist, create and store one in memory
|
|
@@ -77,9 +279,15 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
77
279
|
*/
|
|
78
280
|
private _destroyAbortControllers;
|
|
79
281
|
/**
|
|
80
|
-
* When the DO is destroyed, cancel all pending requests
|
|
282
|
+
* When the DO is destroyed, cancel all pending requests and clean up resources
|
|
81
283
|
*/
|
|
82
284
|
destroy(): Promise<void>;
|
|
83
285
|
}
|
|
84
|
-
|
|
85
|
-
export {
|
|
286
|
+
//#endregion
|
|
287
|
+
export {
|
|
288
|
+
AIChatAgent,
|
|
289
|
+
ClientToolSchema,
|
|
290
|
+
OnChatMessageOptions,
|
|
291
|
+
createToolsFromClientSchemas
|
|
292
|
+
};
|
|
293
|
+
//# sourceMappingURL=ai-chat-agent.d.ts.map
|