agents 0.0.0-c552d8b → 0.0.0-c5e3a32

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 (47) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +32 -5
  3. package/dist/ai-chat-agent.js +149 -115
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +18 -5
  6. package/dist/ai-react.js +28 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/chunk-EDUDXISR.js +1148 -0
  9. package/dist/chunk-EDUDXISR.js.map +1 -0
  10. package/dist/chunk-KUH345EY.js +116 -0
  11. package/dist/chunk-KUH345EY.js.map +1 -0
  12. package/dist/{chunk-Q5ZBHY4Z.js → chunk-MW5BQ2FW.js} +49 -36
  13. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  14. package/dist/chunk-PVQZBKN7.js +106 -0
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +16 -2
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index-DukU3sIa.d.ts +571 -0
  20. package/dist/index.d.ts +32 -308
  21. package/dist/index.js +10 -3
  22. package/dist/mcp/client.d.ts +301 -23
  23. package/dist/mcp/client.js +1 -2
  24. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  25. package/dist/mcp/do-oauth-client-provider.js +3 -103
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  27. package/dist/mcp/index.d.ts +23 -13
  28. package/dist/mcp/index.js +150 -175
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/observability/index.d.ts +12 -0
  31. package/dist/observability/index.js +10 -0
  32. package/dist/react.d.ts +85 -5
  33. package/dist/react.js +20 -8
  34. package/dist/react.js.map +1 -1
  35. package/dist/schedule.d.ts +6 -6
  36. package/dist/schedule.js +4 -6
  37. package/dist/schedule.js.map +1 -1
  38. package/dist/serializable.d.ts +32 -0
  39. package/dist/serializable.js +1 -0
  40. package/dist/serializable.js.map +1 -0
  41. package/package.json +76 -68
  42. package/src/index.ts +926 -136
  43. package/dist/chunk-HMLY7DHA.js +0 -16
  44. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  45. package/dist/chunk-WNIGPPNB.js +0 -608
  46. package/dist/chunk-WNIGPPNB.js.map +0 -1
  47. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,20 +1,32 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
4
+
5
+ import type {
6
+ Prompt,
7
+ Resource,
8
+ ServerCapabilities,
9
+ Tool
10
+ } from "@modelcontextprotocol/sdk/types.js";
11
+ import { parseCronExpression } from "cron-schedule";
12
+ import { nanoid } from "nanoid";
13
+ import { EmailMessage } from "cloudflare:email";
1
14
  import {
2
- Server,
3
- routePartykitRequest,
4
- type PartyServerOptions,
5
- getServerByName,
6
15
  type Connection,
7
16
  type ConnectionContext,
17
+ type PartyServerOptions,
18
+ Server,
8
19
  type WSMessage,
20
+ getServerByName,
21
+ routePartykitRequest
9
22
  } from "partyserver";
10
-
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- import { AsyncLocalStorage } from "node:async_hooks";
23
+ import { camelCaseToKebabCase } from "./client";
15
24
  import { MCPClientManager } from "./mcp/client";
25
+ // import type { MCPClientConnection } from "./mcp/client-connection";
26
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
27
+ import { genericObservability, type Observability } from "./observability";
16
28
 
17
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
29
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
18
30
 
19
31
  /**
20
32
  * RPC request message from client
@@ -98,7 +110,6 @@ export type CallableMetadata = {
98
110
  streaming?: boolean;
99
111
  };
100
112
 
101
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
102
113
  const callableMetadata = new Map<Function, CallableMetadata>();
103
114
 
104
115
  /**
@@ -108,6 +119,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
108
119
  export function unstable_callable(metadata: CallableMetadata = {}) {
109
120
  return function callableDecorator<This, Args extends unknown[], Return>(
110
121
  target: (this: This, ...args: Args) => Return,
122
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
111
123
  context: ClassMethodDecoratorContext
112
124
  ) {
113
125
  if (!callableMetadata.has(target)) {
@@ -159,29 +171,74 @@ function getNextCronTime(cron: string) {
159
171
  return interval.getNextDate();
160
172
  }
161
173
 
174
+ /**
175
+ * MCP Server state update message from server -> Client
176
+ */
177
+ export type MCPServerMessage = {
178
+ type: "cf_agent_mcp_servers";
179
+ mcp: MCPServersState;
180
+ };
181
+
182
+ export type MCPServersState = {
183
+ servers: {
184
+ [id: string]: MCPServer;
185
+ };
186
+ tools: Tool[];
187
+ prompts: Prompt[];
188
+ resources: Resource[];
189
+ };
190
+
191
+ export type MCPServer = {
192
+ name: string;
193
+ server_url: string;
194
+ auth_url: string | null;
195
+ // This state is specifically about the temporary process of getting a token (if needed).
196
+ // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
197
+ // to communicate a change to a non-ready state.
198
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
199
+ instructions: string | null;
200
+ capabilities: ServerCapabilities | null;
201
+ };
202
+
203
+ /**
204
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
205
+ */
206
+ type MCPServerRow = {
207
+ id: string;
208
+ name: string;
209
+ server_url: string;
210
+ client_id: string | null;
211
+ auth_url: string | null;
212
+ callback_url: string;
213
+ server_options: string;
214
+ };
215
+
162
216
  const STATE_ROW_ID = "cf_state_row_id";
163
217
  const STATE_WAS_CHANGED = "cf_state_was_changed";
164
218
 
165
219
  const DEFAULT_STATE = {} as unknown;
166
220
 
167
221
  const agentContext = new AsyncLocalStorage<{
168
- agent: Agent<unknown>;
222
+ agent: Agent<unknown, unknown>;
169
223
  connection: Connection | undefined;
170
224
  request: Request | undefined;
225
+ email: AgentEmail | undefined;
171
226
  }>();
172
227
 
173
228
  export function getCurrentAgent<
174
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
229
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
175
230
  >(): {
176
231
  agent: T | undefined;
177
232
  connection: Connection | undefined;
178
- request: Request<unknown, CfProperties<unknown>> | undefined;
233
+ request: Request | undefined;
234
+ email: AgentEmail | undefined;
179
235
  } {
180
236
  const store = agentContext.getStore() as
181
237
  | {
182
238
  agent: T;
183
239
  connection: Connection | undefined;
184
- request: Request<unknown, CfProperties<unknown>> | undefined;
240
+ request: Request | undefined;
241
+ email: AgentEmail | undefined;
185
242
  }
186
243
  | undefined;
187
244
  if (!store) {
@@ -189,23 +246,43 @@ export function getCurrentAgent<
189
246
  agent: undefined,
190
247
  connection: undefined,
191
248
  request: undefined,
249
+ email: undefined
192
250
  };
193
251
  }
194
252
  return store;
195
253
  }
196
254
 
255
+ /**
256
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
257
+ * @param agent The agent instance
258
+ * @param method The method to wrap
259
+ * @returns A wrapped method that runs within the agent context
260
+ */
261
+
262
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
263
+ function withAgentContext<T extends (...args: any[]) => any>(
264
+ method: T
265
+ ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
266
+ return function (...args: Parameters<T>): ReturnType<T> {
267
+ const { connection, request, email } = getCurrentAgent();
268
+ return agentContext.run({ agent: this, connection, request, email }, () => {
269
+ return method.apply(this, args);
270
+ });
271
+ };
272
+ }
273
+
197
274
  /**
198
275
  * Base class for creating Agent implementations
199
276
  * @template Env Environment type containing bindings
200
277
  * @template State State type to store within the Agent
201
278
  */
202
279
  export class Agent<Env, State = unknown> extends Server<Env> {
203
- #state = DEFAULT_STATE as State;
280
+ private _state = DEFAULT_STATE as State;
204
281
 
205
- #ParentClass: typeof Agent<Env, State> =
282
+ private _ParentClass: typeof Agent<Env, State> =
206
283
  Object.getPrototypeOf(this).constructor;
207
284
 
208
- mcp: MCPClientManager = new MCPClientManager(this.#ParentClass.name, "0.0.1");
285
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
209
286
 
210
287
  /**
211
288
  * Initial state for the Agent
@@ -217,9 +294,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
217
294
  * Current state of the Agent
218
295
  */
219
296
  get state(): State {
220
- if (this.#state !== DEFAULT_STATE) {
297
+ if (this._state !== DEFAULT_STATE) {
221
298
  // state was previously set, and populated internal state
222
- return this.#state;
299
+ return this._state;
223
300
  }
224
301
  // looks like this is the first time the state is being accessed
225
302
  // check if the state was set in a previous life
@@ -239,8 +316,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
239
316
  ) {
240
317
  const state = result[0]?.state as string; // could be null?
241
318
 
242
- this.#state = JSON.parse(state);
243
- return this.#state;
319
+ this._state = JSON.parse(state);
320
+ return this._state;
244
321
  }
245
322
 
246
323
  // ok, this is the first time the state is being accessed
@@ -261,9 +338,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
261
338
  */
262
339
  static options = {
263
340
  /** Whether the Agent should hibernate when inactive */
264
- hibernate: true, // default to hibernate
341
+ hibernate: true // default to hibernate
265
342
  };
266
343
 
344
+ /**
345
+ * The observability implementation to use for the Agent
346
+ */
347
+ observability?: Observability = genericObservability;
348
+
267
349
  /**
268
350
  * Execute SQL queries against the Agent's database
269
351
  * @template T Type of the returned rows
@@ -300,8 +382,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
300
382
  )
301
383
  `;
302
384
 
385
+ // Auto-wrap custom methods with agent context
386
+ this._autoWrapCustomMethods();
387
+
303
388
  void this.ctx.blockConcurrencyWhile(async () => {
304
- return this.#tryCatch(async () => {
389
+ return this._tryCatch(async () => {
305
390
  // Create alarms table if it doesn't exist
306
391
  this.sql`
307
392
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -321,25 +406,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
321
406
  });
322
407
  });
323
408
 
409
+ this.sql`
410
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
411
+ id TEXT PRIMARY KEY NOT NULL,
412
+ name TEXT NOT NULL,
413
+ server_url TEXT NOT NULL,
414
+ callback_url TEXT NOT NULL,
415
+ client_id TEXT,
416
+ auth_url TEXT,
417
+ server_options TEXT
418
+ )
419
+ `;
420
+
421
+ const _onRequest = this.onRequest.bind(this);
422
+ this.onRequest = (request: Request) => {
423
+ return agentContext.run(
424
+ { agent: this, connection: undefined, request, email: undefined },
425
+ async () => {
426
+ if (this.mcp.isCallbackRequest(request)) {
427
+ await this.mcp.handleCallbackRequest(request);
428
+
429
+ // after the MCP connection handshake, we can send updated mcp state
430
+ this.broadcast(
431
+ JSON.stringify({
432
+ mcp: this.getMcpServers(),
433
+ type: "cf_agent_mcp_servers"
434
+ })
435
+ );
436
+
437
+ // We probably should let the user configure this response/redirect, but this is fine for now.
438
+ return new Response("<script>window.close();</script>", {
439
+ headers: { "content-type": "text/html" },
440
+ status: 200
441
+ });
442
+ }
443
+
444
+ return this._tryCatch(() => _onRequest(request));
445
+ }
446
+ );
447
+ };
448
+
324
449
  const _onMessage = this.onMessage.bind(this);
325
450
  this.onMessage = async (connection: Connection, message: WSMessage) => {
326
451
  return agentContext.run(
327
- { agent: this, connection, request: undefined },
452
+ { agent: this, connection, request: undefined, email: undefined },
328
453
  async () => {
329
454
  if (typeof message !== "string") {
330
- return this.#tryCatch(() => _onMessage(connection, message));
455
+ return this._tryCatch(() => _onMessage(connection, message));
331
456
  }
332
457
 
333
458
  let parsed: unknown;
334
459
  try {
335
460
  parsed = JSON.parse(message);
336
- } catch (e) {
461
+ } catch (_e) {
337
462
  // silently fail and let the onMessage handler handle it
338
- return this.#tryCatch(() => _onMessage(connection, message));
463
+ return this._tryCatch(() => _onMessage(connection, message));
339
464
  }
340
465
 
341
466
  if (isStateUpdateMessage(parsed)) {
342
- this.#setStateInternal(parsed.state as State, connection);
467
+ this._setStateInternal(parsed.state as State, connection);
343
468
  return;
344
469
  }
345
470
 
@@ -353,11 +478,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
353
478
  throw new Error(`Method ${method} does not exist`);
354
479
  }
355
480
 
356
- if (!this.#isCallable(method)) {
481
+ if (!this._isCallable(method)) {
357
482
  throw new Error(`Method ${method} is not callable`);
358
483
  }
359
484
 
360
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
361
485
  const metadata = callableMetadata.get(methodFn as Function);
362
486
 
363
487
  // For streaming methods, pass a StreamingResponse object
@@ -369,22 +493,39 @@ export class Agent<Env, State = unknown> extends Server<Env> {
369
493
 
370
494
  // For regular methods, execute and send response
371
495
  const result = await methodFn.apply(this, args);
496
+
497
+ this.observability?.emit(
498
+ {
499
+ displayMessage: `RPC call to ${method}`,
500
+ id: nanoid(),
501
+ payload: {
502
+ args,
503
+ method,
504
+ streaming: metadata?.streaming,
505
+ success: true
506
+ },
507
+ timestamp: Date.now(),
508
+ type: "rpc"
509
+ },
510
+ this.ctx
511
+ );
512
+
372
513
  const response: RPCResponse = {
373
- type: "rpc",
514
+ done: true,
374
515
  id,
375
- success: true,
376
516
  result,
377
- done: true,
517
+ success: true,
518
+ type: "rpc"
378
519
  };
379
520
  connection.send(JSON.stringify(response));
380
521
  } catch (e) {
381
522
  // Send error response
382
523
  const response: RPCResponse = {
383
- type: "rpc",
384
- id: parsed.id,
385
- success: false,
386
524
  error:
387
525
  e instanceof Error ? e.message : "Unknown error occurred",
526
+ id: parsed.id,
527
+ success: false,
528
+ type: "rpc"
388
529
  };
389
530
  connection.send(JSON.stringify(response));
390
531
  console.error("RPC error:", e);
@@ -392,7 +533,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
392
533
  return;
393
534
  }
394
535
 
395
- return this.#tryCatch(() => _onMessage(connection, message));
536
+ return this._tryCatch(() => _onMessage(connection, message));
396
537
  }
397
538
  );
398
539
  };
@@ -402,26 +543,95 @@ export class Agent<Env, State = unknown> extends Server<Env> {
402
543
  // TODO: This is a hack to ensure the state is sent after the connection is established
403
544
  // must fix this
404
545
  return agentContext.run(
405
- { agent: this, connection, request: ctx.request },
546
+ { agent: this, connection, request: ctx.request, email: undefined },
406
547
  async () => {
407
548
  setTimeout(() => {
408
549
  if (this.state) {
409
550
  connection.send(
410
551
  JSON.stringify({
411
- type: "cf_agent_state",
412
552
  state: this.state,
553
+ type: "cf_agent_state"
413
554
  })
414
555
  );
415
556
  }
416
- return this.#tryCatch(() => _onConnect(connection, ctx));
557
+
558
+ connection.send(
559
+ JSON.stringify({
560
+ mcp: this.getMcpServers(),
561
+ type: "cf_agent_mcp_servers"
562
+ })
563
+ );
564
+
565
+ this.observability?.emit(
566
+ {
567
+ displayMessage: "Connection established",
568
+ id: nanoid(),
569
+ payload: {
570
+ connectionId: connection.id
571
+ },
572
+ timestamp: Date.now(),
573
+ type: "connect"
574
+ },
575
+ this.ctx
576
+ );
577
+ return this._tryCatch(() => _onConnect(connection, ctx));
417
578
  }, 20);
418
579
  }
419
580
  );
420
581
  };
582
+
583
+ const _onStart = this.onStart.bind(this);
584
+ this.onStart = async () => {
585
+ return agentContext.run(
586
+ {
587
+ agent: this,
588
+ connection: undefined,
589
+ request: undefined,
590
+ email: undefined
591
+ },
592
+ async () => {
593
+ const servers = this.sql<MCPServerRow>`
594
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
595
+ `;
596
+
597
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
598
+ if (servers && Array.isArray(servers) && servers.length > 0) {
599
+ Promise.allSettled(
600
+ servers.map((server) => {
601
+ return this._connectToMcpServerInternal(
602
+ server.name,
603
+ server.server_url,
604
+ server.callback_url,
605
+ server.server_options
606
+ ? JSON.parse(server.server_options)
607
+ : undefined,
608
+ {
609
+ id: server.id,
610
+ oauthClientId: server.client_id ?? undefined
611
+ }
612
+ );
613
+ })
614
+ ).then((_results) => {
615
+ this.broadcast(
616
+ JSON.stringify({
617
+ mcp: this.getMcpServers(),
618
+ type: "cf_agent_mcp_servers"
619
+ })
620
+ );
621
+ });
622
+ }
623
+ await this._tryCatch(() => _onStart());
624
+ }
625
+ );
626
+ };
421
627
  }
422
628
 
423
- #setStateInternal(state: State, source: Connection | "server" = "server") {
424
- this.#state = state;
629
+ private _setStateInternal(
630
+ state: State,
631
+ source: Connection | "server" = "server"
632
+ ) {
633
+ const previousState = this._state;
634
+ this._state = state;
425
635
  this.sql`
426
636
  INSERT OR REPLACE INTO cf_agents_state (id, state)
427
637
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -432,16 +642,29 @@ export class Agent<Env, State = unknown> extends Server<Env> {
432
642
  `;
433
643
  this.broadcast(
434
644
  JSON.stringify({
435
- type: "cf_agent_state",
436
645
  state: state,
646
+ type: "cf_agent_state"
437
647
  }),
438
648
  source !== "server" ? [source.id] : []
439
649
  );
440
- return this.#tryCatch(() => {
441
- const { connection, request } = agentContext.getStore() || {};
650
+ return this._tryCatch(() => {
651
+ const { connection, request, email } = agentContext.getStore() || {};
442
652
  return agentContext.run(
443
- { agent: this, connection, request },
653
+ { agent: this, connection, request, email },
444
654
  async () => {
655
+ this.observability?.emit(
656
+ {
657
+ displayMessage: "State updated",
658
+ id: nanoid(),
659
+ payload: {
660
+ previousState,
661
+ state
662
+ },
663
+ timestamp: Date.now(),
664
+ type: "state:update"
665
+ },
666
+ this.ctx
667
+ );
445
668
  return this.onStateUpdate(state, source);
446
669
  }
447
670
  );
@@ -453,7 +676,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
453
676
  * @param state New state to set
454
677
  */
455
678
  setState(state: State) {
456
- this.#setStateInternal(state, "server");
679
+ this._setStateInternal(state, "server");
457
680
  }
458
681
 
459
682
  /**
@@ -461,24 +684,90 @@ export class Agent<Env, State = unknown> extends Server<Env> {
461
684
  * @param state Updated state
462
685
  * @param source Source of the state update ("server" or a client connection)
463
686
  */
687
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
464
688
  onStateUpdate(state: State | undefined, source: Connection | "server") {
465
689
  // override this to handle state updates
466
690
  }
467
691
 
468
692
  /**
469
- * Called when the Agent receives an email
693
+ * Called when the Agent receives an email via routeAgentEmail()
694
+ * Override this method to handle incoming emails
470
695
  * @param email Email message to process
471
696
  */
472
- onEmail(email: ForwardableEmailMessage) {
697
+ async _onEmail(email: AgentEmail) {
698
+ // nb: we use this roundabout way of getting to onEmail
699
+ // because of https://github.com/cloudflare/workerd/issues/4499
473
700
  return agentContext.run(
474
- { agent: this, connection: undefined, request: undefined },
701
+ { agent: this, connection: undefined, request: undefined, email: email },
475
702
  async () => {
476
- console.error("onEmail not implemented");
703
+ if ("onEmail" in this && typeof this.onEmail === "function") {
704
+ return this._tryCatch(() =>
705
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
706
+ );
707
+ } else {
708
+ console.log("Received email from:", email.from, "to:", email.to);
709
+ console.log("Subject:", email.headers.get("subject"));
710
+ console.log(
711
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
712
+ );
713
+ }
477
714
  }
478
715
  );
479
716
  }
480
717
 
481
- async #tryCatch<T>(fn: () => T | Promise<T>) {
718
+ /**
719
+ * Reply to an email
720
+ * @param email The email to reply to
721
+ * @param options Options for the reply
722
+ * @returns void
723
+ */
724
+ async replyToEmail(
725
+ email: AgentEmail,
726
+ options: {
727
+ fromName: string;
728
+ subject?: string | undefined;
729
+ body: string;
730
+ contentType?: string;
731
+ headers?: Record<string, string>;
732
+ }
733
+ ): Promise<void> {
734
+ return this._tryCatch(async () => {
735
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
736
+ const agentId = this.name;
737
+
738
+ const { createMimeMessage } = await import("mimetext");
739
+ const msg = createMimeMessage();
740
+ msg.setSender({ addr: email.to, name: options.fromName });
741
+ msg.setRecipient(email.from);
742
+ msg.setSubject(
743
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
744
+ );
745
+ msg.addMessage({
746
+ contentType: options.contentType || "text/plain",
747
+ data: options.body
748
+ });
749
+
750
+ const domain = email.from.split("@")[1];
751
+ const messageId = `<${agentId}@${domain}>`;
752
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
753
+ msg.setHeader("Message-ID", messageId);
754
+ msg.setHeader("X-Agent-Name", agentName);
755
+ msg.setHeader("X-Agent-ID", agentId);
756
+
757
+ if (options.headers) {
758
+ for (const [key, value] of Object.entries(options.headers)) {
759
+ msg.setHeader(key, value);
760
+ }
761
+ }
762
+ await email.reply({
763
+ from: email.to,
764
+ raw: msg.asRaw(),
765
+ to: email.from
766
+ });
767
+ });
768
+ }
769
+
770
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
482
771
  try {
483
772
  return await fn();
484
773
  } catch (e) {
@@ -486,6 +775,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
486
775
  }
487
776
  }
488
777
 
778
+ /**
779
+ * Automatically wrap custom methods with agent context
780
+ * This ensures getCurrentAgent() works in all custom methods without decorators
781
+ */
782
+ private _autoWrapCustomMethods() {
783
+ // Collect all methods from base prototypes (Agent and Server)
784
+ const basePrototypes = [Agent.prototype, Server.prototype];
785
+ const baseMethods = new Set<string>();
786
+ for (const baseProto of basePrototypes) {
787
+ let proto = baseProto;
788
+ while (proto && proto !== Object.prototype) {
789
+ const methodNames = Object.getOwnPropertyNames(proto);
790
+ for (const methodName of methodNames) {
791
+ baseMethods.add(methodName);
792
+ }
793
+ proto = Object.getPrototypeOf(proto);
794
+ }
795
+ }
796
+ // Get all methods from the current instance's prototype chain
797
+ let proto = Object.getPrototypeOf(this);
798
+ let depth = 0;
799
+ while (proto && proto !== Object.prototype && depth < 10) {
800
+ const methodNames = Object.getOwnPropertyNames(proto);
801
+ for (const methodName of methodNames) {
802
+ // Skip if it's a private method or not a function
803
+ if (
804
+ baseMethods.has(methodName) ||
805
+ methodName.startsWith("_") ||
806
+ typeof this[methodName as keyof this] !== "function"
807
+ ) {
808
+ continue;
809
+ }
810
+ // If the method doesn't exist in base prototypes, it's a custom method
811
+ if (!baseMethods.has(methodName)) {
812
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
813
+ if (descriptor && typeof descriptor.value === "function") {
814
+ // Wrap the custom method with context
815
+
816
+ const wrappedFunction = withAgentContext(
817
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
818
+ this[methodName as keyof this] as (...args: any[]) => any
819
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
820
+ ) as any;
821
+
822
+ // if the method is callable, copy the metadata from the original method
823
+ if (this._isCallable(methodName)) {
824
+ callableMetadata.set(
825
+ wrappedFunction,
826
+ callableMetadata.get(
827
+ this[methodName as keyof this] as Function
828
+ )!
829
+ );
830
+ }
831
+
832
+ // set the wrapped function on the prototype
833
+ this.constructor.prototype[methodName as keyof this] =
834
+ wrappedFunction;
835
+ }
836
+ }
837
+ }
838
+
839
+ proto = Object.getPrototypeOf(proto);
840
+ depth++;
841
+ }
842
+ }
843
+
489
844
  override onError(
490
845
  connection: Connection,
491
846
  error: unknown
@@ -535,6 +890,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
535
890
  ): Promise<Schedule<T>> {
536
891
  const id = nanoid(9);
537
892
 
893
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
894
+ this.observability?.emit(
895
+ {
896
+ displayMessage: `Schedule ${schedule.id} created`,
897
+ id: nanoid(),
898
+ payload: schedule,
899
+ timestamp: Date.now(),
900
+ type: "schedule:create"
901
+ },
902
+ this.ctx
903
+ );
904
+
538
905
  if (typeof callback !== "string") {
539
906
  throw new Error("Callback must be a string");
540
907
  }
@@ -552,15 +919,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
552
919
  )}, 'scheduled', ${timestamp})
553
920
  `;
554
921
 
555
- await this.#scheduleNextAlarm();
922
+ await this._scheduleNextAlarm();
556
923
 
557
- return {
558
- id,
924
+ const schedule: Schedule<T> = {
559
925
  callback: callback,
926
+ id,
560
927
  payload: payload as T,
561
928
  time: timestamp,
562
- type: "scheduled",
929
+ type: "scheduled"
563
930
  };
931
+
932
+ emitScheduleCreate(schedule);
933
+
934
+ return schedule;
564
935
  }
565
936
  if (typeof when === "number") {
566
937
  const time = new Date(Date.now() + when * 1000);
@@ -573,16 +944,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
573
944
  )}, 'delayed', ${when}, ${timestamp})
574
945
  `;
575
946
 
576
- await this.#scheduleNextAlarm();
947
+ await this._scheduleNextAlarm();
577
948
 
578
- return {
579
- id,
949
+ const schedule: Schedule<T> = {
580
950
  callback: callback,
581
- payload: payload as T,
582
951
  delayInSeconds: when,
952
+ id,
953
+ payload: payload as T,
583
954
  time: timestamp,
584
- type: "delayed",
955
+ type: "delayed"
585
956
  };
957
+
958
+ emitScheduleCreate(schedule);
959
+
960
+ return schedule;
586
961
  }
587
962
  if (typeof when === "string") {
588
963
  const nextExecutionTime = getNextCronTime(when);
@@ -595,16 +970,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
595
970
  )}, 'cron', ${when}, ${timestamp})
596
971
  `;
597
972
 
598
- await this.#scheduleNextAlarm();
973
+ await this._scheduleNextAlarm();
599
974
 
600
- return {
601
- id,
975
+ const schedule: Schedule<T> = {
602
976
  callback: callback,
603
- payload: payload as T,
604
977
  cron: when,
978
+ id,
979
+ payload: payload as T,
605
980
  time: timestamp,
606
- type: "cron",
981
+ type: "cron"
607
982
  };
983
+
984
+ emitScheduleCreate(schedule);
985
+
986
+ return schedule;
608
987
  }
609
988
  throw new Error("Invalid schedule type");
610
989
  }
@@ -668,7 +1047,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
668
1047
  .toArray()
669
1048
  .map((row) => ({
670
1049
  ...row,
671
- payload: JSON.parse(row.payload as string) as T,
1050
+ payload: JSON.parse(row.payload as string) as T
672
1051
  })) as Schedule<T>[];
673
1052
 
674
1053
  return result;
@@ -680,13 +1059,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
680
1059
  * @returns true if the task was cancelled, false otherwise
681
1060
  */
682
1061
  async cancelSchedule(id: string): Promise<boolean> {
1062
+ const schedule = await this.getSchedule(id);
1063
+ if (schedule) {
1064
+ this.observability?.emit(
1065
+ {
1066
+ displayMessage: `Schedule ${id} cancelled`,
1067
+ id: nanoid(),
1068
+ payload: schedule,
1069
+ timestamp: Date.now(),
1070
+ type: "schedule:cancel"
1071
+ },
1072
+ this.ctx
1073
+ );
1074
+ }
683
1075
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
684
1076
 
685
- await this.#scheduleNextAlarm();
1077
+ await this._scheduleNextAlarm();
686
1078
  return true;
687
1079
  }
688
1080
 
689
- async #scheduleNextAlarm() {
1081
+ private async _scheduleNextAlarm() {
690
1082
  // Find the next schedule that needs to be executed
691
1083
  const result = this.sql`
692
1084
  SELECT time FROM cf_agents_schedules
@@ -703,10 +1095,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
703
1095
  }
704
1096
 
705
1097
  /**
706
- * Method called when an alarm fires
707
- * Executes any scheduled tasks that are due
1098
+ * Method called when an alarm fires.
1099
+ * Executes any scheduled tasks that are due.
1100
+ *
1101
+ * @remarks
1102
+ * To schedule a task, please use the `this.schedule` method instead.
1103
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
708
1104
  */
709
- async alarm() {
1105
+ public readonly alarm = async () => {
710
1106
  const now = Math.floor(Date.now() / 1000);
711
1107
 
712
1108
  // Get all schedules that should be executed now
@@ -714,46 +1110,64 @@ export class Agent<Env, State = unknown> extends Server<Env> {
714
1110
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
715
1111
  `;
716
1112
 
717
- for (const row of result || []) {
718
- const callback = this[row.callback as keyof Agent<Env>];
719
- if (!callback) {
720
- console.error(`callback ${row.callback} not found`);
721
- continue;
722
- }
723
- await agentContext.run(
724
- { agent: this, connection: undefined, request: undefined },
725
- async () => {
726
- try {
727
- await (
728
- callback as (
729
- payload: unknown,
730
- schedule: Schedule<unknown>
731
- ) => Promise<void>
732
- ).bind(this)(JSON.parse(row.payload as string), row);
733
- } catch (e) {
734
- console.error(`error executing callback "${row.callback}"`, e);
735
- }
1113
+ if (result && Array.isArray(result)) {
1114
+ for (const row of result) {
1115
+ const callback = this[row.callback as keyof Agent<Env>];
1116
+ if (!callback) {
1117
+ console.error(`callback ${row.callback} not found`);
1118
+ continue;
736
1119
  }
737
- );
738
- if (row.type === "cron") {
739
- // Update next execution time for cron schedules
740
- const nextExecutionTime = getNextCronTime(row.cron);
741
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1120
+ await agentContext.run(
1121
+ {
1122
+ agent: this,
1123
+ connection: undefined,
1124
+ request: undefined,
1125
+ email: undefined
1126
+ },
1127
+ async () => {
1128
+ try {
1129
+ this.observability?.emit(
1130
+ {
1131
+ displayMessage: `Schedule ${row.id} executed`,
1132
+ id: nanoid(),
1133
+ payload: row,
1134
+ timestamp: Date.now(),
1135
+ type: "schedule:execute"
1136
+ },
1137
+ this.ctx
1138
+ );
742
1139
 
743
- this.sql`
1140
+ await (
1141
+ callback as (
1142
+ payload: unknown,
1143
+ schedule: Schedule<unknown>
1144
+ ) => Promise<void>
1145
+ ).bind(this)(JSON.parse(row.payload as string), row);
1146
+ } catch (e) {
1147
+ console.error(`error executing callback "${row.callback}"`, e);
1148
+ }
1149
+ }
1150
+ );
1151
+ if (row.type === "cron") {
1152
+ // Update next execution time for cron schedules
1153
+ const nextExecutionTime = getNextCronTime(row.cron);
1154
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1155
+
1156
+ this.sql`
744
1157
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
745
1158
  `;
746
- } else {
747
- // Delete one-time schedules after execution
748
- this.sql`
1159
+ } else {
1160
+ // Delete one-time schedules after execution
1161
+ this.sql`
749
1162
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
750
1163
  `;
1164
+ }
751
1165
  }
752
1166
  }
753
1167
 
754
1168
  // Schedule the next alarm
755
- await this.#scheduleNextAlarm();
756
- }
1169
+ await this._scheduleNextAlarm();
1170
+ };
757
1171
 
758
1172
  /**
759
1173
  * Destroy the Agent, removing all state and scheduled tasks
@@ -762,20 +1176,202 @@ export class Agent<Env, State = unknown> extends Server<Env> {
762
1176
  // drop all tables
763
1177
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
764
1178
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1179
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
765
1180
 
766
1181
  // delete all alarms
767
1182
  await this.ctx.storage.deleteAlarm();
768
1183
  await this.ctx.storage.deleteAll();
1184
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
1185
+
1186
+ this.observability?.emit(
1187
+ {
1188
+ displayMessage: "Agent destroyed",
1189
+ id: nanoid(),
1190
+ payload: {},
1191
+ timestamp: Date.now(),
1192
+ type: "destroy"
1193
+ },
1194
+ this.ctx
1195
+ );
769
1196
  }
770
1197
 
771
1198
  /**
772
1199
  * Get all methods marked as callable on this Agent
773
1200
  * @returns A map of method names to their metadata
774
1201
  */
775
- #isCallable(method: string): boolean {
776
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
1202
+ private _isCallable(method: string): boolean {
777
1203
  return callableMetadata.has(this[method as keyof this] as Function);
778
1204
  }
1205
+
1206
+ /**
1207
+ * Connect to a new MCP Server
1208
+ *
1209
+ * @param url MCP Server SSE URL
1210
+ * @param callbackHost Base host for the agent, used for the redirect URI.
1211
+ * @param agentsPrefix agents routing prefix if not using `agents`
1212
+ * @param options MCP client and transport (header) options
1213
+ * @returns authUrl
1214
+ */
1215
+ async addMcpServer(
1216
+ serverName: string,
1217
+ url: string,
1218
+ callbackHost: string,
1219
+ agentsPrefix = "agents",
1220
+ options?: {
1221
+ client?: ConstructorParameters<typeof Client>[1];
1222
+ transport?: {
1223
+ headers: HeadersInit;
1224
+ };
1225
+ }
1226
+ ): Promise<{ id: string; authUrl: string | undefined }> {
1227
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1228
+
1229
+ const result = await this._connectToMcpServerInternal(
1230
+ serverName,
1231
+ url,
1232
+ callbackUrl,
1233
+ options
1234
+ );
1235
+ this.sql`
1236
+ INSERT
1237
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1238
+ VALUES (
1239
+ ${result.id},
1240
+ ${serverName},
1241
+ ${url},
1242
+ ${result.clientId ?? null},
1243
+ ${result.authUrl ?? null},
1244
+ ${callbackUrl},
1245
+ ${options ? JSON.stringify(options) : null}
1246
+ );
1247
+ `;
1248
+
1249
+ this.broadcast(
1250
+ JSON.stringify({
1251
+ mcp: this.getMcpServers(),
1252
+ type: "cf_agent_mcp_servers"
1253
+ })
1254
+ );
1255
+
1256
+ return result;
1257
+ }
1258
+
1259
+ async _connectToMcpServerInternal(
1260
+ _serverName: string,
1261
+ url: string,
1262
+ callbackUrl: string,
1263
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
1264
+ options?: {
1265
+ client?: ConstructorParameters<typeof Client>[1];
1266
+ /**
1267
+ * We don't expose the normal set of transport options because:
1268
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
1269
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
1270
+ *
1271
+ * 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).
1272
+ */
1273
+ transport?: {
1274
+ headers?: HeadersInit;
1275
+ };
1276
+ },
1277
+ reconnect?: {
1278
+ id: string;
1279
+ oauthClientId?: string;
1280
+ }
1281
+ ): Promise<{
1282
+ id: string;
1283
+ authUrl: string | undefined;
1284
+ clientId: string | undefined;
1285
+ }> {
1286
+ const authProvider = new DurableObjectOAuthClientProvider(
1287
+ this.ctx.storage,
1288
+ this.name,
1289
+ callbackUrl
1290
+ );
1291
+
1292
+ if (reconnect) {
1293
+ authProvider.serverId = reconnect.id;
1294
+ if (reconnect.oauthClientId) {
1295
+ authProvider.clientId = reconnect.oauthClientId;
1296
+ }
1297
+ }
1298
+
1299
+ // allows passing through transport headers if necessary
1300
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1301
+ let headerTransportOpts: SSEClientTransportOptions = {};
1302
+ if (options?.transport?.headers) {
1303
+ headerTransportOpts = {
1304
+ eventSourceInit: {
1305
+ fetch: (url, init) =>
1306
+ fetch(url, {
1307
+ ...init,
1308
+ headers: options?.transport?.headers
1309
+ })
1310
+ },
1311
+ requestInit: {
1312
+ headers: options?.transport?.headers
1313
+ }
1314
+ };
1315
+ }
1316
+
1317
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1318
+ client: options?.client,
1319
+ reconnect,
1320
+ transport: {
1321
+ ...headerTransportOpts,
1322
+ authProvider
1323
+ }
1324
+ });
1325
+
1326
+ return {
1327
+ authUrl,
1328
+ clientId,
1329
+ id
1330
+ };
1331
+ }
1332
+
1333
+ async removeMcpServer(id: string) {
1334
+ this.mcp.closeConnection(id);
1335
+ this.sql`
1336
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1337
+ `;
1338
+ this.broadcast(
1339
+ JSON.stringify({
1340
+ mcp: this.getMcpServers(),
1341
+ type: "cf_agent_mcp_servers"
1342
+ })
1343
+ );
1344
+ }
1345
+
1346
+ getMcpServers(): MCPServersState {
1347
+ const mcpState: MCPServersState = {
1348
+ prompts: this.mcp.listPrompts(),
1349
+ resources: this.mcp.listResources(),
1350
+ servers: {},
1351
+ tools: this.mcp.listTools()
1352
+ };
1353
+
1354
+ const servers = this.sql<MCPServerRow>`
1355
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1356
+ `;
1357
+
1358
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1359
+ for (const server of servers) {
1360
+ const serverConn = this.mcp.mcpConnections[server.id];
1361
+ mcpState.servers[server.id] = {
1362
+ auth_url: server.auth_url,
1363
+ capabilities: serverConn?.serverCapabilities ?? null,
1364
+ instructions: serverConn?.instructions ?? null,
1365
+ name: server.name,
1366
+ server_url: server.server_url,
1367
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1368
+ state: serverConn?.connectionState ?? "authenticating"
1369
+ };
1370
+ }
1371
+ }
1372
+
1373
+ return mcpState;
1374
+ }
779
1375
  }
780
1376
 
781
1377
  /**
@@ -815,17 +1411,17 @@ export async function routeAgentRequest<Env>(
815
1411
  const corsHeaders =
816
1412
  options?.cors === true
817
1413
  ? {
818
- "Access-Control-Allow-Origin": "*",
819
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
820
1414
  "Access-Control-Allow-Credentials": "true",
821
- "Access-Control-Max-Age": "86400",
1415
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1416
+ "Access-Control-Allow-Origin": "*",
1417
+ "Access-Control-Max-Age": "86400"
822
1418
  }
823
1419
  : options?.cors;
824
1420
 
825
1421
  if (request.method === "OPTIONS") {
826
1422
  if (corsHeaders) {
827
1423
  return new Response(null, {
828
- headers: corsHeaders,
1424
+ headers: corsHeaders
829
1425
  });
830
1426
  }
831
1427
  console.warn(
@@ -838,7 +1434,7 @@ export async function routeAgentRequest<Env>(
838
1434
  env as Record<string, unknown>,
839
1435
  {
840
1436
  prefix: "agents",
841
- ...(options as PartyServerOptions<Record<string, unknown>>),
1437
+ ...(options as PartyServerOptions<Record<string, unknown>>)
842
1438
  }
843
1439
  );
844
1440
 
@@ -851,24 +1447,218 @@ export async function routeAgentRequest<Env>(
851
1447
  response = new Response(response.body, {
852
1448
  headers: {
853
1449
  ...response.headers,
854
- ...corsHeaders,
855
- },
1450
+ ...corsHeaders
1451
+ }
856
1452
  });
857
1453
  }
858
1454
  return response;
859
1455
  }
860
1456
 
1457
+ export type EmailResolver<Env> = (
1458
+ email: ForwardableEmailMessage,
1459
+ env: Env
1460
+ ) => Promise<{
1461
+ agentName: string;
1462
+ agentId: string;
1463
+ } | null>;
1464
+
1465
+ /**
1466
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1467
+ * @returns A function that resolves the agent to route the email to
1468
+ */
1469
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1470
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1471
+ const messageId = email.headers.get("message-id");
1472
+ if (messageId) {
1473
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1474
+ if (messageIdMatch) {
1475
+ const [, agentId, domain] = messageIdMatch;
1476
+ const agentName = domain.split(".")[0];
1477
+ return { agentName, agentId };
1478
+ }
1479
+ }
1480
+
1481
+ const references = email.headers.get("references");
1482
+ if (references) {
1483
+ const referencesMatch = references.match(
1484
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1485
+ );
1486
+ if (referencesMatch) {
1487
+ const [, base64Id, domain] = referencesMatch;
1488
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1489
+ const agentName = domain.split(".")[0];
1490
+ return { agentName, agentId };
1491
+ }
1492
+ }
1493
+
1494
+ const agentName = email.headers.get("x-agent-name");
1495
+ const agentId = email.headers.get("x-agent-id");
1496
+ if (agentName && agentId) {
1497
+ return { agentName, agentId };
1498
+ }
1499
+
1500
+ return null;
1501
+ };
1502
+ }
1503
+
1504
+ /**
1505
+ * Create a resolver that uses the email address to determine the agent to route the email to
1506
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1507
+ * @returns A function that resolves the agent to route the email to
1508
+ */
1509
+ export function createAddressBasedEmailResolver<Env>(
1510
+ defaultAgentName: string
1511
+ ): EmailResolver<Env> {
1512
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1513
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1514
+ if (!emailMatch) {
1515
+ return null;
1516
+ }
1517
+
1518
+ const [, localPart, subAddress] = emailMatch;
1519
+
1520
+ if (subAddress) {
1521
+ return {
1522
+ agentName: localPart,
1523
+ agentId: subAddress
1524
+ };
1525
+ }
1526
+
1527
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1528
+ // Common for catch-all email routing to a single EmailAgent namespace
1529
+ return {
1530
+ agentName: defaultAgentName,
1531
+ agentId: localPart
1532
+ };
1533
+ };
1534
+ }
1535
+
1536
+ /**
1537
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1538
+ * @param agentName The name of the agent to route the email to
1539
+ * @param agentId The id of the agent to route the email to
1540
+ * @returns A function that resolves the agent to route the email to
1541
+ */
1542
+ export function createCatchAllEmailResolver<Env>(
1543
+ agentName: string,
1544
+ agentId: string
1545
+ ): EmailResolver<Env> {
1546
+ return async () => ({ agentName, agentId });
1547
+ }
1548
+
1549
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1550
+ resolver: EmailResolver<Env>;
1551
+ };
1552
+
861
1553
  /**
862
1554
  * Route an email to the appropriate Agent
863
- * @param email Email message to route
864
- * @param env Environment containing Agent bindings
865
- * @param options Routing options
1555
+ * @param email The email to route
1556
+ * @param env The environment containing the Agent bindings
1557
+ * @param options The options for routing the email
1558
+ * @returns A promise that resolves when the email has been routed
866
1559
  */
867
1560
  export async function routeAgentEmail<Env>(
868
1561
  email: ForwardableEmailMessage,
869
1562
  env: Env,
870
- options?: AgentOptions<Env>
871
- ): Promise<void> {}
1563
+ options: EmailRoutingOptions<Env>
1564
+ ): Promise<void> {
1565
+ const routingInfo = await options.resolver(email, env);
1566
+
1567
+ if (!routingInfo) {
1568
+ console.warn("No routing information found for email, dropping message");
1569
+ return;
1570
+ }
1571
+
1572
+ const namespaceBinding = env[routingInfo.agentName as keyof Env];
1573
+ if (!namespaceBinding) {
1574
+ throw new Error(
1575
+ `Agent namespace '${routingInfo.agentName}' not found in environment`
1576
+ );
1577
+ }
1578
+
1579
+ // Type guard to check if this is actually a DurableObjectNamespace (AgentNamespace)
1580
+ if (
1581
+ typeof namespaceBinding !== "object" ||
1582
+ !("idFromName" in namespaceBinding) ||
1583
+ typeof namespaceBinding.idFromName !== "function"
1584
+ ) {
1585
+ throw new Error(
1586
+ `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1587
+ );
1588
+ }
1589
+
1590
+ // Safe cast after runtime validation
1591
+ const namespace = namespaceBinding as unknown as AgentNamespace<Agent<Env>>;
1592
+
1593
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1594
+
1595
+ // let's make a serialisable version of the email
1596
+ const serialisableEmail: AgentEmail = {
1597
+ getRaw: async () => {
1598
+ const reader = email.raw.getReader();
1599
+ const chunks: Uint8Array[] = [];
1600
+
1601
+ let done = false;
1602
+ while (!done) {
1603
+ const { value, done: readerDone } = await reader.read();
1604
+ done = readerDone;
1605
+ if (value) {
1606
+ chunks.push(value);
1607
+ }
1608
+ }
1609
+
1610
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1611
+ const combined = new Uint8Array(totalLength);
1612
+ let offset = 0;
1613
+ for (const chunk of chunks) {
1614
+ combined.set(chunk, offset);
1615
+ offset += chunk.length;
1616
+ }
1617
+
1618
+ return combined;
1619
+ },
1620
+ headers: email.headers,
1621
+ rawSize: email.rawSize,
1622
+ setReject: (reason: string) => {
1623
+ email.setReject(reason);
1624
+ },
1625
+ forward: (rcptTo: string, headers?: Headers) => {
1626
+ return email.forward(rcptTo, headers);
1627
+ },
1628
+ reply: (options: { from: string; to: string; raw: string }) => {
1629
+ return email.reply(
1630
+ new EmailMessage(options.from, options.to, options.raw)
1631
+ );
1632
+ },
1633
+ from: email.from,
1634
+ to: email.to
1635
+ };
1636
+
1637
+ await agent._onEmail(serialisableEmail);
1638
+ }
1639
+
1640
+ export type AgentEmail = {
1641
+ from: string;
1642
+ to: string;
1643
+ getRaw: () => Promise<Uint8Array>;
1644
+ headers: Headers;
1645
+ rawSize: number;
1646
+ setReject: (reason: string) => void;
1647
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
1648
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
1649
+ };
1650
+
1651
+ export type EmailSendOptions = {
1652
+ to: string;
1653
+ subject: string;
1654
+ body: string;
1655
+ contentType?: string;
1656
+ headers?: Record<string, string>;
1657
+ includeRoutingHeaders?: boolean;
1658
+ agentName?: string;
1659
+ agentId?: string;
1660
+ domain?: string;
1661
+ };
872
1662
 
873
1663
  /**
874
1664
  * Get or create an Agent by name
@@ -879,7 +1669,7 @@ export async function routeAgentEmail<Env>(
879
1669
  * @param options Options for Agent creation
880
1670
  * @returns Promise resolving to an Agent instance stub
881
1671
  */
882
- export function getAgentByName<Env, T extends Agent<Env>>(
1672
+ export async function getAgentByName<Env, T extends Agent<Env>>(
883
1673
  namespace: AgentNamespace<T>,
884
1674
  name: string,
885
1675
  options?: {
@@ -894,13 +1684,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
894
1684
  * A wrapper for streaming responses in callable methods
895
1685
  */
896
1686
  export class StreamingResponse {
897
- #connection: Connection;
898
- #id: string;
899
- #closed = false;
1687
+ private _connection: Connection;
1688
+ private _id: string;
1689
+ private _closed = false;
900
1690
 
901
1691
  constructor(connection: Connection, id: string) {
902
- this.#connection = connection;
903
- this.#id = id;
1692
+ this._connection = connection;
1693
+ this._id = id;
904
1694
  }
905
1695
 
906
1696
  /**
@@ -908,17 +1698,17 @@ export class StreamingResponse {
908
1698
  * @param chunk The data to send
909
1699
  */
910
1700
  send(chunk: unknown) {
911
- if (this.#closed) {
1701
+ if (this._closed) {
912
1702
  throw new Error("StreamingResponse is already closed");
913
1703
  }
914
1704
  const response: RPCResponse = {
915
- type: "rpc",
916
- id: this.#id,
917
- success: true,
918
- result: chunk,
919
1705
  done: false,
1706
+ id: this._id,
1707
+ result: chunk,
1708
+ success: true,
1709
+ type: "rpc"
920
1710
  };
921
- this.#connection.send(JSON.stringify(response));
1711
+ this._connection.send(JSON.stringify(response));
922
1712
  }
923
1713
 
924
1714
  /**
@@ -926,17 +1716,17 @@ export class StreamingResponse {
926
1716
  * @param finalChunk Optional final chunk of data to send
927
1717
  */
928
1718
  end(finalChunk?: unknown) {
929
- if (this.#closed) {
1719
+ if (this._closed) {
930
1720
  throw new Error("StreamingResponse is already closed");
931
1721
  }
932
- this.#closed = true;
1722
+ this._closed = true;
933
1723
  const response: RPCResponse = {
934
- type: "rpc",
935
- id: this.#id,
936
- success: true,
937
- result: finalChunk,
938
1724
  done: true,
1725
+ id: this._id,
1726
+ result: finalChunk,
1727
+ success: true,
1728
+ type: "rpc"
939
1729
  };
940
- this.#connection.send(JSON.stringify(response));
1730
+ this._connection.send(JSON.stringify(response));
941
1731
  }
942
1732
  }