agents 0.0.0-07086ea → 0.0.0-087264c

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 (78) hide show
  1. package/README.md +378 -27
  2. package/dist/ai-chat-agent.d.ts +265 -30
  3. package/dist/ai-chat-agent.js +1118 -226
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +155 -0
  6. package/dist/ai-chat-v5-migration.js +155 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +197 -71
  9. package/dist/ai-react.js +574 -200
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types-0OnT3FHg.d.ts +127 -0
  12. package/dist/ai-types-DEtF_8Km.js +28 -0
  13. package/dist/ai-types-DEtF_8Km.js.map +1 -0
  14. package/dist/ai-types.d.ts +6 -74
  15. package/dist/ai-types.js +3 -1
  16. package/dist/cli/index.d.ts +1 -0
  17. package/dist/cli/index.js +28 -0
  18. package/dist/cli/index.js.map +1 -0
  19. package/dist/client-CdM5I962.d.ts +104 -0
  20. package/dist/client-DFotUKH_.d.ts +834 -0
  21. package/dist/client-DjTPRM8-.js +117 -0
  22. package/dist/client-DjTPRM8-.js.map +1 -0
  23. package/dist/client-QZa2Rq0l.js +1105 -0
  24. package/dist/client-QZa2Rq0l.js.map +1 -0
  25. package/dist/client.d.ts +11 -79
  26. package/dist/client.js +2 -130
  27. package/dist/codemode/ai.d.ts +27 -0
  28. package/dist/codemode/ai.js +151 -0
  29. package/dist/codemode/ai.js.map +1 -0
  30. package/dist/context-BkKbAa1R.js +8 -0
  31. package/dist/context-BkKbAa1R.js.map +1 -0
  32. package/dist/context-DcbQ8o7k.d.ts +24 -0
  33. package/dist/context.d.ts +6 -0
  34. package/dist/context.js +3 -0
  35. package/dist/do-oauth-client-provider--To1Tsjj.d.ts +70 -0
  36. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  38. package/dist/index-BaskqQ6f.d.ts +576 -0
  39. package/dist/index-DLuxm_9W.d.ts +58 -0
  40. package/dist/index.d.ts +60 -306
  41. package/dist/index.js +7 -21
  42. package/dist/mcp/client.d.ts +2 -768
  43. package/dist/mcp/client.js +4 -10
  44. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  45. package/dist/mcp/do-oauth-client-provider.js +2 -106
  46. package/dist/mcp/index.d.ts +197 -71
  47. package/dist/mcp/index.js +1431 -797
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/x402.d.ts +34 -0
  50. package/dist/mcp/x402.js +198 -0
  51. package/dist/mcp/x402.js.map +1 -0
  52. package/dist/mcp-CPSfGUgd.d.ts +61 -0
  53. package/dist/observability/index.d.ts +2 -0
  54. package/dist/observability/index.js +7 -0
  55. package/dist/react.d.ts +107 -12
  56. package/dist/react.js +183 -98
  57. package/dist/react.js.map +1 -1
  58. package/dist/schedule.d.ts +62 -39
  59. package/dist/schedule.js +46 -23
  60. package/dist/schedule.js.map +1 -1
  61. package/dist/serializable-Crsj26mx.d.ts +39 -0
  62. package/dist/serializable.d.ts +7 -0
  63. package/dist/serializable.js +1 -0
  64. package/dist/src-BZDh910Z.js +1181 -0
  65. package/dist/src-BZDh910Z.js.map +1 -0
  66. package/package.json +140 -68
  67. package/dist/ai-types.js.map +0 -1
  68. package/dist/chunk-HMLY7DHA.js +0 -16
  69. package/dist/chunk-HMLY7DHA.js.map +0 -1
  70. package/dist/chunk-WNICV3OI.js +0 -436
  71. package/dist/chunk-WNICV3OI.js.map +0 -1
  72. package/dist/chunk-ZRZEISHY.js +0 -597
  73. package/dist/chunk-ZRZEISHY.js.map +0 -1
  74. package/dist/client.js.map +0 -1
  75. package/dist/index.js.map +0 -1
  76. package/dist/mcp/client.js.map +0 -1
  77. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  78. package/src/index.ts +0 -918
@@ -1,56 +1,291 @@
1
- import { Agent, AgentContext } from "./index.js";
2
- import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
3
- import { Connection, WSMessage } from "partyserver";
4
- import "node:async_hooks";
5
- import "./mcp/client.js";
6
- import "zod";
7
- import "@modelcontextprotocol/sdk/types.js";
8
- import "@modelcontextprotocol/sdk/client/index.js";
9
- import "@modelcontextprotocol/sdk/client/sse.js";
10
- import "./mcp/do-oauth-client-provider.js";
11
- import "@modelcontextprotocol/sdk/client/auth.js";
12
- import "@modelcontextprotocol/sdk/shared/auth.js";
13
- import "@modelcontextprotocol/sdk/shared/protocol.js";
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-BaskqQ6f.js";
5
+ import {
6
+ JSONSchema7,
7
+ StreamTextOnFinishCallback,
8
+ Tool,
9
+ ToolSet,
10
+ UIMessage
11
+ } from "ai";
14
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
+ type ClientToolSchema = {
23
+ /** Unique name for the tool */
24
+ name: string;
25
+ /** Human-readable description of what the tool does */
26
+ description?: Tool["description"];
27
+ /** JSON Schema defining the tool's input parameters */
28
+ parameters?: JSONSchema7;
29
+ };
30
+ /**
31
+ * Options passed to the onChatMessage handler.
32
+ */
33
+ type OnChatMessageOptions = {
34
+ /** AbortSignal for cancelling the request */
35
+ abortSignal?: AbortSignal;
36
+ /**
37
+ * Tool schemas sent from the client for dynamic tool registration.
38
+ * These represent tools that will be executed on the client side.
39
+ * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
40
+ */
41
+ clientTools?: ClientToolSchema[];
42
+ };
43
+ /**
44
+ * Converts client tool schemas to AI SDK tool format.
45
+ *
46
+ * These tools have no `execute` function - when the AI model calls them,
47
+ * the tool call is sent back to the client for execution.
48
+ *
49
+ * @param clientTools - Array of tool schemas from the client
50
+ * @returns Record of AI SDK tools that can be spread into your tools object
51
+ */
52
+ declare function createToolsFromClientSchemas(
53
+ clientTools?: ClientToolSchema[]
54
+ ): ToolSet;
15
55
  /**
16
56
  * Extension of Agent with built-in chat capabilities
17
57
  * @template Env Environment type containing bindings
18
58
  */
19
- declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
20
- Env,
21
- State
22
- > {
23
- #private;
59
+ declare class AIChatAgent<
60
+ Env extends Cloudflare.Env = Cloudflare.Env,
61
+ State = unknown
62
+ > extends Agent<Env, State> {
63
+ /**
64
+ * Map of message `id`s to `AbortController`s
65
+ * useful to propagate request cancellation signals for any external calls made by the agent
66
+ */
67
+ private _chatMessageAbortControllers;
68
+ /**
69
+ * Currently active stream ID for resumable streaming.
70
+ * Stored in memory for quick access; persisted in stream_metadata table.
71
+ * @internal Protected for testing purposes.
72
+ */
73
+ protected _activeStreamId: string | null;
74
+ /**
75
+ * Request ID associated with the active stream.
76
+ * @internal Protected for testing purposes.
77
+ */
78
+ protected _activeRequestId: string | null;
79
+ /**
80
+ * The message currently being streamed. Used to apply tool results
81
+ * before the message is persisted.
82
+ * @internal
83
+ */
84
+ private _streamingMessage;
85
+ /**
86
+ * Promise that resolves when the current stream completes.
87
+ * Used to wait for message persistence before continuing after tool results.
88
+ * @internal
89
+ */
90
+ private _streamCompletionPromise;
91
+ private _streamCompletionResolve;
92
+ /**
93
+ * Current chunk index for the active stream
94
+ */
95
+ private _streamChunkIndex;
96
+ /**
97
+ * Buffer for stream chunks pending write to SQLite.
98
+ * Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
99
+ */
100
+ private _chunkBuffer;
101
+ /**
102
+ * Lock to prevent concurrent flush operations
103
+ */
104
+ private _isFlushingChunks;
105
+ /**
106
+ * Timestamp of the last cleanup operation for old streams
107
+ */
108
+ private _lastCleanupTime;
24
109
  /** Array of chat messages for the current conversation */
25
- messages: Message[];
110
+ messages: UIMessage[];
26
111
  constructor(ctx: AgentContext, env: Env);
27
- onMessage(connection: Connection, message: WSMessage): Promise<void>;
112
+ /**
113
+ * Restore active stream state if the agent was restarted during streaming.
114
+ * Called during construction to recover any interrupted streams.
115
+ * Validates stream freshness to avoid sending stale resume notifications.
116
+ * @internal Protected for testing purposes.
117
+ */
118
+ protected _restoreActiveStream(): void;
119
+ /**
120
+ * Notify a connection about an active stream that can be resumed.
121
+ * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
122
+ * Uses in-memory state for request ID - no extra DB lookup needed.
123
+ * @param connection - The WebSocket connection to notify
124
+ */
125
+ private _notifyStreamResuming;
126
+ /**
127
+ * Send stream chunks to a connection after receiving ACK.
128
+ * @param connection - The WebSocket connection
129
+ * @param streamId - The stream to replay
130
+ * @param requestId - The original request ID
131
+ */
132
+ private _sendStreamChunks;
133
+ /**
134
+ * Buffer a stream chunk for batch write to SQLite.
135
+ * @param streamId - The stream this chunk belongs to
136
+ * @param body - The serialized chunk body
137
+ * @internal Protected for testing purposes.
138
+ */
139
+ protected _storeStreamChunk(streamId: string, body: string): void;
140
+ /**
141
+ * Flush buffered chunks to SQLite in a single batch.
142
+ * Uses a lock to prevent concurrent flush operations.
143
+ * @internal Protected for testing purposes.
144
+ */
145
+ protected _flushChunkBuffer(): void;
146
+ /**
147
+ * Start tracking a new stream for resumable streaming.
148
+ * Creates metadata entry in SQLite and sets up tracking state.
149
+ * @param requestId - The unique ID of the chat request
150
+ * @returns The generated stream ID
151
+ * @internal Protected for testing purposes.
152
+ */
153
+ protected _startStream(requestId: string): string;
154
+ /**
155
+ * Mark a stream as completed and flush any pending chunks.
156
+ * @param streamId - The stream to mark as completed
157
+ * @internal Protected for testing purposes.
158
+ */
159
+ protected _completeStream(streamId: string): void;
160
+ /**
161
+ * Clean up old completed streams if enough time has passed since last cleanup.
162
+ * This prevents database growth while avoiding cleanup overhead on every stream completion.
163
+ */
164
+ private _maybeCleanupOldStreams;
165
+ private _broadcastChatMessage;
166
+ private _loadMessagesFromDb;
28
167
  onRequest(request: Request): Promise<Response>;
168
+ private _tryCatchChat;
29
169
  /**
30
170
  * Handle incoming chat messages and generate a response
31
171
  * @param onFinish Callback to be called when the response is finished
32
- * @param options.signal A signal to pass to any child requests which can be used to cancel them
172
+ * @param options Options including abort signal and client-defined tools
33
173
  * @returns Response to send to the client or undefined
34
174
  */
35
175
  onChatMessage(
36
176
  onFinish: StreamTextOnFinishCallback<ToolSet>,
37
- options?: {
38
- abortSignal: AbortSignal | undefined;
39
- }
177
+ options?: OnChatMessageOptions
40
178
  ): Promise<Response | undefined>;
41
179
  /**
42
- * Save messages on the server side and trigger AI response
180
+ * Save messages on the server side
43
181
  * @param messages Chat messages to save
44
182
  */
45
- saveMessages(messages: Message[]): Promise<void>;
183
+ saveMessages(messages: UIMessage[]): Promise<void>;
46
184
  persistMessages(
47
- messages: Message[],
185
+ messages: UIMessage[],
48
186
  excludeBroadcastIds?: string[]
49
187
  ): Promise<void>;
50
188
  /**
51
- * When the DO is destroyed, cancel all pending requests
189
+ * Merges incoming messages with existing server state.
190
+ * This preserves tool outputs that the server has (via _applyToolResult)
191
+ * but the client doesn't have yet.
192
+ *
193
+ * @param incomingMessages - Messages from the client
194
+ * @returns Messages with server's tool outputs preserved
195
+ */
196
+ private _mergeIncomingWithServerState;
197
+ /**
198
+ * Resolves a message for persistence, handling tool result merging.
199
+ * If the message contains tool parts with output-available state, checks if there's
200
+ * an existing message with the same toolCallId that should be updated instead of
201
+ * creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
202
+ * when client-side tool results arrive in a new request.
203
+ *
204
+ * @param message - The message to potentially merge
205
+ * @returns The message with the correct ID (either original or merged)
206
+ */
207
+ private _resolveMessageForToolMerge;
208
+ /**
209
+ * Finds an existing assistant message that contains a tool part with the given toolCallId.
210
+ * Used to detect when a tool result should update an existing message rather than
211
+ * creating a new one.
212
+ *
213
+ * @param toolCallId - The tool call ID to search for
214
+ * @returns The existing message if found, undefined otherwise
215
+ */
216
+ private _findMessageByToolCallId;
217
+ /**
218
+ * Sanitizes a message for persistence by removing ephemeral provider-specific
219
+ * data that should not be stored or sent back in subsequent requests.
220
+ *
221
+ * This handles two issues with the OpenAI Responses API:
222
+ *
223
+ * 1. **Duplicate item IDs**: The AI SDK's @ai-sdk/openai provider (v2.0.x+)
224
+ * defaults to using OpenAI's Responses API which assigns unique itemIds
225
+ * to each message part. When these IDs are persisted and sent back,
226
+ * OpenAI rejects them as duplicates.
227
+ *
228
+ * 2. **Empty reasoning parts**: OpenAI may return reasoning parts with empty
229
+ * text and encrypted content. These cause "Non-OpenAI reasoning parts are
230
+ * not supported" warnings when sent back via convertToModelMessages().
231
+ *
232
+ * @param message - The message to sanitize
233
+ * @returns A new message with ephemeral provider data removed
234
+ */
235
+ private _sanitizeMessageForPersistence;
236
+ /**
237
+ * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
238
+ * Removes itemId and reasoningEncryptedContent while preserving other fields.
239
+ */
240
+ private _stripOpenAIMetadata;
241
+ /**
242
+ * Applies a tool result to an existing assistant message.
243
+ * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
244
+ * The server is the source of truth, so we update the message here and broadcast
245
+ * the update to all clients.
246
+ *
247
+ * @param toolCallId - The tool call ID this result is for
248
+ * @param toolName - The name of the tool
249
+ * @param output - The output from the tool execution
250
+ * @returns true if the result was applied, false if the message was not found
251
+ */
252
+ private _applyToolResult;
253
+ private _reply;
254
+ /**
255
+ * Mark a stream as errored and clean up state.
256
+ * @param streamId - The stream to mark as errored
257
+ * @internal Protected for testing purposes.
258
+ */
259
+ protected _markStreamError(streamId: string): void;
260
+ /**
261
+ * For the given message id, look up its associated AbortController
262
+ * If the AbortController does not exist, create and store one in memory
263
+ *
264
+ * returns the AbortSignal associated with the AbortController
265
+ */
266
+ private _getAbortSignal;
267
+ /**
268
+ * Remove an abort controller from the cache of pending message responses
269
+ */
270
+ private _removeAbortController;
271
+ /**
272
+ * Propagate an abort signal for any requests associated with the given message id
273
+ */
274
+ private _cancelChatRequest;
275
+ /**
276
+ * Abort all pending requests and clear the cache of AbortControllers
277
+ */
278
+ private _destroyAbortControllers;
279
+ /**
280
+ * When the DO is destroyed, cancel all pending requests and clean up resources
52
281
  */
53
282
  destroy(): Promise<void>;
54
283
  }
55
-
56
- export { AIChatAgent };
284
+ //#endregion
285
+ export {
286
+ AIChatAgent,
287
+ ClientToolSchema,
288
+ OnChatMessageOptions,
289
+ createToolsFromClientSchemas
290
+ };
291
+ //# sourceMappingURL=ai-chat-agent.d.ts.map