agents 0.0.0-f641104 → 0.0.0-f64700e

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 (71) hide show
  1. package/README.md +257 -33
  2. package/dist/ai-chat-agent.d.ts +59 -10
  3. package/dist/ai-chat-agent.js +532 -159
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  6. package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -72
  10. package/dist/ai-react.js +261 -185
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  13. package/dist/ai-types-UZlfLOYP.js +20 -0
  14. package/dist/ai-types-UZlfLOYP.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/client-C-nwz-3N.d.ts +5313 -0
  18. package/dist/client-CZBVDDoO.js +786 -0
  19. package/dist/client-CZBVDDoO.js.map +1 -0
  20. package/dist/client-CmMi85Sj.d.ts +104 -0
  21. package/dist/client-DjR-lC16.js +117 -0
  22. package/dist/client-DjR-lC16.js.map +1 -0
  23. package/dist/client.d.ts +12 -79
  24. package/dist/client.js +3 -137
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  29. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  30. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  31. package/dist/index-CMEWpbHx.d.ts +568 -0
  32. package/dist/index-W4JUkafc.d.ts +54 -0
  33. package/dist/index.d.ts +63 -295
  34. package/dist/index.js +7 -20
  35. package/dist/mcp/client.d.ts +4 -0
  36. package/dist/mcp/client.js +3 -0
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -0
  38. package/dist/mcp/do-oauth-client-provider.js +3 -0
  39. package/dist/mcp/index.d.ts +75 -0
  40. package/dist/mcp/index.js +847 -0
  41. package/dist/mcp/index.js.map +1 -0
  42. package/dist/mcp/x402.d.ts +34 -0
  43. package/dist/mcp/x402.js +194 -0
  44. package/dist/mcp/x402.js.map +1 -0
  45. package/dist/mcp-BEwaCsxO.d.ts +61 -0
  46. package/dist/observability/index.d.ts +3 -0
  47. package/dist/observability/index.js +7 -0
  48. package/dist/react-jvtffQuA.d.ts +113 -0
  49. package/dist/react.d.ts +10 -39
  50. package/dist/react.js +185 -93
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +89 -12
  53. package/dist/schedule.js +46 -23
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  56. package/dist/serializable.d.ts +7 -0
  57. package/dist/serializable.js +1 -0
  58. package/dist/src-L3cHuAag.js +1231 -0
  59. package/dist/src-L3cHuAag.js.map +1 -0
  60. package/package.json +118 -51
  61. package/src/index.ts +1463 -184
  62. package/dist/ai-types.js.map +0 -1
  63. package/dist/chunk-HMLY7DHA.js +0 -16
  64. package/dist/chunk-HMLY7DHA.js.map +0 -1
  65. package/dist/chunk-X6BBKLSC.js +0 -568
  66. package/dist/chunk-X6BBKLSC.js.map +0 -1
  67. package/dist/client.js.map +0 -1
  68. package/dist/index.js.map +0 -1
  69. package/dist/mcp.d.ts +0 -58
  70. package/dist/mcp.js +0 -945
  71. package/dist/mcp.js.map +0 -1
package/src/index.ts CHANGED
@@ -1,19 +1,36 @@
1
+ import type { env } from "cloudflare:workers";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
5
+
6
+ import type {
7
+ Prompt,
8
+ Resource,
9
+ ServerCapabilities,
10
+ Tool
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+ import { parseCronExpression } from "cron-schedule";
13
+ import { nanoid } from "nanoid";
14
+ import { EmailMessage } from "cloudflare:email";
1
15
  import {
2
- Server,
3
- routePartykitRequest,
4
- type PartyServerOptions,
5
- getServerByName,
6
16
  type Connection,
7
17
  type ConnectionContext,
18
+ type PartyServerOptions,
19
+ Server,
8
20
  type WSMessage,
21
+ getServerByName,
22
+ routePartykitRequest
9
23
  } from "partyserver";
24
+ import { camelCaseToKebabCase } from "./client";
25
+ import { MCPClientManager, type MCPClientOAuthResult } from "./mcp/client";
26
+ import type { MCPConnectionState } from "./mcp/client-connection";
27
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
+ import type { TransportType } from "./mcp/types";
29
+ import { genericObservability, type Observability } from "./observability";
30
+ import { DisposableStore } from "./core/events";
31
+ import { MessageType } from "./ai-types";
10
32
 
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
15
-
16
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
33
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
17
34
 
18
35
  /**
19
36
  * RPC request message from client
@@ -29,7 +46,7 @@ export type RPCRequest = {
29
46
  * State update message from client
30
47
  */
31
48
  export type StateUpdateMessage = {
32
- type: "cf_agent_state";
49
+ type: MessageType.CF_AGENT_STATE;
33
50
  state: unknown;
34
51
  };
35
52
 
@@ -37,7 +54,7 @@ export type StateUpdateMessage = {
37
54
  * RPC response message to client
38
55
  */
39
56
  export type RPCResponse = {
40
- type: "rpc";
57
+ type: MessageType.RPC;
41
58
  id: string;
42
59
  } & (
43
60
  | {
@@ -64,7 +81,7 @@ function isRPCRequest(msg: unknown): msg is RPCRequest {
64
81
  typeof msg === "object" &&
65
82
  msg !== null &&
66
83
  "type" in msg &&
67
- msg.type === "rpc" &&
84
+ msg.type === MessageType.RPC &&
68
85
  "id" in msg &&
69
86
  typeof msg.id === "string" &&
70
87
  "method" in msg &&
@@ -82,7 +99,7 @@ function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
82
99
  typeof msg === "object" &&
83
100
  msg !== null &&
84
101
  "type" in msg &&
85
- msg.type === "cf_agent_state" &&
102
+ msg.type === MessageType.CF_AGENT_STATE &&
86
103
  "state" in msg
87
104
  );
88
105
  }
@@ -97,16 +114,16 @@ export type CallableMetadata = {
97
114
  streaming?: boolean;
98
115
  };
99
116
 
100
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
101
117
  const callableMetadata = new Map<Function, CallableMetadata>();
102
118
 
103
119
  /**
104
120
  * Decorator that marks a method as callable by clients
105
121
  * @param metadata Optional metadata about the callable method
106
122
  */
107
- export function unstable_callable(metadata: CallableMetadata = {}) {
123
+ export function callable(metadata: CallableMetadata = {}) {
108
124
  return function callableDecorator<This, Args extends unknown[], Return>(
109
125
  target: (this: This, ...args: Args) => Return,
126
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
110
127
  context: ClassMethodDecoratorContext
111
128
  ) {
112
129
  if (!callableMetadata.has(target)) {
@@ -117,10 +134,29 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
117
134
  };
118
135
  }
119
136
 
137
+ let didWarnAboutUnstableCallable = false;
138
+
120
139
  /**
121
- * A class for creating workflow entry points that can be used with Cloudflare Workers
140
+ * Decorator that marks a method as callable by clients
141
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
142
+ * @param metadata Optional metadata about the callable method
122
143
  */
123
- export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
144
+ export const unstable_callable = (metadata: CallableMetadata = {}) => {
145
+ if (!didWarnAboutUnstableCallable) {
146
+ didWarnAboutUnstableCallable = true;
147
+ console.warn(
148
+ "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
149
+ );
150
+ }
151
+ callable(metadata);
152
+ };
153
+
154
+ export type QueueItem<T = string> = {
155
+ id: string;
156
+ payload: T;
157
+ callback: keyof Agent<unknown>;
158
+ created_at: number;
159
+ };
124
160
 
125
161
  /**
126
162
  * Represents a scheduled task within an Agent
@@ -163,18 +199,134 @@ function getNextCronTime(cron: string) {
163
199
  return interval.getNextDate();
164
200
  }
165
201
 
202
+ export type { TransportType } from "./mcp/types";
203
+
204
+ /**
205
+ * MCP Server state update message from server -> Client
206
+ */
207
+ export type MCPServerMessage = {
208
+ type: MessageType.CF_AGENT_MCP_SERVERS;
209
+ mcp: MCPServersState;
210
+ };
211
+
212
+ export type MCPServersState = {
213
+ servers: {
214
+ [id: string]: MCPServer;
215
+ };
216
+ tools: Tool[];
217
+ prompts: Prompt[];
218
+ resources: Resource[];
219
+ };
220
+
221
+ export type MCPServer = {
222
+ name: string;
223
+ server_url: string;
224
+ auth_url: string | null;
225
+ // This state is specifically about the temporary process of getting a token (if needed).
226
+ // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
227
+ // to communicate a change to a non-ready state.
228
+ state: MCPConnectionState;
229
+ instructions: string | null;
230
+ capabilities: ServerCapabilities | null;
231
+ };
232
+
233
+ /**
234
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
235
+ */
236
+ type MCPServerRow = {
237
+ id: string;
238
+ name: string;
239
+ server_url: string;
240
+ client_id: string | null;
241
+ auth_url: string | null;
242
+ callback_url: string;
243
+ server_options: string;
244
+ };
245
+
166
246
  const STATE_ROW_ID = "cf_state_row_id";
167
247
  const STATE_WAS_CHANGED = "cf_state_was_changed";
168
248
 
169
249
  const DEFAULT_STATE = {} as unknown;
170
250
 
251
+ const agentContext = new AsyncLocalStorage<{
252
+ agent: Agent<unknown, unknown>;
253
+ connection: Connection | undefined;
254
+ request: Request | undefined;
255
+ email: AgentEmail | undefined;
256
+ }>();
257
+
258
+ export function getCurrentAgent<
259
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
260
+ >(): {
261
+ agent: T | undefined;
262
+ connection: Connection | undefined;
263
+ request: Request | undefined;
264
+ email: AgentEmail | undefined;
265
+ } {
266
+ const store = agentContext.getStore() as
267
+ | {
268
+ agent: T;
269
+ connection: Connection | undefined;
270
+ request: Request | undefined;
271
+ email: AgentEmail | undefined;
272
+ }
273
+ | undefined;
274
+ if (!store) {
275
+ return {
276
+ agent: undefined,
277
+ connection: undefined,
278
+ request: undefined,
279
+ email: undefined
280
+ };
281
+ }
282
+ return store;
283
+ }
284
+
285
+ /**
286
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
287
+ * @param agent The agent instance
288
+ * @param method The method to wrap
289
+ * @returns A wrapped method that runs within the agent context
290
+ */
291
+
292
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
293
+ function withAgentContext<T extends (...args: any[]) => any>(
294
+ method: T
295
+ ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
296
+ return function (...args: Parameters<T>): ReturnType<T> {
297
+ const { connection, request, email, agent } = getCurrentAgent();
298
+
299
+ if (agent === this) {
300
+ // already wrapped, so we can just call the method
301
+ return method.apply(this, args);
302
+ }
303
+ // not wrapped, so we need to wrap it
304
+ return agentContext.run({ agent: this, connection, request, email }, () => {
305
+ return method.apply(this, args);
306
+ });
307
+ };
308
+ }
309
+
171
310
  /**
172
311
  * Base class for creating Agent implementations
173
312
  * @template Env Environment type containing bindings
174
313
  * @template State State type to store within the Agent
175
314
  */
176
- export class Agent<Env, State = unknown> extends Server<Env> {
177
- #state = DEFAULT_STATE as State;
315
+ export class Agent<
316
+ Env = typeof env,
317
+ State = unknown,
318
+ Props extends Record<string, unknown> = Record<string, unknown>
319
+ > extends Server<Env, Props> {
320
+ private _state = DEFAULT_STATE as State;
321
+ private _disposables = new DisposableStore();
322
+
323
+ private _ParentClass: typeof Agent<Env, State> =
324
+ Object.getPrototypeOf(this).constructor;
325
+
326
+ readonly mcp: MCPClientManager = new MCPClientManager(
327
+ this._ParentClass.name,
328
+ "0.0.1"
329
+ );
178
330
 
179
331
  /**
180
332
  * Initial state for the Agent
@@ -186,9 +338,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
186
338
  * Current state of the Agent
187
339
  */
188
340
  get state(): State {
189
- if (this.#state !== DEFAULT_STATE) {
341
+ if (this._state !== DEFAULT_STATE) {
190
342
  // state was previously set, and populated internal state
191
- return this.#state;
343
+ return this._state;
192
344
  }
193
345
  // looks like this is the first time the state is being accessed
194
346
  // check if the state was set in a previous life
@@ -208,8 +360,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
208
360
  ) {
209
361
  const state = result[0]?.state as string; // could be null?
210
362
 
211
- this.#state = JSON.parse(state);
212
- return this.#state;
363
+ this._state = JSON.parse(state);
364
+ return this._state;
213
365
  }
214
366
 
215
367
  // ok, this is the first time the state is being accessed
@@ -230,9 +382,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
230
382
  */
231
383
  static options = {
232
384
  /** Whether the Agent should hibernate when inactive */
233
- hibernate: true, // default to hibernate
385
+ hibernate: true // default to hibernate
234
386
  };
235
387
 
388
+ /**
389
+ * The observability implementation to use for the Agent
390
+ */
391
+ observability?: Observability = genericObservability;
392
+
236
393
  /**
237
394
  * Execute SQL queries against the Agent's database
238
395
  * @template T Type of the returned rows
@@ -262,6 +419,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
262
419
  constructor(ctx: AgentContext, env: Env) {
263
420
  super(ctx, env);
264
421
 
422
+ if (!wrappedClasses.has(this.constructor)) {
423
+ // Auto-wrap custom methods with agent context
424
+ this._autoWrapCustomMethods();
425
+ wrappedClasses.add(this.constructor);
426
+ }
427
+
428
+ // Broadcast server state after background connects (for OAuth servers)
429
+ this._disposables.add(
430
+ this.mcp.onConnected(async () => {
431
+ this.broadcastMcpServers();
432
+ })
433
+ );
434
+
435
+ // Emit MCP observability events
436
+ this._disposables.add(
437
+ this.mcp.onObservabilityEvent((event) => {
438
+ this.observability?.emit(event);
439
+ })
440
+ );
441
+
265
442
  this.sql`
266
443
  CREATE TABLE IF NOT EXISTS cf_agents_state (
267
444
  id TEXT PRIMARY KEY NOT NULL,
@@ -269,8 +446,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
269
446
  )
270
447
  `;
271
448
 
449
+ this.sql`
450
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
451
+ id TEXT PRIMARY KEY NOT NULL,
452
+ payload TEXT,
453
+ callback TEXT,
454
+ created_at INTEGER DEFAULT (unixepoch())
455
+ )
456
+ `;
457
+
272
458
  void this.ctx.blockConcurrencyWhile(async () => {
273
- return this.#tryCatch(async () => {
459
+ return this._tryCatch(async () => {
274
460
  // Create alarms table if it doesn't exist
275
461
  this.sql`
276
462
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -290,96 +476,233 @@ export class Agent<Env, State = unknown> extends Server<Env> {
290
476
  });
291
477
  });
292
478
 
293
- const _onMessage = this.onMessage.bind(this);
294
- this.onMessage = async (connection: Connection, message: WSMessage) => {
295
- if (typeof message !== "string") {
296
- return this.#tryCatch(() => _onMessage(connection, message));
297
- }
298
-
299
- let parsed: unknown;
300
- try {
301
- parsed = JSON.parse(message);
302
- } catch (e) {
303
- // silently fail and let the onMessage handler handle it
304
- return this.#tryCatch(() => _onMessage(connection, message));
305
- }
479
+ this.sql`
480
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
481
+ id TEXT PRIMARY KEY NOT NULL,
482
+ name TEXT NOT NULL,
483
+ server_url TEXT NOT NULL,
484
+ callback_url TEXT NOT NULL,
485
+ client_id TEXT,
486
+ auth_url TEXT,
487
+ server_options TEXT
488
+ )
489
+ `;
306
490
 
307
- if (isStateUpdateMessage(parsed)) {
308
- this.#setStateInternal(parsed.state as State, connection);
309
- return;
310
- }
491
+ const _onRequest = this.onRequest.bind(this);
492
+ this.onRequest = (request: Request) => {
493
+ return agentContext.run(
494
+ { agent: this, connection: undefined, request, email: undefined },
495
+ async () => {
496
+ // Check if this is an OAuth callback and restore state if needed
497
+ const callbackResult =
498
+ await this._handlePotentialOAuthCallback(request);
499
+ if (callbackResult) {
500
+ return callbackResult;
501
+ }
311
502
 
312
- if (isRPCRequest(parsed)) {
313
- try {
314
- const { id, method, args } = parsed;
503
+ return this._tryCatch(() => _onRequest(request));
504
+ }
505
+ );
506
+ };
315
507
 
316
- // Check if method exists and is callable
317
- const methodFn = this[method as keyof this];
318
- if (typeof methodFn !== "function") {
319
- throw new Error(`Method ${method} does not exist`);
508
+ const _onMessage = this.onMessage.bind(this);
509
+ this.onMessage = async (connection: Connection, message: WSMessage) => {
510
+ return agentContext.run(
511
+ { agent: this, connection, request: undefined, email: undefined },
512
+ async () => {
513
+ if (typeof message !== "string") {
514
+ return this._tryCatch(() => _onMessage(connection, message));
320
515
  }
321
516
 
322
- if (!this.#isCallable(method)) {
323
- throw new Error(`Method ${method} is not callable`);
517
+ let parsed: unknown;
518
+ try {
519
+ parsed = JSON.parse(message);
520
+ } catch (_e) {
521
+ // silently fail and let the onMessage handler handle it
522
+ return this._tryCatch(() => _onMessage(connection, message));
324
523
  }
325
524
 
326
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
327
- const metadata = callableMetadata.get(methodFn as Function);
525
+ if (isStateUpdateMessage(parsed)) {
526
+ this._setStateInternal(parsed.state as State, connection);
527
+ return;
528
+ }
328
529
 
329
- // For streaming methods, pass a StreamingResponse object
330
- if (metadata?.streaming) {
331
- const stream = new StreamingResponse(connection, id);
332
- await methodFn.apply(this, [stream, ...args]);
530
+ if (isRPCRequest(parsed)) {
531
+ try {
532
+ const { id, method, args } = parsed;
533
+
534
+ // Check if method exists and is callable
535
+ const methodFn = this[method as keyof this];
536
+ if (typeof methodFn !== "function") {
537
+ throw new Error(`Method ${method} does not exist`);
538
+ }
539
+
540
+ if (!this._isCallable(method)) {
541
+ throw new Error(`Method ${method} is not callable`);
542
+ }
543
+
544
+ const metadata = callableMetadata.get(methodFn as Function);
545
+
546
+ // For streaming methods, pass a StreamingResponse object
547
+ if (metadata?.streaming) {
548
+ const stream = new StreamingResponse(connection, id);
549
+ await methodFn.apply(this, [stream, ...args]);
550
+ return;
551
+ }
552
+
553
+ // For regular methods, execute and send response
554
+ const result = await methodFn.apply(this, args);
555
+
556
+ this.observability?.emit(
557
+ {
558
+ displayMessage: `RPC call to ${method}`,
559
+ id: nanoid(),
560
+ payload: {
561
+ method,
562
+ streaming: metadata?.streaming
563
+ },
564
+ timestamp: Date.now(),
565
+ type: "rpc"
566
+ },
567
+ this.ctx
568
+ );
569
+
570
+ const response: RPCResponse = {
571
+ done: true,
572
+ id,
573
+ result,
574
+ success: true,
575
+ type: MessageType.RPC
576
+ };
577
+ connection.send(JSON.stringify(response));
578
+ } catch (e) {
579
+ // Send error response
580
+ const response: RPCResponse = {
581
+ error:
582
+ e instanceof Error ? e.message : "Unknown error occurred",
583
+ id: parsed.id,
584
+ success: false,
585
+ type: MessageType.RPC
586
+ };
587
+ connection.send(JSON.stringify(response));
588
+ console.error("RPC error:", e);
589
+ }
333
590
  return;
334
591
  }
335
592
 
336
- // For regular methods, execute and send response
337
- const result = await methodFn.apply(this, args);
338
- const response: RPCResponse = {
339
- type: "rpc",
340
- id,
341
- success: true,
342
- result,
343
- done: true,
344
- };
345
- connection.send(JSON.stringify(response));
346
- } catch (e) {
347
- // Send error response
348
- const response: RPCResponse = {
349
- type: "rpc",
350
- id: parsed.id,
351
- success: false,
352
- error: e instanceof Error ? e.message : "Unknown error occurred",
353
- };
354
- connection.send(JSON.stringify(response));
355
- console.error("RPC error:", e);
593
+ return this._tryCatch(() => _onMessage(connection, message));
356
594
  }
357
- return;
358
- }
359
-
360
- return this.#tryCatch(() => _onMessage(connection, message));
595
+ );
361
596
  };
362
597
 
363
598
  const _onConnect = this.onConnect.bind(this);
364
599
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
365
600
  // TODO: This is a hack to ensure the state is sent after the connection is established
366
601
  // must fix this
367
- setTimeout(() => {
368
- if (this.state) {
602
+ return agentContext.run(
603
+ { agent: this, connection, request: ctx.request, email: undefined },
604
+ () => {
605
+ if (this.state) {
606
+ connection.send(
607
+ JSON.stringify({
608
+ state: this.state,
609
+ type: MessageType.CF_AGENT_STATE
610
+ })
611
+ );
612
+ }
613
+
369
614
  connection.send(
370
615
  JSON.stringify({
371
- type: "cf_agent_state",
372
- state: this.state,
616
+ mcp: this.getMcpServers(),
617
+ type: MessageType.CF_AGENT_MCP_SERVERS
373
618
  })
374
619
  );
620
+
621
+ this.observability?.emit(
622
+ {
623
+ displayMessage: "Connection established",
624
+ id: nanoid(),
625
+ payload: {
626
+ connectionId: connection.id
627
+ },
628
+ timestamp: Date.now(),
629
+ type: "connect"
630
+ },
631
+ this.ctx
632
+ );
633
+ return this._tryCatch(() => _onConnect(connection, ctx));
375
634
  }
376
- return this.#tryCatch(() => _onConnect(connection, ctx));
377
- }, 20);
635
+ );
636
+ };
637
+
638
+ const _onStart = this.onStart.bind(this);
639
+ this.onStart = async (props?: Props) => {
640
+ return agentContext.run(
641
+ {
642
+ agent: this,
643
+ connection: undefined,
644
+ request: undefined,
645
+ email: undefined
646
+ },
647
+ async () => {
648
+ await this._tryCatch(() => {
649
+ const servers = this.sql<MCPServerRow>`
650
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
651
+ `;
652
+
653
+ this.broadcastMcpServers();
654
+
655
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
656
+ if (servers && Array.isArray(servers) && servers.length > 0) {
657
+ // Restore callback URLs for OAuth-enabled servers
658
+ servers.forEach((server) => {
659
+ if (server.callback_url) {
660
+ // Register the full redirect URL including serverId to avoid ambiguous matches
661
+ this.mcp.registerCallbackUrl(
662
+ `${server.callback_url}/${server.id}`
663
+ );
664
+ }
665
+ });
666
+
667
+ servers.forEach((server) => {
668
+ this._connectToMcpServerInternal(
669
+ server.name,
670
+ server.server_url,
671
+ server.callback_url,
672
+ server.server_options
673
+ ? JSON.parse(server.server_options)
674
+ : undefined,
675
+ {
676
+ id: server.id,
677
+ oauthClientId: server.client_id ?? undefined
678
+ }
679
+ )
680
+ .then(() => {
681
+ // Broadcast updated MCP servers state after each server connects
682
+ this.broadcastMcpServers();
683
+ })
684
+ .catch((error) => {
685
+ console.error(
686
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
687
+ error
688
+ );
689
+ // Still broadcast even if connection fails, so clients know about the failure
690
+ this.broadcastMcpServers();
691
+ });
692
+ });
693
+ }
694
+ return _onStart(props);
695
+ });
696
+ }
697
+ );
378
698
  };
379
699
  }
380
700
 
381
- #setStateInternal(state: State, source: Connection | "server" = "server") {
382
- this.#state = state;
701
+ private _setStateInternal(
702
+ state: State,
703
+ source: Connection | "server" = "server"
704
+ ) {
705
+ this._state = state;
383
706
  this.sql`
384
707
  INSERT OR REPLACE INTO cf_agents_state (id, state)
385
708
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -390,12 +713,30 @@ export class Agent<Env, State = unknown> extends Server<Env> {
390
713
  `;
391
714
  this.broadcast(
392
715
  JSON.stringify({
393
- type: "cf_agent_state",
394
716
  state: state,
717
+ type: MessageType.CF_AGENT_STATE
395
718
  }),
396
719
  source !== "server" ? [source.id] : []
397
720
  );
398
- return this.#tryCatch(() => this.onStateUpdate(state, source));
721
+ return this._tryCatch(() => {
722
+ const { connection, request, email } = agentContext.getStore() || {};
723
+ return agentContext.run(
724
+ { agent: this, connection, request, email },
725
+ async () => {
726
+ this.observability?.emit(
727
+ {
728
+ displayMessage: "State updated",
729
+ id: nanoid(),
730
+ payload: {},
731
+ timestamp: Date.now(),
732
+ type: "state:update"
733
+ },
734
+ this.ctx
735
+ );
736
+ return this.onStateUpdate(state, source);
737
+ }
738
+ );
739
+ });
399
740
  }
400
741
 
401
742
  /**
@@ -403,7 +744,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
403
744
  * @param state New state to set
404
745
  */
405
746
  setState(state: State) {
406
- this.#setStateInternal(state, "server");
747
+ this._setStateInternal(state, "server");
407
748
  }
408
749
 
409
750
  /**
@@ -411,19 +752,90 @@ export class Agent<Env, State = unknown> extends Server<Env> {
411
752
  * @param state Updated state
412
753
  * @param source Source of the state update ("server" or a client connection)
413
754
  */
755
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
414
756
  onStateUpdate(state: State | undefined, source: Connection | "server") {
415
757
  // override this to handle state updates
416
758
  }
417
759
 
418
760
  /**
419
- * Called when the Agent receives an email
761
+ * Called when the Agent receives an email via routeAgentEmail()
762
+ * Override this method to handle incoming emails
420
763
  * @param email Email message to process
421
764
  */
422
- onEmail(email: ForwardableEmailMessage) {
423
- throw new Error("Not implemented");
765
+ async _onEmail(email: AgentEmail) {
766
+ // nb: we use this roundabout way of getting to onEmail
767
+ // because of https://github.com/cloudflare/workerd/issues/4499
768
+ return agentContext.run(
769
+ { agent: this, connection: undefined, request: undefined, email: email },
770
+ async () => {
771
+ if ("onEmail" in this && typeof this.onEmail === "function") {
772
+ return this._tryCatch(() =>
773
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
774
+ );
775
+ } else {
776
+ console.log("Received email from:", email.from, "to:", email.to);
777
+ console.log("Subject:", email.headers.get("subject"));
778
+ console.log(
779
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
780
+ );
781
+ }
782
+ }
783
+ );
784
+ }
785
+
786
+ /**
787
+ * Reply to an email
788
+ * @param email The email to reply to
789
+ * @param options Options for the reply
790
+ * @returns void
791
+ */
792
+ async replyToEmail(
793
+ email: AgentEmail,
794
+ options: {
795
+ fromName: string;
796
+ subject?: string | undefined;
797
+ body: string;
798
+ contentType?: string;
799
+ headers?: Record<string, string>;
800
+ }
801
+ ): Promise<void> {
802
+ return this._tryCatch(async () => {
803
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
804
+ const agentId = this.name;
805
+
806
+ const { createMimeMessage } = await import("mimetext");
807
+ const msg = createMimeMessage();
808
+ msg.setSender({ addr: email.to, name: options.fromName });
809
+ msg.setRecipient(email.from);
810
+ msg.setSubject(
811
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
812
+ );
813
+ msg.addMessage({
814
+ contentType: options.contentType || "text/plain",
815
+ data: options.body
816
+ });
817
+
818
+ const domain = email.from.split("@")[1];
819
+ const messageId = `<${agentId}@${domain}>`;
820
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
821
+ msg.setHeader("Message-ID", messageId);
822
+ msg.setHeader("X-Agent-Name", agentName);
823
+ msg.setHeader("X-Agent-ID", agentId);
824
+
825
+ if (options.headers) {
826
+ for (const [key, value] of Object.entries(options.headers)) {
827
+ msg.setHeader(key, value);
828
+ }
829
+ }
830
+ await email.reply({
831
+ from: email.to,
832
+ raw: msg.asRaw(),
833
+ to: email.from
834
+ });
835
+ });
424
836
  }
425
837
 
426
- async #tryCatch<T>(fn: () => T | Promise<T>) {
838
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
427
839
  try {
428
840
  return await fn();
429
841
  } catch (e) {
@@ -431,6 +843,68 @@ export class Agent<Env, State = unknown> extends Server<Env> {
431
843
  }
432
844
  }
433
845
 
846
+ /**
847
+ * Automatically wrap custom methods with agent context
848
+ * This ensures getCurrentAgent() works in all custom methods without decorators
849
+ */
850
+ private _autoWrapCustomMethods() {
851
+ // Collect all methods from base prototypes (Agent and Server)
852
+ const basePrototypes = [Agent.prototype, Server.prototype];
853
+ const baseMethods = new Set<string>();
854
+ for (const baseProto of basePrototypes) {
855
+ let proto = baseProto;
856
+ while (proto && proto !== Object.prototype) {
857
+ const methodNames = Object.getOwnPropertyNames(proto);
858
+ for (const methodName of methodNames) {
859
+ baseMethods.add(methodName);
860
+ }
861
+ proto = Object.getPrototypeOf(proto);
862
+ }
863
+ }
864
+ // Get all methods from the current instance's prototype chain
865
+ let proto = Object.getPrototypeOf(this);
866
+ let depth = 0;
867
+ while (proto && proto !== Object.prototype && depth < 10) {
868
+ const methodNames = Object.getOwnPropertyNames(proto);
869
+ for (const methodName of methodNames) {
870
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
871
+
872
+ // Skip if it's a private method, a base method, a getter, or not a function,
873
+ if (
874
+ baseMethods.has(methodName) ||
875
+ methodName.startsWith("_") ||
876
+ !descriptor ||
877
+ !!descriptor.get ||
878
+ typeof descriptor.value !== "function"
879
+ ) {
880
+ continue;
881
+ }
882
+
883
+ // Now, methodName is confirmed to be a custom method/function
884
+ // Wrap the custom method with context
885
+ const wrappedFunction = withAgentContext(
886
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
887
+ this[methodName as keyof this] as (...args: any[]) => any
888
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
889
+ ) as any;
890
+
891
+ // if the method is callable, copy the metadata from the original method
892
+ if (this._isCallable(methodName)) {
893
+ callableMetadata.set(
894
+ wrappedFunction,
895
+ callableMetadata.get(this[methodName as keyof this] as Function)!
896
+ );
897
+ }
898
+
899
+ // set the wrapped function on the prototype
900
+ this.constructor.prototype[methodName as keyof this] = wrappedFunction;
901
+ }
902
+
903
+ proto = Object.getPrototypeOf(proto);
904
+ depth++;
905
+ }
906
+ }
907
+
434
908
  override onError(
435
909
  connection: Connection,
436
910
  error: unknown
@@ -465,6 +939,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
465
939
  throw new Error("Not implemented");
466
940
  }
467
941
 
942
+ /**
943
+ * Queue a task to be executed in the future
944
+ * @param payload Payload to pass to the callback
945
+ * @param callback Name of the method to call
946
+ * @returns The ID of the queued task
947
+ */
948
+ async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
949
+ const id = nanoid(9);
950
+ if (typeof callback !== "string") {
951
+ throw new Error("Callback must be a string");
952
+ }
953
+
954
+ if (typeof this[callback] !== "function") {
955
+ throw new Error(`this.${callback} is not a function`);
956
+ }
957
+
958
+ this.sql`
959
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
960
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
961
+ `;
962
+
963
+ void this._flushQueue().catch((e) => {
964
+ console.error("Error flushing queue:", e);
965
+ });
966
+
967
+ return id;
968
+ }
969
+
970
+ private _flushingQueue = false;
971
+
972
+ private async _flushQueue() {
973
+ if (this._flushingQueue) {
974
+ return;
975
+ }
976
+ this._flushingQueue = true;
977
+ while (true) {
978
+ const result = this.sql<QueueItem<string>>`
979
+ SELECT * FROM cf_agents_queues
980
+ ORDER BY created_at ASC
981
+ `;
982
+
983
+ if (!result || result.length === 0) {
984
+ break;
985
+ }
986
+
987
+ for (const row of result || []) {
988
+ const callback = this[row.callback as keyof Agent<Env>];
989
+ if (!callback) {
990
+ console.error(`callback ${row.callback} not found`);
991
+ continue;
992
+ }
993
+ const { connection, request, email } = agentContext.getStore() || {};
994
+ await agentContext.run(
995
+ {
996
+ agent: this,
997
+ connection,
998
+ request,
999
+ email
1000
+ },
1001
+ async () => {
1002
+ // TODO: add retries and backoff
1003
+ await (
1004
+ callback as (
1005
+ payload: unknown,
1006
+ queueItem: QueueItem<string>
1007
+ ) => Promise<void>
1008
+ ).bind(this)(JSON.parse(row.payload as string), row);
1009
+ await this.dequeue(row.id);
1010
+ }
1011
+ );
1012
+ }
1013
+ }
1014
+ this._flushingQueue = false;
1015
+ }
1016
+
1017
+ /**
1018
+ * Dequeue a task by ID
1019
+ * @param id ID of the task to dequeue
1020
+ */
1021
+ async dequeue(id: string) {
1022
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1023
+ }
1024
+
1025
+ /**
1026
+ * Dequeue all tasks
1027
+ */
1028
+ async dequeueAll() {
1029
+ this.sql`DELETE FROM cf_agents_queues`;
1030
+ }
1031
+
1032
+ /**
1033
+ * Dequeue all tasks by callback
1034
+ * @param callback Name of the callback to dequeue
1035
+ */
1036
+ async dequeueAllByCallback(callback: string) {
1037
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1038
+ }
1039
+
1040
+ /**
1041
+ * Get a queued task by ID
1042
+ * @param id ID of the task to get
1043
+ * @returns The task or undefined if not found
1044
+ */
1045
+ async getQueue(id: string): Promise<QueueItem<string> | undefined> {
1046
+ const result = this.sql<QueueItem<string>>`
1047
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1048
+ `;
1049
+ return result
1050
+ ? { ...result[0], payload: JSON.parse(result[0].payload) }
1051
+ : undefined;
1052
+ }
1053
+
1054
+ /**
1055
+ * Get all queues by key and value
1056
+ * @param key Key to filter by
1057
+ * @param value Value to filter by
1058
+ * @returns Array of matching QueueItem objects
1059
+ */
1060
+ async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1061
+ const result = this.sql<QueueItem<string>>`
1062
+ SELECT * FROM cf_agents_queues
1063
+ `;
1064
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
1065
+ }
1066
+
468
1067
  /**
469
1068
  * Schedule a task to be executed in the future
470
1069
  * @template T Type of the payload data
@@ -480,6 +1079,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
480
1079
  ): Promise<Schedule<T>> {
481
1080
  const id = nanoid(9);
482
1081
 
1082
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
1083
+ this.observability?.emit(
1084
+ {
1085
+ displayMessage: `Schedule ${schedule.id} created`,
1086
+ id: nanoid(),
1087
+ payload: {
1088
+ callback: callback as string,
1089
+ id: id
1090
+ },
1091
+ timestamp: Date.now(),
1092
+ type: "schedule:create"
1093
+ },
1094
+ this.ctx
1095
+ );
1096
+
483
1097
  if (typeof callback !== "string") {
484
1098
  throw new Error("Callback must be a string");
485
1099
  }
@@ -497,15 +1111,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
497
1111
  )}, 'scheduled', ${timestamp})
498
1112
  `;
499
1113
 
500
- await this.#scheduleNextAlarm();
1114
+ await this._scheduleNextAlarm();
501
1115
 
502
- return {
503
- id,
1116
+ const schedule: Schedule<T> = {
504
1117
  callback: callback,
1118
+ id,
505
1119
  payload: payload as T,
506
1120
  time: timestamp,
507
- type: "scheduled",
1121
+ type: "scheduled"
508
1122
  };
1123
+
1124
+ emitScheduleCreate(schedule);
1125
+
1126
+ return schedule;
509
1127
  }
510
1128
  if (typeof when === "number") {
511
1129
  const time = new Date(Date.now() + when * 1000);
@@ -518,16 +1136,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
518
1136
  )}, 'delayed', ${when}, ${timestamp})
519
1137
  `;
520
1138
 
521
- await this.#scheduleNextAlarm();
1139
+ await this._scheduleNextAlarm();
522
1140
 
523
- return {
524
- id,
1141
+ const schedule: Schedule<T> = {
525
1142
  callback: callback,
526
- payload: payload as T,
527
1143
  delayInSeconds: when,
1144
+ id,
1145
+ payload: payload as T,
528
1146
  time: timestamp,
529
- type: "delayed",
1147
+ type: "delayed"
530
1148
  };
1149
+
1150
+ emitScheduleCreate(schedule);
1151
+
1152
+ return schedule;
531
1153
  }
532
1154
  if (typeof when === "string") {
533
1155
  const nextExecutionTime = getNextCronTime(when);
@@ -540,16 +1162,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
540
1162
  )}, 'cron', ${when}, ${timestamp})
541
1163
  `;
542
1164
 
543
- await this.#scheduleNextAlarm();
1165
+ await this._scheduleNextAlarm();
544
1166
 
545
- return {
546
- id,
1167
+ const schedule: Schedule<T> = {
547
1168
  callback: callback,
548
- payload: payload as T,
549
1169
  cron: when,
1170
+ id,
1171
+ payload: payload as T,
550
1172
  time: timestamp,
551
- type: "cron",
1173
+ type: "cron"
552
1174
  };
1175
+
1176
+ emitScheduleCreate(schedule);
1177
+
1178
+ return schedule;
553
1179
  }
554
1180
  throw new Error("Invalid schedule type");
555
1181
  }
@@ -580,7 +1206,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
580
1206
  */
581
1207
  getSchedules<T = string>(
582
1208
  criteria: {
583
- description?: string;
584
1209
  id?: string;
585
1210
  type?: "scheduled" | "delayed" | "cron";
586
1211
  timeRange?: { start?: Date; end?: Date };
@@ -594,11 +1219,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
594
1219
  params.push(criteria.id);
595
1220
  }
596
1221
 
597
- if (criteria.description) {
598
- query += " AND description = ?";
599
- params.push(criteria.description);
600
- }
601
-
602
1222
  if (criteria.type) {
603
1223
  query += " AND type = ?";
604
1224
  params.push(criteria.type);
@@ -619,7 +1239,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
619
1239
  .toArray()
620
1240
  .map((row) => ({
621
1241
  ...row,
622
- payload: JSON.parse(row.payload as string) as T,
1242
+ payload: JSON.parse(row.payload as string) as T
623
1243
  })) as Schedule<T>[];
624
1244
 
625
1245
  return result;
@@ -631,18 +1251,34 @@ export class Agent<Env, State = unknown> extends Server<Env> {
631
1251
  * @returns true if the task was cancelled, false otherwise
632
1252
  */
633
1253
  async cancelSchedule(id: string): Promise<boolean> {
1254
+ const schedule = await this.getSchedule(id);
1255
+ if (schedule) {
1256
+ this.observability?.emit(
1257
+ {
1258
+ displayMessage: `Schedule ${id} cancelled`,
1259
+ id: nanoid(),
1260
+ payload: {
1261
+ callback: schedule.callback,
1262
+ id: schedule.id
1263
+ },
1264
+ timestamp: Date.now(),
1265
+ type: "schedule:cancel"
1266
+ },
1267
+ this.ctx
1268
+ );
1269
+ }
634
1270
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
635
1271
 
636
- await this.#scheduleNextAlarm();
1272
+ await this._scheduleNextAlarm();
637
1273
  return true;
638
1274
  }
639
1275
 
640
- async #scheduleNextAlarm() {
1276
+ private async _scheduleNextAlarm() {
641
1277
  // Find the next schedule that needs to be executed
642
1278
  const result = this.sql`
643
- SELECT time FROM cf_agents_schedules
1279
+ SELECT time FROM cf_agents_schedules
644
1280
  WHERE time > ${Math.floor(Date.now() / 1000)}
645
- ORDER BY time ASC
1281
+ ORDER BY time ASC
646
1282
  LIMIT 1
647
1283
  `;
648
1284
  if (!result) return;
@@ -654,10 +1290,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
654
1290
  }
655
1291
 
656
1292
  /**
657
- * Method called when an alarm fires
658
- * Executes any scheduled tasks that are due
1293
+ * Method called when an alarm fires.
1294
+ * Executes any scheduled tasks that are due.
1295
+ *
1296
+ * @remarks
1297
+ * To schedule a task, please use the `this.schedule` method instead.
1298
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
659
1299
  */
660
- async alarm() {
1300
+ public readonly alarm = async () => {
661
1301
  const now = Math.floor(Date.now() / 1000);
662
1302
 
663
1303
  // Get all schedules that should be executed now
@@ -665,41 +1305,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
665
1305
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
666
1306
  `;
667
1307
 
668
- for (const row of result || []) {
669
- const callback = this[row.callback as keyof Agent<Env>];
670
- if (!callback) {
671
- console.error(`callback ${row.callback} not found`);
672
- continue;
673
- }
674
- try {
675
- await (
676
- callback as (
677
- payload: unknown,
678
- schedule: Schedule<unknown>
679
- ) => Promise<void>
680
- ).bind(this)(JSON.parse(row.payload as string), row);
681
- } catch (e) {
682
- console.error(`error executing callback "${row.callback}"`, e);
683
- }
684
- if (row.type === "cron") {
685
- // Update next execution time for cron schedules
686
- const nextExecutionTime = getNextCronTime(row.cron);
687
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1308
+ if (result && Array.isArray(result)) {
1309
+ for (const row of result) {
1310
+ const callback = this[row.callback as keyof Agent<Env>];
1311
+ if (!callback) {
1312
+ console.error(`callback ${row.callback} not found`);
1313
+ continue;
1314
+ }
1315
+ await agentContext.run(
1316
+ {
1317
+ agent: this,
1318
+ connection: undefined,
1319
+ request: undefined,
1320
+ email: undefined
1321
+ },
1322
+ async () => {
1323
+ try {
1324
+ this.observability?.emit(
1325
+ {
1326
+ displayMessage: `Schedule ${row.id} executed`,
1327
+ id: nanoid(),
1328
+ payload: {
1329
+ callback: row.callback,
1330
+ id: row.id
1331
+ },
1332
+ timestamp: Date.now(),
1333
+ type: "schedule:execute"
1334
+ },
1335
+ this.ctx
1336
+ );
1337
+
1338
+ await (
1339
+ callback as (
1340
+ payload: unknown,
1341
+ schedule: Schedule<unknown>
1342
+ ) => Promise<void>
1343
+ ).bind(this)(JSON.parse(row.payload as string), row);
1344
+ } catch (e) {
1345
+ console.error(`error executing callback "${row.callback}"`, e);
1346
+ }
1347
+ }
1348
+ );
1349
+ if (row.type === "cron") {
1350
+ // Update next execution time for cron schedules
1351
+ const nextExecutionTime = getNextCronTime(row.cron);
1352
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
688
1353
 
689
- this.sql`
1354
+ this.sql`
690
1355
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
691
1356
  `;
692
- } else {
693
- // Delete one-time schedules after execution
694
- this.sql`
1357
+ } else {
1358
+ // Delete one-time schedules after execution
1359
+ this.sql`
695
1360
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
696
1361
  `;
1362
+ }
697
1363
  }
698
1364
  }
699
1365
 
700
1366
  // Schedule the next alarm
701
- await this.#scheduleNextAlarm();
702
- }
1367
+ await this._scheduleNextAlarm();
1368
+ };
703
1369
 
704
1370
  /**
705
1371
  * Destroy the Agent, removing all state and scheduled tasks
@@ -708,22 +1374,416 @@ export class Agent<Env, State = unknown> extends Server<Env> {
708
1374
  // drop all tables
709
1375
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
710
1376
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1377
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1378
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
711
1379
 
712
1380
  // delete all alarms
713
1381
  await this.ctx.storage.deleteAlarm();
714
1382
  await this.ctx.storage.deleteAll();
1383
+ this._disposables.dispose();
1384
+ await this.mcp.dispose?.();
1385
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
1386
+
1387
+ this.observability?.emit(
1388
+ {
1389
+ displayMessage: "Agent destroyed",
1390
+ id: nanoid(),
1391
+ payload: {},
1392
+ timestamp: Date.now(),
1393
+ type: "destroy"
1394
+ },
1395
+ this.ctx
1396
+ );
715
1397
  }
716
1398
 
717
1399
  /**
718
1400
  * Get all methods marked as callable on this Agent
719
1401
  * @returns A map of method names to their metadata
720
1402
  */
721
- #isCallable(method: string): boolean {
722
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
1403
+ private _isCallable(method: string): boolean {
723
1404
  return callableMetadata.has(this[method as keyof this] as Function);
724
1405
  }
1406
+
1407
+ /**
1408
+ * Connect to a new MCP Server
1409
+ *
1410
+ * @param serverName Name of the MCP server
1411
+ * @param url MCP Server SSE URL
1412
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
1413
+ * @param agentsPrefix agents routing prefix if not using `agents`
1414
+ * @param options MCP client and transport options
1415
+ * @returns authUrl
1416
+ */
1417
+ async addMcpServer(
1418
+ serverName: string,
1419
+ url: string,
1420
+ callbackHost?: string,
1421
+ agentsPrefix = "agents",
1422
+ options?: {
1423
+ client?: ConstructorParameters<typeof Client>[1];
1424
+ transport?: {
1425
+ headers?: HeadersInit;
1426
+ type?: TransportType;
1427
+ };
1428
+ }
1429
+ ): Promise<{ id: string; authUrl: string | undefined }> {
1430
+ // If callbackHost is not provided, derive it from the current request
1431
+ let resolvedCallbackHost = callbackHost;
1432
+ if (!resolvedCallbackHost) {
1433
+ const { request } = getCurrentAgent();
1434
+ if (!request) {
1435
+ throw new Error(
1436
+ "callbackHost is required when not called within a request context"
1437
+ );
1438
+ }
1439
+
1440
+ // Extract the origin from the request
1441
+ const requestUrl = new URL(request.url);
1442
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1443
+ }
1444
+
1445
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1446
+
1447
+ // Generate a serverId upfront
1448
+ const serverId = nanoid(8);
1449
+
1450
+ // Persist to database BEFORE starting OAuth flow to survive DO hibernation
1451
+ this.sql`
1452
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1453
+ VALUES (
1454
+ ${serverId},
1455
+ ${serverName},
1456
+ ${url},
1457
+ ${null},
1458
+ ${null},
1459
+ ${callbackUrl},
1460
+ ${options ? JSON.stringify(options) : null}
1461
+ );
1462
+ `;
1463
+
1464
+ // _connectToMcpServerInternal will call mcp.connect which registers the callback URL
1465
+ const result = await this._connectToMcpServerInternal(
1466
+ serverName,
1467
+ url,
1468
+ callbackUrl,
1469
+ options,
1470
+ { id: serverId }
1471
+ );
1472
+
1473
+ // Update database with OAuth client info if auth is required
1474
+ if (result.clientId || result.authUrl) {
1475
+ this.sql`
1476
+ UPDATE cf_agents_mcp_servers
1477
+ SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
1478
+ WHERE id = ${serverId}
1479
+ `;
1480
+ }
1481
+
1482
+ this.broadcastMcpServers();
1483
+
1484
+ return result;
1485
+ }
1486
+
1487
+ /**
1488
+ * Handle potential OAuth callback requests after DO hibernation.
1489
+ * Detects OAuth callbacks, restores state from database, and processes the callback.
1490
+ * Returns a Response if this was an OAuth callback, otherwise returns undefined.
1491
+ */
1492
+ private async _handlePotentialOAuthCallback(
1493
+ request: Request
1494
+ ): Promise<Response | undefined> {
1495
+ // Quick check: must be GET with callback pattern and code parameter
1496
+ if (request.method !== "GET") {
1497
+ return undefined;
1498
+ }
1499
+
1500
+ const url = new URL(request.url);
1501
+ const hasCallbackPattern =
1502
+ url.pathname.includes("/callback/") && url.searchParams.has("code");
1503
+
1504
+ if (!hasCallbackPattern) {
1505
+ return undefined;
1506
+ }
1507
+
1508
+ // Extract serverId from callback URL
1509
+ const pathParts = url.pathname.split("/");
1510
+ const callbackIndex = pathParts.indexOf("callback");
1511
+ const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
1512
+
1513
+ if (!serverId) {
1514
+ return new Response("Invalid callback URL: missing serverId", {
1515
+ status: 400
1516
+ });
1517
+ }
1518
+
1519
+ // Check if callback is already registered AND connection exists (not hibernated)
1520
+ if (
1521
+ this.mcp.isCallbackRequest(request) &&
1522
+ this.mcp.mcpConnections[serverId]
1523
+ ) {
1524
+ // State already restored, handle normally
1525
+ return this._processOAuthCallback(request);
1526
+ }
1527
+
1528
+ // Need to restore from database after hibernation
1529
+ try {
1530
+ const server = this.sql<MCPServerRow>`
1531
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
1532
+ FROM cf_agents_mcp_servers
1533
+ WHERE id = ${serverId}
1534
+ `.find((s) => s.id === serverId);
1535
+
1536
+ if (!server) {
1537
+ return new Response(
1538
+ `OAuth callback failed: Server ${serverId} not found in database`,
1539
+ { status: 404 }
1540
+ );
1541
+ }
1542
+
1543
+ // Register callback URL (restores it after hibernation)
1544
+ if (!server.callback_url) {
1545
+ return new Response(
1546
+ `OAuth callback failed: No callback URL stored for server ${serverId}`,
1547
+ { status: 500 }
1548
+ );
1549
+ }
1550
+
1551
+ this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
1552
+
1553
+ // Restore connection if not in memory
1554
+ if (!this.mcp.mcpConnections[serverId]) {
1555
+ let parsedOptions:
1556
+ | {
1557
+ client?: ConstructorParameters<typeof Client>[1];
1558
+ transport?: {
1559
+ headers?: HeadersInit;
1560
+ type?: TransportType;
1561
+ };
1562
+ }
1563
+ | undefined;
1564
+ try {
1565
+ parsedOptions = server.server_options
1566
+ ? JSON.parse(server.server_options)
1567
+ : undefined;
1568
+ } catch {
1569
+ return new Response(
1570
+ `OAuth callback failed: Invalid server options in database for ${serverId}`,
1571
+ { status: 500 }
1572
+ );
1573
+ }
1574
+
1575
+ await this._connectToMcpServerInternal(
1576
+ server.name,
1577
+ server.server_url,
1578
+ server.callback_url,
1579
+ parsedOptions,
1580
+ {
1581
+ id: server.id,
1582
+ oauthClientId: server.client_id ?? undefined
1583
+ }
1584
+ );
1585
+ }
1586
+
1587
+ // Now process the OAuth callback
1588
+ return this._processOAuthCallback(request);
1589
+ } catch (error) {
1590
+ const errorMsg = error instanceof Error ? error.message : "Unknown error";
1591
+ console.error(`Failed to restore MCP state for ${serverId}:`, error);
1592
+ return new Response(
1593
+ `OAuth callback failed during state restoration: ${errorMsg}`,
1594
+ { status: 500 }
1595
+ );
1596
+ }
1597
+ }
1598
+
1599
+ /**
1600
+ * Process an OAuth callback request (assumes state is already restored)
1601
+ */
1602
+ private async _processOAuthCallback(request: Request): Promise<Response> {
1603
+ const result = await this.mcp.handleCallbackRequest(request);
1604
+ this.broadcastMcpServers();
1605
+
1606
+ if (result.authSuccess) {
1607
+ // Start background connection if auth was successful
1608
+ this.mcp
1609
+ .establishConnection(result.serverId)
1610
+ .catch((error) => {
1611
+ console.error("Background connection failed:", error);
1612
+ })
1613
+ .finally(() => {
1614
+ // Broadcast after background connection resolves (success/failure)
1615
+ this.broadcastMcpServers();
1616
+ });
1617
+ }
1618
+
1619
+ // Handle OAuth callback response using MCPClientManager configuration
1620
+ return this.handleOAuthCallbackResponse(result, request);
1621
+ }
1622
+
1623
+ private async _connectToMcpServerInternal(
1624
+ _serverName: string,
1625
+ url: string,
1626
+ callbackUrl: string,
1627
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
1628
+ options?: {
1629
+ client?: ConstructorParameters<typeof Client>[1];
1630
+ /**
1631
+ * We don't expose the normal set of transport options because:
1632
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
1633
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
1634
+ *
1635
+ * 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).
1636
+ */
1637
+ transport?: {
1638
+ headers?: HeadersInit;
1639
+ type?: TransportType;
1640
+ };
1641
+ },
1642
+ reconnect?: {
1643
+ id: string;
1644
+ oauthClientId?: string;
1645
+ }
1646
+ ): Promise<{
1647
+ id: string;
1648
+ authUrl: string | undefined;
1649
+ clientId: string | undefined;
1650
+ }> {
1651
+ const authProvider = new DurableObjectOAuthClientProvider(
1652
+ this.ctx.storage,
1653
+ this.name,
1654
+ callbackUrl
1655
+ );
1656
+
1657
+ if (reconnect) {
1658
+ authProvider.serverId = reconnect.id;
1659
+ if (reconnect.oauthClientId) {
1660
+ authProvider.clientId = reconnect.oauthClientId;
1661
+ }
1662
+ }
1663
+
1664
+ // Use the transport type specified in options, or default to "auto"
1665
+ const transportType: TransportType = options?.transport?.type ?? "auto";
1666
+
1667
+ // allows passing through transport headers if necessary
1668
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1669
+ let headerTransportOpts: SSEClientTransportOptions = {};
1670
+ if (options?.transport?.headers) {
1671
+ headerTransportOpts = {
1672
+ eventSourceInit: {
1673
+ fetch: (url, init) =>
1674
+ fetch(url, {
1675
+ ...init,
1676
+ headers: options?.transport?.headers
1677
+ })
1678
+ },
1679
+ requestInit: {
1680
+ headers: options?.transport?.headers
1681
+ }
1682
+ };
1683
+ }
1684
+
1685
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1686
+ client: options?.client,
1687
+ reconnect,
1688
+ transport: {
1689
+ ...headerTransportOpts,
1690
+ authProvider,
1691
+ type: transportType
1692
+ }
1693
+ });
1694
+
1695
+ return {
1696
+ authUrl,
1697
+ clientId,
1698
+ id
1699
+ };
1700
+ }
1701
+
1702
+ async removeMcpServer(id: string) {
1703
+ this.mcp.closeConnection(id);
1704
+ this.mcp.unregisterCallbackUrl(id);
1705
+ this.sql`
1706
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1707
+ `;
1708
+ this.broadcastMcpServers();
1709
+ }
1710
+
1711
+ getMcpServers(): MCPServersState {
1712
+ const mcpState: MCPServersState = {
1713
+ prompts: this.mcp.listPrompts(),
1714
+ resources: this.mcp.listResources(),
1715
+ servers: {},
1716
+ tools: this.mcp.listTools()
1717
+ };
1718
+
1719
+ const servers = this.sql<MCPServerRow>`
1720
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1721
+ `;
1722
+
1723
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1724
+ for (const server of servers) {
1725
+ const serverConn = this.mcp.mcpConnections[server.id];
1726
+ mcpState.servers[server.id] = {
1727
+ auth_url: server.auth_url,
1728
+ capabilities: serverConn?.serverCapabilities ?? null,
1729
+ instructions: serverConn?.instructions ?? null,
1730
+ name: server.name,
1731
+ server_url: server.server_url,
1732
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1733
+ state: serverConn?.connectionState ?? "authenticating"
1734
+ };
1735
+ }
1736
+ }
1737
+
1738
+ return mcpState;
1739
+ }
1740
+
1741
+ private broadcastMcpServers() {
1742
+ this.broadcast(
1743
+ JSON.stringify({
1744
+ mcp: this.getMcpServers(),
1745
+ type: MessageType.CF_AGENT_MCP_SERVERS
1746
+ })
1747
+ );
1748
+ }
1749
+
1750
+ /**
1751
+ * Handle OAuth callback response using MCPClientManager configuration
1752
+ * @param result OAuth callback result
1753
+ * @param request The original request (needed for base URL)
1754
+ * @returns Response for the OAuth callback
1755
+ */
1756
+ private handleOAuthCallbackResponse(
1757
+ result: MCPClientOAuthResult,
1758
+ request: Request
1759
+ ): Response {
1760
+ const config = this.mcp.getOAuthCallbackConfig();
1761
+
1762
+ // Use custom handler if configured
1763
+ if (config?.customHandler) {
1764
+ return config.customHandler(result);
1765
+ }
1766
+
1767
+ // Use redirect URLs if configured
1768
+ if (config?.successRedirect && result.authSuccess) {
1769
+ return Response.redirect(config.successRedirect);
1770
+ }
1771
+
1772
+ if (config?.errorRedirect && !result.authSuccess) {
1773
+ return Response.redirect(
1774
+ `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`
1775
+ );
1776
+ }
1777
+
1778
+ // Default behavior - redirect to base URL
1779
+ const baseUrl = new URL(request.url).origin;
1780
+ return Response.redirect(baseUrl);
1781
+ }
725
1782
  }
726
1783
 
1784
+ // A set of classes that have been wrapped with agent context
1785
+ const wrappedClasses = new Set<typeof Agent.prototype.constructor>();
1786
+
727
1787
  /**
728
1788
  * Namespace for creating Agent instances
729
1789
  * @template Agentic Type of the Agent class
@@ -761,17 +1821,17 @@ export async function routeAgentRequest<Env>(
761
1821
  const corsHeaders =
762
1822
  options?.cors === true
763
1823
  ? {
764
- "Access-Control-Allow-Origin": "*",
765
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
766
1824
  "Access-Control-Allow-Credentials": "true",
767
- "Access-Control-Max-Age": "86400",
1825
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1826
+ "Access-Control-Allow-Origin": "*",
1827
+ "Access-Control-Max-Age": "86400"
768
1828
  }
769
1829
  : options?.cors;
770
1830
 
771
1831
  if (request.method === "OPTIONS") {
772
1832
  if (corsHeaders) {
773
1833
  return new Response(null, {
774
- headers: corsHeaders,
1834
+ headers: corsHeaders
775
1835
  });
776
1836
  }
777
1837
  console.warn(
@@ -784,7 +1844,7 @@ export async function routeAgentRequest<Env>(
784
1844
  env as Record<string, unknown>,
785
1845
  {
786
1846
  prefix: "agents",
787
- ...(options as PartyServerOptions<Record<string, unknown>>),
1847
+ ...(options as PartyServerOptions<Record<string, unknown>>)
788
1848
  }
789
1849
  );
790
1850
 
@@ -797,24 +1857,238 @@ export async function routeAgentRequest<Env>(
797
1857
  response = new Response(response.body, {
798
1858
  headers: {
799
1859
  ...response.headers,
800
- ...corsHeaders,
801
- },
1860
+ ...corsHeaders
1861
+ }
802
1862
  });
803
1863
  }
804
1864
  return response;
805
1865
  }
806
1866
 
1867
+ export type EmailResolver<Env> = (
1868
+ email: ForwardableEmailMessage,
1869
+ env: Env
1870
+ ) => Promise<{
1871
+ agentName: string;
1872
+ agentId: string;
1873
+ } | null>;
1874
+
1875
+ /**
1876
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1877
+ * @returns A function that resolves the agent to route the email to
1878
+ */
1879
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1880
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1881
+ const messageId = email.headers.get("message-id");
1882
+ if (messageId) {
1883
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1884
+ if (messageIdMatch) {
1885
+ const [, agentId, domain] = messageIdMatch;
1886
+ const agentName = domain.split(".")[0];
1887
+ return { agentName, agentId };
1888
+ }
1889
+ }
1890
+
1891
+ const references = email.headers.get("references");
1892
+ if (references) {
1893
+ const referencesMatch = references.match(
1894
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1895
+ );
1896
+ if (referencesMatch) {
1897
+ const [, base64Id, domain] = referencesMatch;
1898
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1899
+ const agentName = domain.split(".")[0];
1900
+ return { agentName, agentId };
1901
+ }
1902
+ }
1903
+
1904
+ const agentName = email.headers.get("x-agent-name");
1905
+ const agentId = email.headers.get("x-agent-id");
1906
+ if (agentName && agentId) {
1907
+ return { agentName, agentId };
1908
+ }
1909
+
1910
+ return null;
1911
+ };
1912
+ }
1913
+
1914
+ /**
1915
+ * Create a resolver that uses the email address to determine the agent to route the email to
1916
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1917
+ * @returns A function that resolves the agent to route the email to
1918
+ */
1919
+ export function createAddressBasedEmailResolver<Env>(
1920
+ defaultAgentName: string
1921
+ ): EmailResolver<Env> {
1922
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1923
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1924
+ if (!emailMatch) {
1925
+ return null;
1926
+ }
1927
+
1928
+ const [, localPart, subAddress] = emailMatch;
1929
+
1930
+ if (subAddress) {
1931
+ return {
1932
+ agentName: localPart,
1933
+ agentId: subAddress
1934
+ };
1935
+ }
1936
+
1937
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1938
+ // Common for catch-all email routing to a single EmailAgent namespace
1939
+ return {
1940
+ agentName: defaultAgentName,
1941
+ agentId: localPart
1942
+ };
1943
+ };
1944
+ }
1945
+
1946
+ /**
1947
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1948
+ * @param agentName The name of the agent to route the email to
1949
+ * @param agentId The id of the agent to route the email to
1950
+ * @returns A function that resolves the agent to route the email to
1951
+ */
1952
+ export function createCatchAllEmailResolver<Env>(
1953
+ agentName: string,
1954
+ agentId: string
1955
+ ): EmailResolver<Env> {
1956
+ return async () => ({ agentName, agentId });
1957
+ }
1958
+
1959
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1960
+ resolver: EmailResolver<Env>;
1961
+ };
1962
+
1963
+ // Cache the agent namespace map for email routing
1964
+ // This maps both kebab-case and original names to namespaces
1965
+ const agentMapCache = new WeakMap<
1966
+ Record<string, unknown>,
1967
+ Record<string, unknown>
1968
+ >();
1969
+
807
1970
  /**
808
1971
  * Route an email to the appropriate Agent
809
- * @param email Email message to route
810
- * @param env Environment containing Agent bindings
811
- * @param options Routing options
1972
+ * @param email The email to route
1973
+ * @param env The environment containing the Agent bindings
1974
+ * @param options The options for routing the email
1975
+ * @returns A promise that resolves when the email has been routed
812
1976
  */
813
1977
  export async function routeAgentEmail<Env>(
814
1978
  email: ForwardableEmailMessage,
815
1979
  env: Env,
816
- options?: AgentOptions<Env>
817
- ): Promise<void> {}
1980
+ options: EmailRoutingOptions<Env>
1981
+ ): Promise<void> {
1982
+ const routingInfo = await options.resolver(email, env);
1983
+
1984
+ if (!routingInfo) {
1985
+ console.warn("No routing information found for email, dropping message");
1986
+ return;
1987
+ }
1988
+
1989
+ // Build a map that includes both original names and kebab-case versions
1990
+ if (!agentMapCache.has(env as Record<string, unknown>)) {
1991
+ const map: Record<string, unknown> = {};
1992
+ for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1993
+ if (
1994
+ value &&
1995
+ typeof value === "object" &&
1996
+ "idFromName" in value &&
1997
+ typeof value.idFromName === "function"
1998
+ ) {
1999
+ // Add both the original name and kebab-case version
2000
+ map[key] = value;
2001
+ map[camelCaseToKebabCase(key)] = value;
2002
+ }
2003
+ }
2004
+ agentMapCache.set(env as Record<string, unknown>, map);
2005
+ }
2006
+
2007
+ const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
2008
+ const namespace = agentMap[routingInfo.agentName];
2009
+
2010
+ if (!namespace) {
2011
+ // Provide helpful error message listing available agents
2012
+ const availableAgents = Object.keys(agentMap)
2013
+ .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
2014
+ .join(", ");
2015
+ throw new Error(
2016
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
2017
+ );
2018
+ }
2019
+
2020
+ const agent = await getAgentByName(
2021
+ namespace as unknown as AgentNamespace<Agent<Env>>,
2022
+ routingInfo.agentId
2023
+ );
2024
+
2025
+ // let's make a serialisable version of the email
2026
+ const serialisableEmail: AgentEmail = {
2027
+ getRaw: async () => {
2028
+ const reader = email.raw.getReader();
2029
+ const chunks: Uint8Array[] = [];
2030
+
2031
+ let done = false;
2032
+ while (!done) {
2033
+ const { value, done: readerDone } = await reader.read();
2034
+ done = readerDone;
2035
+ if (value) {
2036
+ chunks.push(value);
2037
+ }
2038
+ }
2039
+
2040
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
2041
+ const combined = new Uint8Array(totalLength);
2042
+ let offset = 0;
2043
+ for (const chunk of chunks) {
2044
+ combined.set(chunk, offset);
2045
+ offset += chunk.length;
2046
+ }
2047
+
2048
+ return combined;
2049
+ },
2050
+ headers: email.headers,
2051
+ rawSize: email.rawSize,
2052
+ setReject: (reason: string) => {
2053
+ email.setReject(reason);
2054
+ },
2055
+ forward: (rcptTo: string, headers?: Headers) => {
2056
+ return email.forward(rcptTo, headers);
2057
+ },
2058
+ reply: (options: { from: string; to: string; raw: string }) => {
2059
+ return email.reply(
2060
+ new EmailMessage(options.from, options.to, options.raw)
2061
+ );
2062
+ },
2063
+ from: email.from,
2064
+ to: email.to
2065
+ };
2066
+
2067
+ await agent._onEmail(serialisableEmail);
2068
+ }
2069
+
2070
+ export type AgentEmail = {
2071
+ from: string;
2072
+ to: string;
2073
+ getRaw: () => Promise<Uint8Array>;
2074
+ headers: Headers;
2075
+ rawSize: number;
2076
+ setReject: (reason: string) => void;
2077
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
2078
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
2079
+ };
2080
+
2081
+ export type EmailSendOptions = {
2082
+ to: string;
2083
+ subject: string;
2084
+ body: string;
2085
+ contentType?: string;
2086
+ headers?: Record<string, string>;
2087
+ includeRoutingHeaders?: boolean;
2088
+ agentName?: string;
2089
+ agentId?: string;
2090
+ domain?: string;
2091
+ };
818
2092
 
819
2093
  /**
820
2094
  * Get or create an Agent by name
@@ -825,12 +2099,17 @@ export async function routeAgentEmail<Env>(
825
2099
  * @param options Options for Agent creation
826
2100
  * @returns Promise resolving to an Agent instance stub
827
2101
  */
828
- export function getAgentByName<Env, T extends Agent<Env>>(
2102
+ export async function getAgentByName<
2103
+ Env,
2104
+ T extends Agent<Env>,
2105
+ Props extends Record<string, unknown> = Record<string, unknown>
2106
+ >(
829
2107
  namespace: AgentNamespace<T>,
830
2108
  name: string,
831
2109
  options?: {
832
2110
  jurisdiction?: DurableObjectJurisdiction;
833
2111
  locationHint?: DurableObjectLocationHint;
2112
+ props?: Props;
834
2113
  }
835
2114
  ) {
836
2115
  return getServerByName<Env, T>(namespace, name, options);
@@ -840,13 +2119,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
840
2119
  * A wrapper for streaming responses in callable methods
841
2120
  */
842
2121
  export class StreamingResponse {
843
- #connection: Connection;
844
- #id: string;
845
- #closed = false;
2122
+ private _connection: Connection;
2123
+ private _id: string;
2124
+ private _closed = false;
846
2125
 
847
2126
  constructor(connection: Connection, id: string) {
848
- this.#connection = connection;
849
- this.#id = id;
2127
+ this._connection = connection;
2128
+ this._id = id;
850
2129
  }
851
2130
 
852
2131
  /**
@@ -854,17 +2133,17 @@ export class StreamingResponse {
854
2133
  * @param chunk The data to send
855
2134
  */
856
2135
  send(chunk: unknown) {
857
- if (this.#closed) {
2136
+ if (this._closed) {
858
2137
  throw new Error("StreamingResponse is already closed");
859
2138
  }
860
2139
  const response: RPCResponse = {
861
- type: "rpc",
862
- id: this.#id,
863
- success: true,
864
- result: chunk,
865
2140
  done: false,
2141
+ id: this._id,
2142
+ result: chunk,
2143
+ success: true,
2144
+ type: MessageType.RPC
866
2145
  };
867
- this.#connection.send(JSON.stringify(response));
2146
+ this._connection.send(JSON.stringify(response));
868
2147
  }
869
2148
 
870
2149
  /**
@@ -872,17 +2151,17 @@ export class StreamingResponse {
872
2151
  * @param finalChunk Optional final chunk of data to send
873
2152
  */
874
2153
  end(finalChunk?: unknown) {
875
- if (this.#closed) {
2154
+ if (this._closed) {
876
2155
  throw new Error("StreamingResponse is already closed");
877
2156
  }
878
- this.#closed = true;
2157
+ this._closed = true;
879
2158
  const response: RPCResponse = {
880
- type: "rpc",
881
- id: this.#id,
882
- success: true,
883
- result: finalChunk,
884
2159
  done: true,
2160
+ id: this._id,
2161
+ result: finalChunk,
2162
+ success: true,
2163
+ type: MessageType.RPC
885
2164
  };
886
- this.#connection.send(JSON.stringify(response));
2165
+ this._connection.send(JSON.stringify(response));
887
2166
  }
888
2167
  }