agents 0.3.1 → 0.3.2

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.
Files changed (67) hide show
  1. package/README.md +12 -326
  2. package/dist/ai-chat-agent.d.ts +1 -324
  3. package/dist/ai-chat-agent.js +3 -1147
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +1 -155
  6. package/dist/ai-chat-v5-migration.js +4 -151
  7. package/dist/ai-chat-v5-migration.js.map +1 -1
  8. package/dist/ai-react.d.ts +1 -286
  9. package/dist/ai-react.js +3 -632
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +7 -6
  12. package/dist/ai-types.js +12 -2
  13. package/dist/ai-types.js.map +1 -0
  14. package/dist/{client-QZa2Rq0l.js → client-C7SOlYfK.js} +2 -2
  15. package/dist/{client-QZa2Rq0l.js.map → client-C7SOlYfK.js.map} +1 -1
  16. package/dist/{client-DjTPRM8-.js → client-CEO0P7vN.js} +2 -2
  17. package/dist/client-CEO0P7vN.js.map +1 -0
  18. package/dist/{client-DFotUKH_.d.ts → client-CbcnyqCo.d.ts} +10 -10
  19. package/dist/client.d.ts +92 -7
  20. package/dist/client.js +1 -1
  21. package/dist/codemode/ai.d.ts +1 -27
  22. package/dist/codemode/ai.js +3 -146
  23. package/dist/codemode/ai.js.map +1 -1
  24. package/dist/{do-oauth-client-provider--To1Tsjj.d.ts → do-oauth-client-provider-BH9zFtSy.d.ts} +1 -1
  25. package/dist/{do-oauth-client-provider-B1fVIshX.js → do-oauth-client-provider-BfPFgQU0.js} +1 -1
  26. package/dist/{do-oauth-client-provider-B1fVIshX.js.map → do-oauth-client-provider-BfPFgQU0.js.map} +1 -1
  27. package/dist/{index-DLuxm_9W.d.ts → index-B7Ny-XfU.d.ts} +2 -2
  28. package/dist/index.d.ts +553 -38
  29. package/dist/index.js +5 -5
  30. package/dist/{context-DcbQ8o7k.d.ts → internal_context-neg89p5n.d.ts} +2 -2
  31. package/dist/{context-BkKbAa1R.js → internal_context-oN047Id3.js} +2 -2
  32. package/dist/internal_context-oN047Id3.js.map +1 -0
  33. package/dist/{context.d.ts → internal_context.d.ts} +1 -1
  34. package/dist/internal_context.js +3 -0
  35. package/dist/mcp/client.d.ts +1 -1
  36. package/dist/mcp/client.js +2 -2
  37. package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
  38. package/dist/mcp/do-oauth-client-provider.js +1 -1
  39. package/dist/mcp/index.d.ts +3 -4
  40. package/dist/mcp/index.js +6 -6
  41. package/dist/mcp/index.js.map +1 -1
  42. package/dist/mcp/x402.d.ts +1 -1
  43. package/dist/{mcp-CPSfGUgd.d.ts → mcp-AK39tq6H.d.ts} +1 -1
  44. package/dist/observability/index.d.ts +1 -1
  45. package/dist/observability/index.js +5 -5
  46. package/dist/react.d.ts +14 -6
  47. package/dist/react.js +16 -8
  48. package/dist/react.js.map +1 -1
  49. package/dist/serializable.d.ts +33 -6
  50. package/dist/{src-BZDh910Z.js → src-CXf5SiV4.js} +6 -6
  51. package/dist/src-CXf5SiV4.js.map +1 -0
  52. package/dist/types-4b5tlB0u.js +15 -0
  53. package/dist/types-4b5tlB0u.js.map +1 -0
  54. package/dist/types-C5vR2Gzv.d.ts +13 -0
  55. package/dist/types.d.ts +2 -0
  56. package/dist/types.js +3 -0
  57. package/package.json +33 -22
  58. package/dist/ai-types-0OnT3FHg.d.ts +0 -127
  59. package/dist/ai-types-DEtF_8Km.js +0 -28
  60. package/dist/ai-types-DEtF_8Km.js.map +0 -1
  61. package/dist/client-CdM5I962.d.ts +0 -104
  62. package/dist/client-DjTPRM8-.js.map +0 -1
  63. package/dist/context-BkKbAa1R.js.map +0 -1
  64. package/dist/context.js +0 -3
  65. package/dist/index-CT2tCrLr.d.ts +0 -577
  66. package/dist/serializable-Crsj26mx.d.ts +0 -39
  67. package/dist/src-BZDh910Z.js.map +0 -1
package/README.md CHANGED
@@ -277,6 +277,18 @@ function StateInterface() {
277
277
 
278
278
  This creates a synchronized state that automatically updates across all connected clients.
279
279
 
280
+ ### 💬 AI Chat Integration
281
+
282
+ For building AI-powered chat experiences with persistent conversations, streaming responses, and tool support, see [`@cloudflare/ai-chat`](../ai-chat/README.md).
283
+
284
+ The `@cloudflare/ai-chat` package provides:
285
+
286
+ - `AIChatAgent` - Chat-enabled agent class with automatic message persistence
287
+ - `useAgentChat` - React hook for seamless chat interactions
288
+ - Resumable streaming - Automatic recovery from disconnections
289
+ - Tool support - Both server and client-side tool execution
290
+ - AI SDK v6 integration - Built on the latest AI SDK
291
+
280
292
  ### ⏳ Temporal Patterns
281
293
 
282
294
  Schedule moments of action and reflection:
@@ -310,332 +322,6 @@ export class TimeAwareAgent extends Agent {
310
322
  }
311
323
  ```
312
324
 
313
- ### 💬 AI Dialogue
314
-
315
- Create meaningful conversations with intelligence:
316
-
317
- ```ts
318
- import { AIChatAgent } from "agents/ai-chat-agent";
319
- import { openai } from "@ai-sdk/openai";
320
- import { streamText, generateText, createDataStreamResponse } from "ai";
321
-
322
- export class DialogueAgent extends AIChatAgent {
323
- async onChatMessage(onFinish) {
324
- // Option 1: Streaming responses (recommended for real-time interaction)
325
- return createDataStreamResponse({
326
- execute: async (dataStream) => {
327
- const stream = streamText({
328
- model: openai("gpt-4o"),
329
- messages: this.messages,
330
- // Optional: onFinish is invoked by the AI SDK when generation completes.
331
- // Persistence is handled automatically by AIChatAgent after streaming completes.
332
- onFinish
333
- });
334
-
335
- stream.mergeIntoDataStream(dataStream);
336
- }
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
- // // 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' }
355
- // });
356
- }
357
- }
358
- ```
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
-
453
- #### Creating the Interface
454
-
455
- Connect with your agent through a React interface:
456
-
457
- ```tsx
458
- import { useAgent } from "agents/react";
459
- import { useAgentChat } from "agents/ai-react";
460
-
461
- function ChatInterface() {
462
- // Connect to the agent
463
- const agent = useAgent({
464
- agent: "dialogue-agent"
465
- });
466
-
467
- // Set up the chat interaction
468
- const { messages, input, handleInputChange, handleSubmit, clearHistory } =
469
- useAgentChat({
470
- agent,
471
- maxSteps: 5
472
- });
473
-
474
- return (
475
- <div className="chat-interface">
476
- {/* Message History */}
477
- <div className="message-flow">
478
- {messages.map((message) => (
479
- <div key={message.id} className="message">
480
- <div className="role">{message.role}</div>
481
- <div className="content">
482
- {message.parts.map((part, i) => {
483
- if (part.type === "text")
484
- return <span key={i}>{part.text}</span>;
485
- // Render other part types (e.g., files, tool calls) as desired
486
- return null;
487
- })}
488
- </div>
489
- </div>
490
- ))}
491
- </div>
492
-
493
- {/* Input Area */}
494
- <form onSubmit={handleSubmit} className="input-area">
495
- <input
496
- value={input}
497
- onChange={handleInputChange}
498
- placeholder="Type your message..."
499
- className="message-input"
500
- />
501
- </form>
502
-
503
- <button onClick={clearHistory} className="clear-button">
504
- Clear Chat
505
- </button>
506
- </div>
507
- );
508
- }
509
- ```
510
-
511
- This creates:
512
-
513
- - Real-time message streaming
514
- - Simple message history
515
- - Intuitive input handling
516
- - Easy conversation reset
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
-
639
325
  ### 🔗 MCP (Model Context Protocol) Integration
640
326
 
641
327
  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).
@@ -1,324 +1 @@
1
- import "./context-DcbQ8o7k.js";
2
- import "./client-DFotUKH_.js";
3
- import "./ai-types-0OnT3FHg.js";
4
- import { n as AgentContext, t as Agent } from "./index-CT2tCrLr.js";
5
- import {
6
- JSONSchema7,
7
- StreamTextOnFinishCallback,
8
- Tool,
9
- ToolSet,
10
- UIMessage
11
- } from "ai";
12
-
13
- //#region src/ai-chat-agent.d.ts
14
-
15
- /**
16
- * Schema for a client-defined tool sent from the browser.
17
- * These tools are executed on the client, not the server.
18
- *
19
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)
20
- * because this is the wire format. Zod schemas cannot be serialized.
21
- *
22
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
23
- * For tools that need client-side execution, omit the `execute` function
24
- * and handle them via the `onToolCall` callback in `useAgentChat`.
25
- */
26
- type ClientToolSchema = {
27
- /** Unique name for the tool */
28
- name: string;
29
- /** Human-readable description of what the tool does */
30
- description?: Tool["description"];
31
- /** JSON Schema defining the tool's input parameters */
32
- parameters?: JSONSchema7;
33
- };
34
- /**
35
- * Options passed to the onChatMessage handler.
36
- */
37
- type OnChatMessageOptions = {
38
- /** AbortSignal for cancelling the request */
39
- abortSignal?: AbortSignal;
40
- /**
41
- * Tool schemas sent from the client for dynamic tool registration.
42
- * These represent tools that will be executed on the client side.
43
- * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
44
- *
45
- * @deprecated Define tools on the server instead. Use `onToolCall` callback
46
- * in `useAgentChat` for client-side execution.
47
- */
48
- clientTools?: ClientToolSchema[];
49
- };
50
- /**
51
- * Converts client tool schemas to AI SDK tool format.
52
- *
53
- * These tools have no `execute` function - when the AI model calls them,
54
- * the tool call is sent back to the client for execution.
55
- *
56
- * @param clientTools - Array of tool schemas from the client
57
- * @returns Record of AI SDK tools that can be spread into your tools object
58
- *
59
- * @deprecated Define tools on the server using `tool()` from "ai" instead.
60
- * For tools that need client-side execution, omit the `execute` function
61
- * and handle them via the `onToolCall` callback in `useAgentChat`.
62
- *
63
- * @example
64
- * ```typescript
65
- * // Server: Define tool without execute
66
- * const tools = {
67
- * getLocation: tool({
68
- * description: "Get user's location",
69
- * inputSchema: z.object({})
70
- * // No execute = client must handle
71
- * })
72
- * };
73
- *
74
- * // Client: Handle in onToolCall
75
- * useAgentChat({
76
- * onToolCall: async ({ toolCall, addToolOutput }) => {
77
- * if (toolCall.toolName === 'getLocation') {
78
- * const pos = await navigator.geolocation.getCurrentPosition();
79
- * addToolOutput({ toolCallId: toolCall.toolCallId, output: pos });
80
- * }
81
- * }
82
- * });
83
- * ```
84
- */
85
- declare function createToolsFromClientSchemas(
86
- clientTools?: ClientToolSchema[]
87
- ): ToolSet;
88
- /**
89
- * Extension of Agent with built-in chat capabilities
90
- * @template Env Environment type containing bindings
91
- */
92
- declare class AIChatAgent<
93
- Env extends Cloudflare.Env = Cloudflare.Env,
94
- State = unknown
95
- > extends Agent<Env, State> {
96
- /**
97
- * Map of message `id`s to `AbortController`s
98
- * useful to propagate request cancellation signals for any external calls made by the agent
99
- */
100
- private _chatMessageAbortControllers;
101
- /**
102
- * Currently active stream ID for resumable streaming.
103
- * Stored in memory for quick access; persisted in stream_metadata table.
104
- * @internal Protected for testing purposes.
105
- */
106
- protected _activeStreamId: string | null;
107
- /**
108
- * Request ID associated with the active stream.
109
- * @internal Protected for testing purposes.
110
- */
111
- protected _activeRequestId: string | null;
112
- /**
113
- * The message currently being streamed. Used to apply tool results
114
- * before the message is persisted.
115
- * @internal
116
- */
117
- private _streamingMessage;
118
- /**
119
- * Promise that resolves when the current stream completes.
120
- * Used to wait for message persistence before continuing after tool results.
121
- * @internal
122
- */
123
- private _streamCompletionPromise;
124
- private _streamCompletionResolve;
125
- /**
126
- * Current chunk index for the active stream
127
- */
128
- private _streamChunkIndex;
129
- /**
130
- * Buffer for stream chunks pending write to SQLite.
131
- * Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
132
- */
133
- private _chunkBuffer;
134
- /**
135
- * Lock to prevent concurrent flush operations
136
- */
137
- private _isFlushingChunks;
138
- /**
139
- * Timestamp of the last cleanup operation for old streams
140
- */
141
- private _lastCleanupTime;
142
- /** Array of chat messages for the current conversation */
143
- messages: UIMessage[];
144
- constructor(ctx: AgentContext, env: Env);
145
- /**
146
- * Restore active stream state if the agent was restarted during streaming.
147
- * Called during construction to recover any interrupted streams.
148
- * Validates stream freshness to avoid sending stale resume notifications.
149
- * @internal Protected for testing purposes.
150
- */
151
- protected _restoreActiveStream(): void;
152
- /**
153
- * Notify a connection about an active stream that can be resumed.
154
- * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
155
- * Uses in-memory state for request ID - no extra DB lookup needed.
156
- * @param connection - The WebSocket connection to notify
157
- */
158
- private _notifyStreamResuming;
159
- /**
160
- * Send stream chunks to a connection after receiving ACK.
161
- * @param connection - The WebSocket connection
162
- * @param streamId - The stream to replay
163
- * @param requestId - The original request ID
164
- */
165
- private _sendStreamChunks;
166
- /**
167
- * Buffer a stream chunk for batch write to SQLite.
168
- * @param streamId - The stream this chunk belongs to
169
- * @param body - The serialized chunk body
170
- * @internal Protected for testing purposes.
171
- */
172
- protected _storeStreamChunk(streamId: string, body: string): void;
173
- /**
174
- * Flush buffered chunks to SQLite in a single batch.
175
- * Uses a lock to prevent concurrent flush operations.
176
- * @internal Protected for testing purposes.
177
- */
178
- protected _flushChunkBuffer(): void;
179
- /**
180
- * Start tracking a new stream for resumable streaming.
181
- * Creates metadata entry in SQLite and sets up tracking state.
182
- * @param requestId - The unique ID of the chat request
183
- * @returns The generated stream ID
184
- * @internal Protected for testing purposes.
185
- */
186
- protected _startStream(requestId: string): string;
187
- /**
188
- * Mark a stream as completed and flush any pending chunks.
189
- * @param streamId - The stream to mark as completed
190
- * @internal Protected for testing purposes.
191
- */
192
- protected _completeStream(streamId: string): void;
193
- /**
194
- * Clean up old completed streams if enough time has passed since last cleanup.
195
- * This prevents database growth while avoiding cleanup overhead on every stream completion.
196
- */
197
- private _maybeCleanupOldStreams;
198
- private _broadcastChatMessage;
199
- private _loadMessagesFromDb;
200
- onRequest(request: Request): Promise<Response>;
201
- private _tryCatchChat;
202
- /**
203
- * Handle incoming chat messages and generate a response
204
- * @param onFinish Callback to be called when the response is finished
205
- * @param options Options including abort signal and client-defined tools
206
- * @returns Response to send to the client or undefined
207
- */
208
- onChatMessage(
209
- onFinish: StreamTextOnFinishCallback<ToolSet>,
210
- options?: OnChatMessageOptions
211
- ): Promise<Response | undefined>;
212
- /**
213
- * Save messages on the server side
214
- * @param messages Chat messages to save
215
- */
216
- saveMessages(messages: UIMessage[]): Promise<void>;
217
- persistMessages(
218
- messages: UIMessage[],
219
- excludeBroadcastIds?: string[]
220
- ): Promise<void>;
221
- /**
222
- * Merges incoming messages with existing server state.
223
- * This preserves tool outputs that the server has (via _applyToolResult)
224
- * but the client doesn't have yet.
225
- *
226
- * @param incomingMessages - Messages from the client
227
- * @returns Messages with server's tool outputs preserved
228
- */
229
- private _mergeIncomingWithServerState;
230
- /**
231
- * Resolves a message for persistence, handling tool result merging.
232
- * If the message contains tool parts with output-available state, checks if there's
233
- * an existing message with the same toolCallId that should be updated instead of
234
- * creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
235
- * when client-side tool results arrive in a new request.
236
- *
237
- * @param message - The message to potentially merge
238
- * @returns The message with the correct ID (either original or merged)
239
- */
240
- private _resolveMessageForToolMerge;
241
- /**
242
- * Finds an existing assistant message that contains a tool part with the given toolCallId.
243
- * Used to detect when a tool result should update an existing message rather than
244
- * creating a new one.
245
- *
246
- * @param toolCallId - The tool call ID to search for
247
- * @returns The existing message if found, undefined otherwise
248
- */
249
- private _findMessageByToolCallId;
250
- /**
251
- * Sanitizes a message for persistence by removing ephemeral provider-specific
252
- * data that should not be stored or sent back in subsequent requests.
253
- *
254
- * This handles two issues with the OpenAI Responses API:
255
- *
256
- * 1. **Duplicate item IDs**: The AI SDK's @ai-sdk/openai provider (v2.0.x+)
257
- * defaults to using OpenAI's Responses API which assigns unique itemIds
258
- * to each message part. When these IDs are persisted and sent back,
259
- * OpenAI rejects them as duplicates.
260
- *
261
- * 2. **Empty reasoning parts**: OpenAI may return reasoning parts with empty
262
- * text and encrypted content. These cause "Non-OpenAI reasoning parts are
263
- * not supported" warnings when sent back via convertToModelMessages().
264
- *
265
- * @param message - The message to sanitize
266
- * @returns A new message with ephemeral provider data removed
267
- */
268
- private _sanitizeMessageForPersistence;
269
- /**
270
- * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
271
- * Removes itemId and reasoningEncryptedContent while preserving other fields.
272
- */
273
- private _stripOpenAIMetadata;
274
- /**
275
- * Applies a tool result to an existing assistant message.
276
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
277
- * The server is the source of truth, so we update the message here and broadcast
278
- * the update to all clients.
279
- *
280
- * @param toolCallId - The tool call ID this result is for
281
- * @param toolName - The name of the tool
282
- * @param output - The output from the tool execution
283
- * @returns true if the result was applied, false if the message was not found
284
- */
285
- private _applyToolResult;
286
- private _reply;
287
- /**
288
- * Mark a stream as errored and clean up state.
289
- * @param streamId - The stream to mark as errored
290
- * @internal Protected for testing purposes.
291
- */
292
- protected _markStreamError(streamId: string): void;
293
- /**
294
- * For the given message id, look up its associated AbortController
295
- * If the AbortController does not exist, create and store one in memory
296
- *
297
- * returns the AbortSignal associated with the AbortController
298
- */
299
- private _getAbortSignal;
300
- /**
301
- * Remove an abort controller from the cache of pending message responses
302
- */
303
- private _removeAbortController;
304
- /**
305
- * Propagate an abort signal for any requests associated with the given message id
306
- */
307
- private _cancelChatRequest;
308
- /**
309
- * Abort all pending requests and clear the cache of AbortControllers
310
- */
311
- private _destroyAbortControllers;
312
- /**
313
- * When the DO is destroyed, cancel all pending requests and clean up resources
314
- */
315
- destroy(): Promise<void>;
316
- }
317
- //#endregion
318
- export {
319
- AIChatAgent,
320
- ClientToolSchema,
321
- OnChatMessageOptions,
322
- createToolsFromClientSchemas
323
- };
324
- //# sourceMappingURL=ai-chat-agent.d.ts.map
1
+ export * from "@cloudflare/ai-chat";