agents 0.0.0-4768b8d → 0.0.0-491ef0f

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 (55) hide show
  1. package/README.md +156 -26
  2. package/dist/ai-chat-agent.d.ts +77 -23
  3. package/dist/ai-chat-agent.js +351 -0
  4. package/dist/ai-chat-agent.js.map +1 -0
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +79 -47
  9. package/dist/ai-react.js +310 -0
  10. package/dist/ai-react.js.map +1 -0
  11. package/dist/ai-types.d.ts +83 -41
  12. package/dist/ai-types.js +7 -0
  13. package/dist/ai-types.js.map +1 -0
  14. package/dist/chunk-AVYJQSLW.js +17 -0
  15. package/dist/chunk-AVYJQSLW.js.map +1 -0
  16. package/dist/chunk-LL2AFX7V.js +109 -0
  17. package/dist/chunk-LL2AFX7V.js.map +1 -0
  18. package/dist/chunk-PNF6ZMUA.js +1296 -0
  19. package/dist/chunk-PNF6ZMUA.js.map +1 -0
  20. package/dist/chunk-QEVM4BVL.js +116 -0
  21. package/dist/chunk-QEVM4BVL.js.map +1 -0
  22. package/dist/chunk-UJVEAURM.js +150 -0
  23. package/dist/chunk-UJVEAURM.js.map +1 -0
  24. package/dist/chunk-VYENMKFS.js +612 -0
  25. package/dist/chunk-VYENMKFS.js.map +1 -0
  26. package/dist/client-CcIORE73.d.ts +4607 -0
  27. package/dist/client.d.ts +71 -37
  28. package/dist/client.js +12 -0
  29. package/dist/client.js.map +1 -0
  30. package/dist/index.d.ts +477 -181
  31. package/dist/index.js +31 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/mcp/client.d.ts +11 -675
  34. package/dist/mcp/client.js +9 -0
  35. package/dist/mcp/client.js.map +1 -0
  36. package/dist/mcp/do-oauth-client-provider.d.ts +42 -0
  37. package/dist/mcp/do-oauth-client-provider.js +7 -0
  38. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  39. package/dist/mcp/index.d.ts +79 -8
  40. package/dist/mcp/index.js +956 -0
  41. package/dist/mcp/index.js.map +1 -0
  42. package/dist/observability/index.d.ts +46 -0
  43. package/dist/observability/index.js +11 -0
  44. package/dist/observability/index.js.map +1 -0
  45. package/dist/react.d.ts +108 -15
  46. package/dist/react.js +118 -0
  47. package/dist/react.js.map +1 -0
  48. package/dist/schedule.d.ts +106 -22
  49. package/dist/schedule.js +84 -0
  50. package/dist/schedule.js.map +1 -0
  51. package/dist/serializable.d.ts +32 -0
  52. package/dist/serializable.js +1 -0
  53. package/dist/serializable.js.map +1 -0
  54. package/package.json +88 -52
  55. package/src/index.ts +1175 -156
package/dist/index.d.ts CHANGED
@@ -1,202 +1,401 @@
1
- import { Server, Connection, PartyServerOptions } from 'partyserver';
2
- export { Connection, ConnectionContext, WSMessage } from 'partyserver';
3
- import { AsyncLocalStorage } from 'node:async_hooks';
4
- import { WorkflowEntrypoint as WorkflowEntrypoint$1 } from 'cloudflare:workers';
1
+ import { env } from "cloudflare:workers";
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import {
4
+ ServerCapabilities,
5
+ Tool,
6
+ Prompt,
7
+ Resource
8
+ } from "@modelcontextprotocol/sdk/types.js";
9
+ import { Server, Connection, PartyServerOptions } from "partyserver";
10
+ export { Connection, ConnectionContext, WSMessage } from "partyserver";
11
+ import { M as MCPClientManager } from "./client-CcIORE73.js";
12
+ import { Observability } from "./observability/index.js";
13
+ import { MessageType } from "./ai-types.js";
14
+ import "zod";
15
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
16
+ import "ai";
17
+ import "@modelcontextprotocol/sdk/client/sse.js";
18
+ import "@modelcontextprotocol/sdk/client/streamableHttp.js";
19
+ import "./mcp/do-oauth-client-provider.js";
20
+ import "@modelcontextprotocol/sdk/client/auth.js";
21
+ import "@modelcontextprotocol/sdk/shared/auth.js";
5
22
 
6
23
  /**
7
24
  * RPC request message from client
8
25
  */
9
26
  type RPCRequest = {
10
- type: "rpc";
11
- id: string;
12
- method: string;
13
- args: unknown[];
27
+ type: "rpc";
28
+ id: string;
29
+ method: string;
30
+ args: unknown[];
14
31
  };
15
32
  /**
16
33
  * State update message from client
17
34
  */
18
35
  type StateUpdateMessage = {
19
- type: "cf_agent_state";
20
- state: unknown;
36
+ type: MessageType.CF_AGENT_STATE;
37
+ state: unknown;
21
38
  };
22
39
  /**
23
40
  * RPC response message to client
24
41
  */
25
42
  type RPCResponse = {
26
- type: "rpc";
27
- id: string;
28
- } & ({
29
- success: true;
30
- result: unknown;
31
- done?: false;
32
- } | {
33
- success: true;
34
- result: unknown;
35
- done: true;
36
- } | {
37
- success: false;
38
- error: string;
39
- });
43
+ type: MessageType.RPC;
44
+ id: string;
45
+ } & (
46
+ | {
47
+ success: true;
48
+ result: unknown;
49
+ done?: false;
50
+ }
51
+ | {
52
+ success: true;
53
+ result: unknown;
54
+ done: true;
55
+ }
56
+ | {
57
+ success: false;
58
+ error: string;
59
+ }
60
+ );
40
61
  /**
41
62
  * Metadata for a callable method
42
63
  */
43
64
  type CallableMetadata = {
44
- /** Optional description of what the method does */
45
- description?: string;
46
- /** Whether the method supports streaming responses */
47
- streaming?: boolean;
65
+ /** Optional description of what the method does */
66
+ description?: string;
67
+ /** Whether the method supports streaming responses */
68
+ streaming?: boolean;
48
69
  };
49
70
  /**
50
71
  * Decorator that marks a method as callable by clients
51
72
  * @param metadata Optional metadata about the callable method
52
73
  */
53
- declare function unstable_callable(metadata?: CallableMetadata): <This, Args extends unknown[], Return>(target: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext) => (this: This, ...args: Args) => Return;
74
+ declare function callable(
75
+ metadata?: CallableMetadata
76
+ ): <This, Args extends unknown[], Return>(
77
+ target: (this: This, ...args: Args) => Return,
78
+ context: ClassMethodDecoratorContext
79
+ ) => (this: This, ...args: Args) => Return;
54
80
  /**
55
- * A class for creating workflow entry points that can be used with Cloudflare Workers
81
+ * Decorator that marks a method as callable by clients
82
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
83
+ * @param metadata Optional metadata about the callable method
56
84
  */
57
- declare class WorkflowEntrypoint extends WorkflowEntrypoint$1 {
58
- }
85
+ declare const unstable_callable: (metadata?: CallableMetadata) => void;
86
+ type QueueItem<T = string> = {
87
+ id: string;
88
+ payload: T;
89
+ callback: keyof Agent<unknown>;
90
+ created_at: number;
91
+ };
59
92
  /**
60
93
  * Represents a scheduled task within an Agent
61
94
  * @template T Type of the payload data
62
95
  */
63
96
  type Schedule<T = string> = {
64
- /** Unique identifier for the schedule */
65
- id: string;
66
- /** Name of the method to be called */
67
- callback: string;
68
- /** Data to be passed to the callback */
69
- payload: T;
70
- } & ({
71
- /** Type of schedule for one-time execution at a specific time */
72
- type: "scheduled";
73
- /** Timestamp when the task should execute */
74
- time: number;
75
- } | {
76
- /** Type of schedule for delayed execution */
77
- type: "delayed";
78
- /** Timestamp when the task should execute */
79
- time: number;
80
- /** Number of seconds to delay execution */
81
- delayInSeconds: number;
82
- } | {
83
- /** Type of schedule for recurring execution based on cron expression */
84
- type: "cron";
85
- /** Timestamp for the next execution */
86
- time: number;
87
- /** Cron expression defining the schedule */
88
- cron: string;
89
- });
90
- declare const unstable_context: AsyncLocalStorage<{
91
- agent: Agent<unknown>;
92
- connection: Connection | undefined;
93
- request: Request | undefined;
94
- }>;
97
+ /** Unique identifier for the schedule */
98
+ id: string;
99
+ /** Name of the method to be called */
100
+ callback: string;
101
+ /** Data to be passed to the callback */
102
+ payload: T;
103
+ } & (
104
+ | {
105
+ /** Type of schedule for one-time execution at a specific time */
106
+ type: "scheduled";
107
+ /** Timestamp when the task should execute */
108
+ time: number;
109
+ }
110
+ | {
111
+ /** Type of schedule for delayed execution */
112
+ type: "delayed";
113
+ /** Timestamp when the task should execute */
114
+ time: number;
115
+ /** Number of seconds to delay execution */
116
+ delayInSeconds: number;
117
+ }
118
+ | {
119
+ /** Type of schedule for recurring execution based on cron expression */
120
+ type: "cron";
121
+ /** Timestamp for the next execution */
122
+ time: number;
123
+ /** Cron expression defining the schedule */
124
+ cron: string;
125
+ }
126
+ );
127
+ /**
128
+ * MCP Server state update message from server -> Client
129
+ */
130
+ type MCPServerMessage = {
131
+ type: MessageType.CF_AGENT_MCP_SERVERS;
132
+ mcp: MCPServersState;
133
+ };
134
+ type MCPServersState = {
135
+ servers: {
136
+ [id: string]: MCPServer;
137
+ };
138
+ tools: Tool[];
139
+ prompts: Prompt[];
140
+ resources: Resource[];
141
+ };
142
+ type MCPServer = {
143
+ name: string;
144
+ server_url: string;
145
+ auth_url: string | null;
146
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
147
+ instructions: string | null;
148
+ capabilities: ServerCapabilities | null;
149
+ };
150
+ declare function getCurrentAgent<
151
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
152
+ >(): {
153
+ agent: T | undefined;
154
+ connection: Connection | undefined;
155
+ request: Request | undefined;
156
+ email: AgentEmail | undefined;
157
+ };
95
158
  /**
96
159
  * Base class for creating Agent implementations
97
160
  * @template Env Environment type containing bindings
98
161
  * @template State State type to store within the Agent
99
162
  */
100
- declare class Agent<Env, State = unknown> extends Server<Env> {
101
- #private;
102
- /**
103
- * Initial state for the Agent
104
- * Override to provide default state values
105
- */
106
- initialState: State;
107
- /**
108
- * Current state of the Agent
109
- */
110
- get state(): State;
111
- /**
112
- * Agent configuration options
113
- */
114
- static options: {
115
- /** Whether the Agent should hibernate when inactive */
116
- hibernate: boolean;
163
+ declare class Agent<Env = typeof env, State = unknown> extends Server<Env> {
164
+ private _state;
165
+ private _ParentClass;
166
+ mcp: MCPClientManager;
167
+ /**
168
+ * Initial state for the Agent
169
+ * Override to provide default state values
170
+ */
171
+ initialState: State;
172
+ /**
173
+ * Current state of the Agent
174
+ */
175
+ get state(): State;
176
+ /**
177
+ * Agent configuration options
178
+ */
179
+ static options: {
180
+ /** Whether the Agent should hibernate when inactive */
181
+ hibernate: boolean;
182
+ };
183
+ /**
184
+ * The observability implementation to use for the Agent
185
+ */
186
+ observability?: Observability;
187
+ /**
188
+ * Execute SQL queries against the Agent's database
189
+ * @template T Type of the returned rows
190
+ * @param strings SQL query template strings
191
+ * @param values Values to be inserted into the query
192
+ * @returns Array of query results
193
+ */
194
+ sql<T = Record<string, string | number | boolean | null>>(
195
+ strings: TemplateStringsArray,
196
+ ...values: (string | number | boolean | null)[]
197
+ ): T[];
198
+ constructor(ctx: AgentContext, env: Env);
199
+ private _setStateInternal;
200
+ /**
201
+ * Update the Agent's state
202
+ * @param state New state to set
203
+ */
204
+ setState(state: State): void;
205
+ /**
206
+ * Called when the Agent's state is updated
207
+ * @param state Updated state
208
+ * @param source Source of the state update ("server" or a client connection)
209
+ */
210
+ onStateUpdate(state: State | undefined, source: Connection | "server"): void;
211
+ /**
212
+ * Called when the Agent receives an email via routeAgentEmail()
213
+ * Override this method to handle incoming emails
214
+ * @param email Email message to process
215
+ */
216
+ _onEmail(email: AgentEmail): Promise<void>;
217
+ /**
218
+ * Reply to an email
219
+ * @param email The email to reply to
220
+ * @param options Options for the reply
221
+ * @returns void
222
+ */
223
+ replyToEmail(
224
+ email: AgentEmail,
225
+ options: {
226
+ fromName: string;
227
+ subject?: string | undefined;
228
+ body: string;
229
+ contentType?: string;
230
+ headers?: Record<string, string>;
231
+ }
232
+ ): Promise<void>;
233
+ private _tryCatch;
234
+ /**
235
+ * Automatically wrap custom methods with agent context
236
+ * This ensures getCurrentAgent() works in all custom methods without decorators
237
+ */
238
+ private _autoWrapCustomMethods;
239
+ onError(connection: Connection, error: unknown): void | Promise<void>;
240
+ onError(error: unknown): void | Promise<void>;
241
+ /**
242
+ * Render content (not implemented in base class)
243
+ */
244
+ render(): void;
245
+ /**
246
+ * Queue a task to be executed in the future
247
+ * @param payload Payload to pass to the callback
248
+ * @param callback Name of the method to call
249
+ * @returns The ID of the queued task
250
+ */
251
+ queue<T = unknown>(callback: keyof this, payload: T): Promise<string>;
252
+ private _flushingQueue;
253
+ private _flushQueue;
254
+ /**
255
+ * Dequeue a task by ID
256
+ * @param id ID of the task to dequeue
257
+ */
258
+ dequeue(id: string): Promise<void>;
259
+ /**
260
+ * Dequeue all tasks
261
+ */
262
+ dequeueAll(): Promise<void>;
263
+ /**
264
+ * Dequeue all tasks by callback
265
+ * @param callback Name of the callback to dequeue
266
+ */
267
+ dequeueAllByCallback(callback: string): Promise<void>;
268
+ /**
269
+ * Get a queued task by ID
270
+ * @param id ID of the task to get
271
+ * @returns The task or undefined if not found
272
+ */
273
+ getQueue(id: string): Promise<QueueItem<string> | undefined>;
274
+ /**
275
+ * Get all queues by key and value
276
+ * @param key Key to filter by
277
+ * @param value Value to filter by
278
+ * @returns Array of matching QueueItem objects
279
+ */
280
+ getQueues(key: string, value: string): Promise<QueueItem<string>[]>;
281
+ /**
282
+ * Schedule a task to be executed in the future
283
+ * @template T Type of the payload data
284
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
285
+ * @param callback Name of the method to call
286
+ * @param payload Data to pass to the callback
287
+ * @returns Schedule object representing the scheduled task
288
+ */
289
+ schedule<T = string>(
290
+ when: Date | string | number,
291
+ callback: keyof this,
292
+ payload?: T
293
+ ): Promise<Schedule<T>>;
294
+ /**
295
+ * Get a scheduled task by ID
296
+ * @template T Type of the payload data
297
+ * @param id ID of the scheduled task
298
+ * @returns The Schedule object or undefined if not found
299
+ */
300
+ getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
301
+ /**
302
+ * Get scheduled tasks matching the given criteria
303
+ * @template T Type of the payload data
304
+ * @param criteria Criteria to filter schedules
305
+ * @returns Array of matching Schedule objects
306
+ */
307
+ getSchedules<T = string>(criteria?: {
308
+ id?: string;
309
+ type?: "scheduled" | "delayed" | "cron";
310
+ timeRange?: {
311
+ start?: Date;
312
+ end?: Date;
117
313
  };
118
- /**
119
- * Execute SQL queries against the Agent's database
120
- * @template T Type of the returned rows
121
- * @param strings SQL query template strings
122
- * @param values Values to be inserted into the query
123
- * @returns Array of query results
124
- */
125
- sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
126
- constructor(ctx: AgentContext, env: Env);
127
- /**
128
- * Update the Agent's state
129
- * @param state New state to set
130
- */
131
- setState(state: State): void;
132
- /**
133
- * Called when the Agent's state is updated
134
- * @param state Updated state
135
- * @param source Source of the state update ("server" or a client connection)
136
- */
137
- onStateUpdate(state: State | undefined, source: Connection | "server"): void;
138
- /**
139
- * Called when the Agent receives an email
140
- * @param email Email message to process
141
- */
142
- onEmail(email: ForwardableEmailMessage): Promise<void>;
143
- onError(connection: Connection, error: unknown): void | Promise<void>;
144
- onError(error: unknown): void | Promise<void>;
145
- /**
146
- * Render content (not implemented in base class)
147
- */
148
- render(): void;
149
- /**
150
- * Schedule a task to be executed in the future
151
- * @template T Type of the payload data
152
- * @param when When to execute the task (Date, seconds delay, or cron expression)
153
- * @param callback Name of the method to call
154
- * @param payload Data to pass to the callback
155
- * @returns Schedule object representing the scheduled task
156
- */
157
- schedule<T = string>(when: Date | string | number, callback: keyof this, payload?: T): Promise<Schedule<T>>;
158
- /**
159
- * Get a scheduled task by ID
160
- * @template T Type of the payload data
161
- * @param id ID of the scheduled task
162
- * @returns The Schedule object or undefined if not found
163
- */
164
- getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
165
- /**
166
- * Get scheduled tasks matching the given criteria
167
- * @template T Type of the payload data
168
- * @param criteria Criteria to filter schedules
169
- * @returns Array of matching Schedule objects
170
- */
171
- getSchedules<T = string>(criteria?: {
172
- id?: string;
173
- type?: "scheduled" | "delayed" | "cron";
174
- timeRange?: {
175
- start?: Date;
176
- end?: Date;
177
- };
178
- }): Schedule<T>[];
179
- /**
180
- * Cancel a scheduled task
181
- * @param id ID of the task to cancel
182
- * @returns true if the task was cancelled, false otherwise
183
- */
184
- cancelSchedule(id: string): Promise<boolean>;
185
- /**
186
- * Method called when an alarm fires
187
- * Executes any scheduled tasks that are due
188
- */
189
- alarm(): Promise<void>;
190
- /**
191
- * Destroy the Agent, removing all state and scheduled tasks
192
- */
193
- destroy(): Promise<void>;
314
+ }): Schedule<T>[];
315
+ /**
316
+ * Cancel a scheduled task
317
+ * @param id ID of the task to cancel
318
+ * @returns true if the task was cancelled, false otherwise
319
+ */
320
+ cancelSchedule(id: string): Promise<boolean>;
321
+ private _scheduleNextAlarm;
322
+ /**
323
+ * Method called when an alarm fires.
324
+ * Executes any scheduled tasks that are due.
325
+ *
326
+ * @remarks
327
+ * To schedule a task, please use the `this.schedule` method instead.
328
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
329
+ */
330
+ readonly alarm: () => Promise<void>;
331
+ /**
332
+ * Destroy the Agent, removing all state and scheduled tasks
333
+ */
334
+ destroy(): Promise<void>;
335
+ /**
336
+ * Get all methods marked as callable on this Agent
337
+ * @returns A map of method names to their metadata
338
+ */
339
+ private _isCallable;
340
+ /**
341
+ * Connect to a new MCP Server
342
+ *
343
+ * @param url MCP Server SSE URL
344
+ * @param callbackHost Base host for the agent, used for the redirect URI.
345
+ * @param agentsPrefix agents routing prefix if not using `agents`
346
+ * @param options MCP client and transport (header) options
347
+ * @returns authUrl
348
+ */
349
+ addMcpServer(
350
+ serverName: string,
351
+ url: string,
352
+ callbackHost: string,
353
+ agentsPrefix?: string,
354
+ options?: {
355
+ client?: ConstructorParameters<typeof Client>[1];
356
+ transport?: {
357
+ headers: HeadersInit;
358
+ };
359
+ }
360
+ ): Promise<{
361
+ id: string;
362
+ authUrl: string | undefined;
363
+ }>;
364
+ _connectToMcpServerInternal(
365
+ _serverName: string,
366
+ url: string,
367
+ callbackUrl: string,
368
+ options?: {
369
+ client?: ConstructorParameters<typeof Client>[1];
370
+ /**
371
+ * We don't expose the normal set of transport options because:
372
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
373
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
374
+ *
375
+ * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
376
+ */
377
+ transport?: {
378
+ headers?: HeadersInit;
379
+ };
380
+ },
381
+ reconnect?: {
382
+ id: string;
383
+ oauthClientId?: string;
384
+ }
385
+ ): Promise<{
386
+ id: string;
387
+ authUrl: string | undefined;
388
+ clientId: string | undefined;
389
+ }>;
390
+ removeMcpServer(id: string): Promise<void>;
391
+ getMcpServers(): MCPServersState;
194
392
  }
195
393
  /**
196
394
  * Namespace for creating Agent instances
197
395
  * @template Agentic Type of the Agent class
198
396
  */
199
- type AgentNamespace<Agentic extends Agent<unknown>> = DurableObjectNamespace<Agentic>;
397
+ type AgentNamespace<Agentic extends Agent<unknown>> =
398
+ DurableObjectNamespace<Agentic>;
200
399
  /**
201
400
  * Agent's durable context
202
401
  */
@@ -205,10 +404,10 @@ type AgentContext = DurableObjectState;
205
404
  * Configuration options for Agent routing
206
405
  */
207
406
  type AgentOptions<Env> = PartyServerOptions<Env> & {
208
- /**
209
- * Whether to enable CORS for the Agent
210
- */
211
- cors?: boolean | HeadersInit | undefined;
407
+ /**
408
+ * Whether to enable CORS for the Agent
409
+ */
410
+ cors?: boolean | HeadersInit | undefined;
212
411
  };
213
412
  /**
214
413
  * Route a request to the appropriate Agent
@@ -217,14 +416,77 @@ type AgentOptions<Env> = PartyServerOptions<Env> & {
217
416
  * @param options Routing options
218
417
  * @returns Response from the Agent or undefined if no route matched
219
418
  */
220
- declare function routeAgentRequest<Env>(request: Request, env: Env, options?: AgentOptions<Env>): Promise<Response | null>;
419
+ declare function routeAgentRequest<Env>(
420
+ request: Request,
421
+ env: Env,
422
+ options?: AgentOptions<Env>
423
+ ): Promise<Response | null>;
424
+ type EmailResolver<Env> = (
425
+ email: ForwardableEmailMessage,
426
+ env: Env
427
+ ) => Promise<{
428
+ agentName: string;
429
+ agentId: string;
430
+ } | null>;
431
+ /**
432
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
433
+ * @returns A function that resolves the agent to route the email to
434
+ */
435
+ declare function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env>;
436
+ /**
437
+ * Create a resolver that uses the email address to determine the agent to route the email to
438
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
439
+ * @returns A function that resolves the agent to route the email to
440
+ */
441
+ declare function createAddressBasedEmailResolver<Env>(
442
+ defaultAgentName: string
443
+ ): EmailResolver<Env>;
444
+ /**
445
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
446
+ * @param agentName The name of the agent to route the email to
447
+ * @param agentId The id of the agent to route the email to
448
+ * @returns A function that resolves the agent to route the email to
449
+ */
450
+ declare function createCatchAllEmailResolver<Env>(
451
+ agentName: string,
452
+ agentId: string
453
+ ): EmailResolver<Env>;
454
+ type EmailRoutingOptions<Env> = AgentOptions<Env> & {
455
+ resolver: EmailResolver<Env>;
456
+ };
221
457
  /**
222
458
  * Route an email to the appropriate Agent
223
- * @param email Email message to route
224
- * @param env Environment containing Agent bindings
225
- * @param options Routing options
459
+ * @param email The email to route
460
+ * @param env The environment containing the Agent bindings
461
+ * @param options The options for routing the email
462
+ * @returns A promise that resolves when the email has been routed
226
463
  */
227
- declare function routeAgentEmail<Env>(email: ForwardableEmailMessage, env: Env, options?: AgentOptions<Env>): Promise<void>;
464
+ declare function routeAgentEmail<Env>(
465
+ email: ForwardableEmailMessage,
466
+ env: Env,
467
+ options: EmailRoutingOptions<Env>
468
+ ): Promise<void>;
469
+ type AgentEmail = {
470
+ from: string;
471
+ to: string;
472
+ getRaw: () => Promise<Uint8Array>;
473
+ headers: Headers;
474
+ rawSize: number;
475
+ setReject: (reason: string) => void;
476
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
477
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
478
+ };
479
+ type EmailSendOptions = {
480
+ to: string;
481
+ subject: string;
482
+ body: string;
483
+ contentType?: string;
484
+ headers?: Record<string, string>;
485
+ includeRoutingHeaders?: boolean;
486
+ agentName?: string;
487
+ agentId?: string;
488
+ domain?: string;
489
+ };
228
490
  /**
229
491
  * Get or create an Agent by name
230
492
  * @template Env Environment type containing bindings
@@ -234,26 +496,60 @@ declare function routeAgentEmail<Env>(email: ForwardableEmailMessage, env: Env,
234
496
  * @param options Options for Agent creation
235
497
  * @returns Promise resolving to an Agent instance stub
236
498
  */
237
- declare function getAgentByName<Env, T extends Agent<Env>>(namespace: AgentNamespace<T>, name: string, options?: {
499
+ declare function getAgentByName<Env, T extends Agent<Env>>(
500
+ namespace: AgentNamespace<T>,
501
+ name: string,
502
+ options?: {
238
503
  jurisdiction?: DurableObjectJurisdiction;
239
504
  locationHint?: DurableObjectLocationHint;
240
- }): Promise<DurableObjectStub<T>>;
505
+ }
506
+ ): Promise<DurableObjectStub<T>>;
241
507
  /**
242
508
  * A wrapper for streaming responses in callable methods
243
509
  */
244
510
  declare class StreamingResponse {
245
- #private;
246
- constructor(connection: Connection, id: string);
247
- /**
248
- * Send a chunk of data to the client
249
- * @param chunk The data to send
250
- */
251
- send(chunk: unknown): void;
252
- /**
253
- * End the stream and send the final chunk (if any)
254
- * @param finalChunk Optional final chunk of data to send
255
- */
256
- end(finalChunk?: unknown): void;
511
+ private _connection;
512
+ private _id;
513
+ private _closed;
514
+ constructor(connection: Connection, id: string);
515
+ /**
516
+ * Send a chunk of data to the client
517
+ * @param chunk The data to send
518
+ */
519
+ send(chunk: unknown): void;
520
+ /**
521
+ * End the stream and send the final chunk (if any)
522
+ * @param finalChunk Optional final chunk of data to send
523
+ */
524
+ end(finalChunk?: unknown): void;
257
525
  }
258
526
 
259
- export { Agent, type AgentContext, type AgentNamespace, type AgentOptions, type CallableMetadata, type RPCRequest, type RPCResponse, type Schedule, type StateUpdateMessage, StreamingResponse, WorkflowEntrypoint, getAgentByName, routeAgentEmail, routeAgentRequest, unstable_callable, unstable_context };
527
+ export {
528
+ Agent,
529
+ type AgentContext,
530
+ type AgentEmail,
531
+ type AgentNamespace,
532
+ type AgentOptions,
533
+ type CallableMetadata,
534
+ type EmailResolver,
535
+ type EmailRoutingOptions,
536
+ type EmailSendOptions,
537
+ type MCPServer,
538
+ type MCPServerMessage,
539
+ type MCPServersState,
540
+ type QueueItem,
541
+ type RPCRequest,
542
+ type RPCResponse,
543
+ type Schedule,
544
+ type StateUpdateMessage,
545
+ StreamingResponse,
546
+ callable,
547
+ createAddressBasedEmailResolver,
548
+ createCatchAllEmailResolver,
549
+ createHeaderBasedEmailResolver,
550
+ getAgentByName,
551
+ getCurrentAgent,
552
+ routeAgentEmail,
553
+ routeAgentRequest,
554
+ unstable_callable
555
+ };