agents 0.0.0-504a24f → 0.0.0-5320b13

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 (51) hide show
  1. package/README.md +157 -27
  2. package/dist/ai-chat-agent.d.ts +11 -7
  3. package/dist/ai-chat-agent.js +168 -47
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +61 -70
  9. package/dist/ai-react.js +144 -37
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +36 -19
  12. package/dist/ai-types.js +6 -0
  13. package/dist/chunk-AVYJQSLW.js +17 -0
  14. package/dist/chunk-AVYJQSLW.js.map +1 -0
  15. package/dist/{chunk-767EASBA.js → chunk-LL2AFX7V.js} +5 -2
  16. package/dist/chunk-LL2AFX7V.js.map +1 -0
  17. package/dist/{chunk-E3LCYPCB.js → chunk-MH46VMM4.js} +163 -20
  18. package/dist/chunk-MH46VMM4.js.map +1 -0
  19. package/dist/{chunk-NKZZ66QY.js → chunk-QEVM4BVL.js} +5 -5
  20. package/dist/chunk-QEVM4BVL.js.map +1 -0
  21. package/dist/chunk-UJVEAURM.js +150 -0
  22. package/dist/chunk-UJVEAURM.js.map +1 -0
  23. package/dist/{chunk-CGWTDCBQ.js → chunk-YDUDMOL6.js} +607 -102
  24. package/dist/chunk-YDUDMOL6.js.map +1 -0
  25. package/dist/client-CvaJdLQA.d.ts +5015 -0
  26. package/dist/client.d.ts +2 -2
  27. package/dist/client.js +2 -1
  28. package/dist/index.d.ts +172 -20
  29. package/dist/index.js +13 -4
  30. package/dist/mcp/client.d.ts +9 -781
  31. package/dist/mcp/client.js +1 -1
  32. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  33. package/dist/mcp/do-oauth-client-provider.js +1 -1
  34. package/dist/mcp/index.d.ts +68 -55
  35. package/dist/mcp/index.js +854 -608
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/observability/index.d.ts +46 -0
  38. package/dist/observability/index.js +11 -0
  39. package/dist/observability/index.js.map +1 -0
  40. package/dist/react.d.ts +9 -5
  41. package/dist/react.js +7 -5
  42. package/dist/react.js.map +1 -1
  43. package/dist/schedule.d.ts +79 -5
  44. package/dist/schedule.js +15 -2
  45. package/dist/schedule.js.map +1 -1
  46. package/package.json +25 -9
  47. package/src/index.ts +830 -140
  48. package/dist/chunk-767EASBA.js.map +0 -1
  49. package/dist/chunk-CGWTDCBQ.js.map +0 -1
  50. package/dist/chunk-E3LCYPCB.js.map +0 -1
  51. package/dist/chunk-NKZZ66QY.js.map +0 -1
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { env } from "cloudflare:workers";
1
2
  import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
4
  import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
@@ -6,23 +7,26 @@ import type {
6
7
  Prompt,
7
8
  Resource,
8
9
  ServerCapabilities,
9
- Tool,
10
+ Tool
10
11
  } from "@modelcontextprotocol/sdk/types.js";
11
12
  import { parseCronExpression } from "cron-schedule";
12
13
  import { nanoid } from "nanoid";
14
+ import { EmailMessage } from "cloudflare:email";
13
15
  import {
14
16
  type Connection,
15
17
  type ConnectionContext,
16
- getServerByName,
17
18
  type PartyServerOptions,
18
- routePartykitRequest,
19
19
  Server,
20
20
  type WSMessage,
21
+ getServerByName,
22
+ routePartykitRequest
21
23
  } from "partyserver";
22
24
  import { camelCaseToKebabCase } from "./client";
23
25
  import { MCPClientManager } from "./mcp/client";
24
26
  // import type { MCPClientConnection } from "./mcp/client-connection";
25
27
  import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
+ import { genericObservability, type Observability } from "./observability";
29
+ import { MessageType } from "./ai-types";
26
30
 
27
31
  export type { Connection, ConnectionContext, WSMessage } from "partyserver";
28
32
 
@@ -40,7 +44,7 @@ export type RPCRequest = {
40
44
  * State update message from client
41
45
  */
42
46
  export type StateUpdateMessage = {
43
- type: "cf_agent_state";
47
+ type: MessageType.CF_AGENT_STATE;
44
48
  state: unknown;
45
49
  };
46
50
 
@@ -48,7 +52,7 @@ export type StateUpdateMessage = {
48
52
  * RPC response message to client
49
53
  */
50
54
  export type RPCResponse = {
51
- type: "rpc";
55
+ type: MessageType.RPC;
52
56
  id: string;
53
57
  } & (
54
58
  | {
@@ -75,7 +79,7 @@ function isRPCRequest(msg: unknown): msg is RPCRequest {
75
79
  typeof msg === "object" &&
76
80
  msg !== null &&
77
81
  "type" in msg &&
78
- msg.type === "rpc" &&
82
+ msg.type === MessageType.RPC &&
79
83
  "id" in msg &&
80
84
  typeof msg.id === "string" &&
81
85
  "method" in msg &&
@@ -93,7 +97,7 @@ function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
93
97
  typeof msg === "object" &&
94
98
  msg !== null &&
95
99
  "type" in msg &&
96
- msg.type === "cf_agent_state" &&
100
+ msg.type === MessageType.CF_AGENT_STATE &&
97
101
  "state" in msg
98
102
  );
99
103
  }
@@ -114,7 +118,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
114
118
  * Decorator that marks a method as callable by clients
115
119
  * @param metadata Optional metadata about the callable method
116
120
  */
117
- export function unstable_callable(metadata: CallableMetadata = {}) {
121
+ export function callable(metadata: CallableMetadata = {}) {
118
122
  return function callableDecorator<This, Args extends unknown[], Return>(
119
123
  target: (this: This, ...args: Args) => Return,
120
124
  // biome-ignore lint/correctness/noUnusedFunctionParameters: later
@@ -128,6 +132,30 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
128
132
  };
129
133
  }
130
134
 
135
+ let didWarnAboutUnstableCallable = false;
136
+
137
+ /**
138
+ * Decorator that marks a method as callable by clients
139
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
140
+ * @param metadata Optional metadata about the callable method
141
+ */
142
+ export const unstable_callable = (metadata: CallableMetadata = {}) => {
143
+ if (!didWarnAboutUnstableCallable) {
144
+ didWarnAboutUnstableCallable = true;
145
+ console.warn(
146
+ "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
147
+ );
148
+ }
149
+ callable(metadata);
150
+ };
151
+
152
+ export type QueueItem<T = string> = {
153
+ id: string;
154
+ payload: T;
155
+ callback: keyof Agent<unknown>;
156
+ created_at: number;
157
+ };
158
+
131
159
  /**
132
160
  * Represents a scheduled task within an Agent
133
161
  * @template T Type of the payload data
@@ -173,7 +201,7 @@ function getNextCronTime(cron: string) {
173
201
  * MCP Server state update message from server -> Client
174
202
  */
175
203
  export type MCPServerMessage = {
176
- type: "cf_agent_mcp_servers";
204
+ type: MessageType.CF_AGENT_MCP_SERVERS;
177
205
  mcp: MCPServersState;
178
206
  };
179
207
 
@@ -217,23 +245,26 @@ const STATE_WAS_CHANGED = "cf_state_was_changed";
217
245
  const DEFAULT_STATE = {} as unknown;
218
246
 
219
247
  const agentContext = new AsyncLocalStorage<{
220
- agent: Agent<unknown>;
248
+ agent: Agent<unknown, unknown>;
221
249
  connection: Connection | undefined;
222
250
  request: Request | undefined;
251
+ email: AgentEmail | undefined;
223
252
  }>();
224
253
 
225
254
  export function getCurrentAgent<
226
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
255
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
227
256
  >(): {
228
257
  agent: T | undefined;
229
258
  connection: Connection | undefined;
230
- request: Request<unknown, CfProperties<unknown>> | undefined;
259
+ request: Request | undefined;
260
+ email: AgentEmail | undefined;
231
261
  } {
232
262
  const store = agentContext.getStore() as
233
263
  | {
234
264
  agent: T;
235
265
  connection: Connection | undefined;
236
- request: Request<unknown, CfProperties<unknown>> | undefined;
266
+ request: Request | undefined;
267
+ email: AgentEmail | undefined;
237
268
  }
238
269
  | undefined;
239
270
  if (!store) {
@@ -241,17 +272,47 @@ export function getCurrentAgent<
241
272
  agent: undefined,
242
273
  connection: undefined,
243
274
  request: undefined,
275
+ email: undefined
244
276
  };
245
277
  }
246
278
  return store;
247
279
  }
248
280
 
281
+ /**
282
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
283
+ * @param agent The agent instance
284
+ * @param method The method to wrap
285
+ * @returns A wrapped method that runs within the agent context
286
+ */
287
+
288
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
289
+ function withAgentContext<T extends (...args: any[]) => any>(
290
+ method: T
291
+ ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
292
+ return function (...args: Parameters<T>): ReturnType<T> {
293
+ const { connection, request, email, agent } = getCurrentAgent();
294
+
295
+ if (agent === this) {
296
+ // already wrapped, so we can just call the method
297
+ return method.apply(this, args);
298
+ }
299
+ // not wrapped, so we need to wrap it
300
+ return agentContext.run({ agent: this, connection, request, email }, () => {
301
+ return method.apply(this, args);
302
+ });
303
+ };
304
+ }
305
+
249
306
  /**
250
307
  * Base class for creating Agent implementations
251
308
  * @template Env Environment type containing bindings
252
309
  * @template State State type to store within the Agent
253
310
  */
254
- export class Agent<Env, State = unknown> extends Server<Env> {
311
+ export class Agent<
312
+ Env = typeof env,
313
+ State = unknown,
314
+ Props extends Record<string, unknown> = Record<string, unknown>
315
+ > extends Server<Env, Props> {
255
316
  private _state = DEFAULT_STATE as State;
256
317
 
257
318
  private _ParentClass: typeof Agent<Env, State> =
@@ -313,9 +374,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
313
374
  */
314
375
  static options = {
315
376
  /** Whether the Agent should hibernate when inactive */
316
- hibernate: true, // default to hibernate
377
+ hibernate: true // default to hibernate
317
378
  };
318
379
 
380
+ /**
381
+ * The observability implementation to use for the Agent
382
+ */
383
+ observability?: Observability = genericObservability;
384
+
319
385
  /**
320
386
  * Execute SQL queries against the Agent's database
321
387
  * @template T Type of the returned rows
@@ -345,6 +411,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
345
411
  constructor(ctx: AgentContext, env: Env) {
346
412
  super(ctx, env);
347
413
 
414
+ // Auto-wrap custom methods with agent context
415
+ this._autoWrapCustomMethods();
416
+
348
417
  this.sql`
349
418
  CREATE TABLE IF NOT EXISTS cf_agents_state (
350
419
  id TEXT PRIMARY KEY NOT NULL,
@@ -352,6 +421,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
352
421
  )
353
422
  `;
354
423
 
424
+ this.sql`
425
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
426
+ id TEXT PRIMARY KEY NOT NULL,
427
+ payload TEXT,
428
+ callback TEXT,
429
+ created_at INTEGER DEFAULT (unixepoch())
430
+ )
431
+ `;
432
+
355
433
  void this.ctx.blockConcurrencyWhile(async () => {
356
434
  return this._tryCatch(async () => {
357
435
  // Create alarms table if it doesn't exist
@@ -388,7 +466,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
388
466
  const _onRequest = this.onRequest.bind(this);
389
467
  this.onRequest = (request: Request) => {
390
468
  return agentContext.run(
391
- { agent: this, connection: undefined, request },
469
+ { agent: this, connection: undefined, request, email: undefined },
392
470
  async () => {
393
471
  if (this.mcp.isCallbackRequest(request)) {
394
472
  await this.mcp.handleCallbackRequest(request);
@@ -397,14 +475,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
397
475
  this.broadcast(
398
476
  JSON.stringify({
399
477
  mcp: this.getMcpServers(),
400
- type: "cf_agent_mcp_servers",
478
+ type: MessageType.CF_AGENT_MCP_SERVERS
401
479
  })
402
480
  );
403
481
 
404
482
  // We probably should let the user configure this response/redirect, but this is fine for now.
405
483
  return new Response("<script>window.close();</script>", {
406
484
  headers: { "content-type": "text/html" },
407
- status: 200,
485
+ status: 200
408
486
  });
409
487
  }
410
488
 
@@ -416,7 +494,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
416
494
  const _onMessage = this.onMessage.bind(this);
417
495
  this.onMessage = async (connection: Connection, message: WSMessage) => {
418
496
  return agentContext.run(
419
- { agent: this, connection, request: undefined },
497
+ { agent: this, connection, request: undefined, email: undefined },
420
498
  async () => {
421
499
  if (typeof message !== "string") {
422
500
  return this._tryCatch(() => _onMessage(connection, message));
@@ -460,12 +538,27 @@ export class Agent<Env, State = unknown> extends Server<Env> {
460
538
 
461
539
  // For regular methods, execute and send response
462
540
  const result = await methodFn.apply(this, args);
541
+
542
+ this.observability?.emit(
543
+ {
544
+ displayMessage: `RPC call to ${method}`,
545
+ id: nanoid(),
546
+ payload: {
547
+ method,
548
+ streaming: metadata?.streaming
549
+ },
550
+ timestamp: Date.now(),
551
+ type: "rpc"
552
+ },
553
+ this.ctx
554
+ );
555
+
463
556
  const response: RPCResponse = {
464
557
  done: true,
465
558
  id,
466
559
  result,
467
560
  success: true,
468
- type: "rpc",
561
+ type: MessageType.RPC
469
562
  };
470
563
  connection.send(JSON.stringify(response));
471
564
  } catch (e) {
@@ -475,7 +568,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
475
568
  e instanceof Error ? e.message : "Unknown error occurred",
476
569
  id: parsed.id,
477
570
  success: false,
478
- type: "rpc",
571
+ type: MessageType.RPC
479
572
  };
480
573
  connection.send(JSON.stringify(response));
481
574
  console.error("RPC error:", e);
@@ -493,65 +586,104 @@ export class Agent<Env, State = unknown> extends Server<Env> {
493
586
  // TODO: This is a hack to ensure the state is sent after the connection is established
494
587
  // must fix this
495
588
  return agentContext.run(
496
- { agent: this, connection, request: ctx.request },
497
- async () => {
498
- setTimeout(() => {
499
- if (this.state) {
500
- connection.send(
501
- JSON.stringify({
502
- state: this.state,
503
- type: "cf_agent_state",
504
- })
505
- );
506
- }
507
-
589
+ { agent: this, connection, request: ctx.request, email: undefined },
590
+ () => {
591
+ if (this.state) {
508
592
  connection.send(
509
593
  JSON.stringify({
510
- mcp: this.getMcpServers(),
511
- type: "cf_agent_mcp_servers",
594
+ state: this.state,
595
+ type: MessageType.CF_AGENT_STATE
512
596
  })
513
597
  );
598
+ }
514
599
 
515
- return this._tryCatch(() => _onConnect(connection, ctx));
516
- }, 20);
600
+ connection.send(
601
+ JSON.stringify({
602
+ mcp: this.getMcpServers(),
603
+ type: MessageType.CF_AGENT_MCP_SERVERS
604
+ })
605
+ );
606
+
607
+ this.observability?.emit(
608
+ {
609
+ displayMessage: "Connection established",
610
+ id: nanoid(),
611
+ payload: {
612
+ connectionId: connection.id
613
+ },
614
+ timestamp: Date.now(),
615
+ type: "connect"
616
+ },
617
+ this.ctx
618
+ );
619
+ return this._tryCatch(() => _onConnect(connection, ctx));
517
620
  }
518
621
  );
519
622
  };
520
623
 
521
624
  const _onStart = this.onStart.bind(this);
522
- this.onStart = async () => {
625
+ this.onStart = async (props?: Props) => {
523
626
  return agentContext.run(
524
- { agent: this, connection: undefined, request: undefined },
627
+ {
628
+ agent: this,
629
+ connection: undefined,
630
+ request: undefined,
631
+ email: undefined
632
+ },
525
633
  async () => {
526
- const servers = this.sql<MCPServerRow>`
634
+ await this._tryCatch(() => {
635
+ const servers = this.sql<MCPServerRow>`
527
636
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
528
637
  `;
529
638
 
530
- // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
531
- Promise.allSettled(
532
- servers.map((server) => {
533
- return this._connectToMcpServerInternal(
534
- server.name,
535
- server.server_url,
536
- server.callback_url,
537
- server.server_options
538
- ? JSON.parse(server.server_options)
539
- : undefined,
540
- {
541
- id: server.id,
542
- oauthClientId: server.client_id ?? undefined,
543
- }
544
- );
545
- })
546
- ).then((_results) => {
547
639
  this.broadcast(
548
640
  JSON.stringify({
549
- type: "cf_agent_mcp_servers",
550
641
  mcp: this.getMcpServers(),
642
+ type: MessageType.CF_AGENT_MCP_SERVERS
551
643
  })
552
644
  );
645
+
646
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
647
+ if (servers && Array.isArray(servers) && servers.length > 0) {
648
+ servers.forEach((server) => {
649
+ this._connectToMcpServerInternal(
650
+ server.name,
651
+ server.server_url,
652
+ server.callback_url,
653
+ server.server_options
654
+ ? JSON.parse(server.server_options)
655
+ : undefined,
656
+ {
657
+ id: server.id,
658
+ oauthClientId: server.client_id ?? undefined
659
+ }
660
+ )
661
+ .then(() => {
662
+ // Broadcast updated MCP servers state after each server connects
663
+ this.broadcast(
664
+ JSON.stringify({
665
+ mcp: this.getMcpServers(),
666
+ type: MessageType.CF_AGENT_MCP_SERVERS
667
+ })
668
+ );
669
+ })
670
+ .catch((error) => {
671
+ console.error(
672
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
673
+ error
674
+ );
675
+ // Still broadcast even if connection fails, so clients know about the failure
676
+ this.broadcast(
677
+ JSON.stringify({
678
+ mcp: this.getMcpServers(),
679
+ type: MessageType.CF_AGENT_MCP_SERVERS
680
+ })
681
+ );
682
+ });
683
+ });
684
+ }
685
+ return _onStart(props);
553
686
  });
554
- await this._tryCatch(() => _onStart());
555
687
  }
556
688
  );
557
689
  };
@@ -573,15 +705,25 @@ export class Agent<Env, State = unknown> extends Server<Env> {
573
705
  this.broadcast(
574
706
  JSON.stringify({
575
707
  state: state,
576
- type: "cf_agent_state",
708
+ type: MessageType.CF_AGENT_STATE
577
709
  }),
578
710
  source !== "server" ? [source.id] : []
579
711
  );
580
712
  return this._tryCatch(() => {
581
- const { connection, request } = agentContext.getStore() || {};
713
+ const { connection, request, email } = agentContext.getStore() || {};
582
714
  return agentContext.run(
583
- { agent: this, connection, request },
715
+ { agent: this, connection, request, email },
584
716
  async () => {
717
+ this.observability?.emit(
718
+ {
719
+ displayMessage: "State updated",
720
+ id: nanoid(),
721
+ payload: {},
722
+ timestamp: Date.now(),
723
+ type: "state:update"
724
+ },
725
+ this.ctx
726
+ );
585
727
  return this.onStateUpdate(state, source);
586
728
  }
587
729
  );
@@ -607,19 +749,83 @@ export class Agent<Env, State = unknown> extends Server<Env> {
607
749
  }
608
750
 
609
751
  /**
610
- * Called when the Agent receives an email
752
+ * Called when the Agent receives an email via routeAgentEmail()
753
+ * Override this method to handle incoming emails
611
754
  * @param email Email message to process
612
755
  */
613
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
614
- onEmail(email: ForwardableEmailMessage) {
756
+ async _onEmail(email: AgentEmail) {
757
+ // nb: we use this roundabout way of getting to onEmail
758
+ // because of https://github.com/cloudflare/workerd/issues/4499
615
759
  return agentContext.run(
616
- { agent: this, connection: undefined, request: undefined },
760
+ { agent: this, connection: undefined, request: undefined, email: email },
617
761
  async () => {
618
- console.error("onEmail not implemented");
762
+ if ("onEmail" in this && typeof this.onEmail === "function") {
763
+ return this._tryCatch(() =>
764
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
765
+ );
766
+ } else {
767
+ console.log("Received email from:", email.from, "to:", email.to);
768
+ console.log("Subject:", email.headers.get("subject"));
769
+ console.log(
770
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
771
+ );
772
+ }
619
773
  }
620
774
  );
621
775
  }
622
776
 
777
+ /**
778
+ * Reply to an email
779
+ * @param email The email to reply to
780
+ * @param options Options for the reply
781
+ * @returns void
782
+ */
783
+ async replyToEmail(
784
+ email: AgentEmail,
785
+ options: {
786
+ fromName: string;
787
+ subject?: string | undefined;
788
+ body: string;
789
+ contentType?: string;
790
+ headers?: Record<string, string>;
791
+ }
792
+ ): Promise<void> {
793
+ return this._tryCatch(async () => {
794
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
795
+ const agentId = this.name;
796
+
797
+ const { createMimeMessage } = await import("mimetext");
798
+ const msg = createMimeMessage();
799
+ msg.setSender({ addr: email.to, name: options.fromName });
800
+ msg.setRecipient(email.from);
801
+ msg.setSubject(
802
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
803
+ );
804
+ msg.addMessage({
805
+ contentType: options.contentType || "text/plain",
806
+ data: options.body
807
+ });
808
+
809
+ const domain = email.from.split("@")[1];
810
+ const messageId = `<${agentId}@${domain}>`;
811
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
812
+ msg.setHeader("Message-ID", messageId);
813
+ msg.setHeader("X-Agent-Name", agentName);
814
+ msg.setHeader("X-Agent-ID", agentId);
815
+
816
+ if (options.headers) {
817
+ for (const [key, value] of Object.entries(options.headers)) {
818
+ msg.setHeader(key, value);
819
+ }
820
+ }
821
+ await email.reply({
822
+ from: email.to,
823
+ raw: msg.asRaw(),
824
+ to: email.from
825
+ });
826
+ });
827
+ }
828
+
623
829
  private async _tryCatch<T>(fn: () => T | Promise<T>) {
624
830
  try {
625
831
  return await fn();
@@ -628,6 +834,68 @@ export class Agent<Env, State = unknown> extends Server<Env> {
628
834
  }
629
835
  }
630
836
 
837
+ /**
838
+ * Automatically wrap custom methods with agent context
839
+ * This ensures getCurrentAgent() works in all custom methods without decorators
840
+ */
841
+ private _autoWrapCustomMethods() {
842
+ // Collect all methods from base prototypes (Agent and Server)
843
+ const basePrototypes = [Agent.prototype, Server.prototype];
844
+ const baseMethods = new Set<string>();
845
+ for (const baseProto of basePrototypes) {
846
+ let proto = baseProto;
847
+ while (proto && proto !== Object.prototype) {
848
+ const methodNames = Object.getOwnPropertyNames(proto);
849
+ for (const methodName of methodNames) {
850
+ baseMethods.add(methodName);
851
+ }
852
+ proto = Object.getPrototypeOf(proto);
853
+ }
854
+ }
855
+ // Get all methods from the current instance's prototype chain
856
+ let proto = Object.getPrototypeOf(this);
857
+ let depth = 0;
858
+ while (proto && proto !== Object.prototype && depth < 10) {
859
+ const methodNames = Object.getOwnPropertyNames(proto);
860
+ for (const methodName of methodNames) {
861
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
862
+
863
+ // Skip if it's a private method, a base method, a getter, or not a function,
864
+ if (
865
+ baseMethods.has(methodName) ||
866
+ methodName.startsWith("_") ||
867
+ !descriptor ||
868
+ !!descriptor.get ||
869
+ typeof descriptor.value !== "function"
870
+ ) {
871
+ continue;
872
+ }
873
+
874
+ // Now, methodName is confirmed to be a custom method/function
875
+ // Wrap the custom method with context
876
+ const wrappedFunction = withAgentContext(
877
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
878
+ this[methodName as keyof this] as (...args: any[]) => any
879
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
880
+ ) as any;
881
+
882
+ // if the method is callable, copy the metadata from the original method
883
+ if (this._isCallable(methodName)) {
884
+ callableMetadata.set(
885
+ wrappedFunction,
886
+ callableMetadata.get(this[methodName as keyof this] as Function)!
887
+ );
888
+ }
889
+
890
+ // set the wrapped function on the prototype
891
+ this.constructor.prototype[methodName as keyof this] = wrappedFunction;
892
+ }
893
+
894
+ proto = Object.getPrototypeOf(proto);
895
+ depth++;
896
+ }
897
+ }
898
+
631
899
  override onError(
632
900
  connection: Connection,
633
901
  error: unknown
@@ -662,6 +930,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
662
930
  throw new Error("Not implemented");
663
931
  }
664
932
 
933
+ /**
934
+ * Queue a task to be executed in the future
935
+ * @param payload Payload to pass to the callback
936
+ * @param callback Name of the method to call
937
+ * @returns The ID of the queued task
938
+ */
939
+ async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
940
+ const id = nanoid(9);
941
+ if (typeof callback !== "string") {
942
+ throw new Error("Callback must be a string");
943
+ }
944
+
945
+ if (typeof this[callback] !== "function") {
946
+ throw new Error(`this.${callback} is not a function`);
947
+ }
948
+
949
+ this.sql`
950
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
951
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
952
+ `;
953
+
954
+ void this._flushQueue().catch((e) => {
955
+ console.error("Error flushing queue:", e);
956
+ });
957
+
958
+ return id;
959
+ }
960
+
961
+ private _flushingQueue = false;
962
+
963
+ private async _flushQueue() {
964
+ if (this._flushingQueue) {
965
+ return;
966
+ }
967
+ this._flushingQueue = true;
968
+ while (true) {
969
+ const result = this.sql<QueueItem<string>>`
970
+ SELECT * FROM cf_agents_queues
971
+ ORDER BY created_at ASC
972
+ `;
973
+
974
+ if (!result || result.length === 0) {
975
+ break;
976
+ }
977
+
978
+ for (const row of result || []) {
979
+ const callback = this[row.callback as keyof Agent<Env>];
980
+ if (!callback) {
981
+ console.error(`callback ${row.callback} not found`);
982
+ continue;
983
+ }
984
+ const { connection, request, email } = agentContext.getStore() || {};
985
+ await agentContext.run(
986
+ {
987
+ agent: this,
988
+ connection,
989
+ request,
990
+ email
991
+ },
992
+ async () => {
993
+ // TODO: add retries and backoff
994
+ await (
995
+ callback as (
996
+ payload: unknown,
997
+ queueItem: QueueItem<string>
998
+ ) => Promise<void>
999
+ ).bind(this)(JSON.parse(row.payload as string), row);
1000
+ await this.dequeue(row.id);
1001
+ }
1002
+ );
1003
+ }
1004
+ }
1005
+ this._flushingQueue = false;
1006
+ }
1007
+
1008
+ /**
1009
+ * Dequeue a task by ID
1010
+ * @param id ID of the task to dequeue
1011
+ */
1012
+ async dequeue(id: string) {
1013
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1014
+ }
1015
+
1016
+ /**
1017
+ * Dequeue all tasks
1018
+ */
1019
+ async dequeueAll() {
1020
+ this.sql`DELETE FROM cf_agents_queues`;
1021
+ }
1022
+
1023
+ /**
1024
+ * Dequeue all tasks by callback
1025
+ * @param callback Name of the callback to dequeue
1026
+ */
1027
+ async dequeueAllByCallback(callback: string) {
1028
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1029
+ }
1030
+
1031
+ /**
1032
+ * Get a queued task by ID
1033
+ * @param id ID of the task to get
1034
+ * @returns The task or undefined if not found
1035
+ */
1036
+ async getQueue(id: string): Promise<QueueItem<string> | undefined> {
1037
+ const result = this.sql<QueueItem<string>>`
1038
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1039
+ `;
1040
+ return result
1041
+ ? { ...result[0], payload: JSON.parse(result[0].payload) }
1042
+ : undefined;
1043
+ }
1044
+
1045
+ /**
1046
+ * Get all queues by key and value
1047
+ * @param key Key to filter by
1048
+ * @param value Value to filter by
1049
+ * @returns Array of matching QueueItem objects
1050
+ */
1051
+ async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1052
+ const result = this.sql<QueueItem<string>>`
1053
+ SELECT * FROM cf_agents_queues
1054
+ `;
1055
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
1056
+ }
1057
+
665
1058
  /**
666
1059
  * Schedule a task to be executed in the future
667
1060
  * @template T Type of the payload data
@@ -677,6 +1070,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
677
1070
  ): Promise<Schedule<T>> {
678
1071
  const id = nanoid(9);
679
1072
 
1073
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
1074
+ this.observability?.emit(
1075
+ {
1076
+ displayMessage: `Schedule ${schedule.id} created`,
1077
+ id: nanoid(),
1078
+ payload: {
1079
+ callback: callback as string,
1080
+ id: id
1081
+ },
1082
+ timestamp: Date.now(),
1083
+ type: "schedule:create"
1084
+ },
1085
+ this.ctx
1086
+ );
1087
+
680
1088
  if (typeof callback !== "string") {
681
1089
  throw new Error("Callback must be a string");
682
1090
  }
@@ -696,13 +1104,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
696
1104
 
697
1105
  await this._scheduleNextAlarm();
698
1106
 
699
- return {
1107
+ const schedule: Schedule<T> = {
700
1108
  callback: callback,
701
1109
  id,
702
1110
  payload: payload as T,
703
1111
  time: timestamp,
704
- type: "scheduled",
1112
+ type: "scheduled"
705
1113
  };
1114
+
1115
+ emitScheduleCreate(schedule);
1116
+
1117
+ return schedule;
706
1118
  }
707
1119
  if (typeof when === "number") {
708
1120
  const time = new Date(Date.now() + when * 1000);
@@ -717,14 +1129,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
717
1129
 
718
1130
  await this._scheduleNextAlarm();
719
1131
 
720
- return {
1132
+ const schedule: Schedule<T> = {
721
1133
  callback: callback,
722
1134
  delayInSeconds: when,
723
1135
  id,
724
1136
  payload: payload as T,
725
1137
  time: timestamp,
726
- type: "delayed",
1138
+ type: "delayed"
727
1139
  };
1140
+
1141
+ emitScheduleCreate(schedule);
1142
+
1143
+ return schedule;
728
1144
  }
729
1145
  if (typeof when === "string") {
730
1146
  const nextExecutionTime = getNextCronTime(when);
@@ -739,14 +1155,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
739
1155
 
740
1156
  await this._scheduleNextAlarm();
741
1157
 
742
- return {
1158
+ const schedule: Schedule<T> = {
743
1159
  callback: callback,
744
1160
  cron: when,
745
1161
  id,
746
1162
  payload: payload as T,
747
1163
  time: timestamp,
748
- type: "cron",
1164
+ type: "cron"
749
1165
  };
1166
+
1167
+ emitScheduleCreate(schedule);
1168
+
1169
+ return schedule;
750
1170
  }
751
1171
  throw new Error("Invalid schedule type");
752
1172
  }
@@ -810,7 +1230,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
810
1230
  .toArray()
811
1231
  .map((row) => ({
812
1232
  ...row,
813
- payload: JSON.parse(row.payload as string) as T,
1233
+ payload: JSON.parse(row.payload as string) as T
814
1234
  })) as Schedule<T>[];
815
1235
 
816
1236
  return result;
@@ -822,6 +1242,22 @@ export class Agent<Env, State = unknown> extends Server<Env> {
822
1242
  * @returns true if the task was cancelled, false otherwise
823
1243
  */
824
1244
  async cancelSchedule(id: string): Promise<boolean> {
1245
+ const schedule = await this.getSchedule(id);
1246
+ if (schedule) {
1247
+ this.observability?.emit(
1248
+ {
1249
+ displayMessage: `Schedule ${id} cancelled`,
1250
+ id: nanoid(),
1251
+ payload: {
1252
+ callback: schedule.callback,
1253
+ id: schedule.id
1254
+ },
1255
+ timestamp: Date.now(),
1256
+ type: "schedule:cancel"
1257
+ },
1258
+ this.ctx
1259
+ );
1260
+ }
825
1261
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
826
1262
 
827
1263
  await this._scheduleNextAlarm();
@@ -831,9 +1267,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
831
1267
  private async _scheduleNextAlarm() {
832
1268
  // Find the next schedule that needs to be executed
833
1269
  const result = this.sql`
834
- SELECT time FROM cf_agents_schedules
1270
+ SELECT time FROM cf_agents_schedules
835
1271
  WHERE time > ${Math.floor(Date.now() / 1000)}
836
- ORDER BY time ASC
1272
+ ORDER BY time ASC
837
1273
  LIMIT 1
838
1274
  `;
839
1275
  if (!result) return;
@@ -860,40 +1296,61 @@ export class Agent<Env, State = unknown> extends Server<Env> {
860
1296
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
861
1297
  `;
862
1298
 
863
- for (const row of result || []) {
864
- const callback = this[row.callback as keyof Agent<Env>];
865
- if (!callback) {
866
- console.error(`callback ${row.callback} not found`);
867
- continue;
868
- }
869
- await agentContext.run(
870
- { agent: this, connection: undefined, request: undefined },
871
- async () => {
872
- try {
873
- await (
874
- callback as (
875
- payload: unknown,
876
- schedule: Schedule<unknown>
877
- ) => Promise<void>
878
- ).bind(this)(JSON.parse(row.payload as string), row);
879
- } catch (e) {
880
- console.error(`error executing callback "${row.callback}"`, e);
881
- }
1299
+ if (result && Array.isArray(result)) {
1300
+ for (const row of result) {
1301
+ const callback = this[row.callback as keyof Agent<Env>];
1302
+ if (!callback) {
1303
+ console.error(`callback ${row.callback} not found`);
1304
+ continue;
882
1305
  }
883
- );
884
- if (row.type === "cron") {
885
- // Update next execution time for cron schedules
886
- const nextExecutionTime = getNextCronTime(row.cron);
887
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1306
+ await agentContext.run(
1307
+ {
1308
+ agent: this,
1309
+ connection: undefined,
1310
+ request: undefined,
1311
+ email: undefined
1312
+ },
1313
+ async () => {
1314
+ try {
1315
+ this.observability?.emit(
1316
+ {
1317
+ displayMessage: `Schedule ${row.id} executed`,
1318
+ id: nanoid(),
1319
+ payload: {
1320
+ callback: row.callback,
1321
+ id: row.id
1322
+ },
1323
+ timestamp: Date.now(),
1324
+ type: "schedule:execute"
1325
+ },
1326
+ this.ctx
1327
+ );
888
1328
 
889
- this.sql`
1329
+ await (
1330
+ callback as (
1331
+ payload: unknown,
1332
+ schedule: Schedule<unknown>
1333
+ ) => Promise<void>
1334
+ ).bind(this)(JSON.parse(row.payload as string), row);
1335
+ } catch (e) {
1336
+ console.error(`error executing callback "${row.callback}"`, e);
1337
+ }
1338
+ }
1339
+ );
1340
+ if (row.type === "cron") {
1341
+ // Update next execution time for cron schedules
1342
+ const nextExecutionTime = getNextCronTime(row.cron);
1343
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1344
+
1345
+ this.sql`
890
1346
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
891
1347
  `;
892
- } else {
893
- // Delete one-time schedules after execution
894
- this.sql`
1348
+ } else {
1349
+ // Delete one-time schedules after execution
1350
+ this.sql`
895
1351
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
896
1352
  `;
1353
+ }
897
1354
  }
898
1355
  }
899
1356
 
@@ -909,11 +1366,23 @@ export class Agent<Env, State = unknown> extends Server<Env> {
909
1366
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
910
1367
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
911
1368
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1369
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
912
1370
 
913
1371
  // delete all alarms
914
1372
  await this.ctx.storage.deleteAlarm();
915
1373
  await this.ctx.storage.deleteAll();
916
1374
  this.ctx.abort("destroyed"); // enforce that the agent is evicted
1375
+
1376
+ this.observability?.emit(
1377
+ {
1378
+ displayMessage: "Agent destroyed",
1379
+ id: nanoid(),
1380
+ payload: {},
1381
+ timestamp: Date.now(),
1382
+ type: "destroy"
1383
+ },
1384
+ this.ctx
1385
+ );
917
1386
  }
918
1387
 
919
1388
  /**
@@ -970,7 +1439,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
970
1439
  this.broadcast(
971
1440
  JSON.stringify({
972
1441
  mcp: this.getMcpServers(),
973
- type: "cf_agent_mcp_servers",
1442
+ type: MessageType.CF_AGENT_MCP_SERVERS
974
1443
  })
975
1444
  );
976
1445
 
@@ -1026,12 +1495,12 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1026
1495
  fetch: (url, init) =>
1027
1496
  fetch(url, {
1028
1497
  ...init,
1029
- headers: options?.transport?.headers,
1030
- }),
1498
+ headers: options?.transport?.headers
1499
+ })
1031
1500
  },
1032
1501
  requestInit: {
1033
- headers: options?.transport?.headers,
1034
- },
1502
+ headers: options?.transport?.headers
1503
+ }
1035
1504
  };
1036
1505
  }
1037
1506
 
@@ -1040,14 +1509,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1040
1509
  reconnect,
1041
1510
  transport: {
1042
1511
  ...headerTransportOpts,
1043
- authProvider,
1044
- },
1512
+ authProvider
1513
+ }
1045
1514
  });
1046
1515
 
1047
1516
  return {
1048
1517
  authUrl,
1049
1518
  clientId,
1050
- id,
1519
+ id
1051
1520
  };
1052
1521
  }
1053
1522
 
@@ -1059,7 +1528,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1059
1528
  this.broadcast(
1060
1529
  JSON.stringify({
1061
1530
  mcp: this.getMcpServers(),
1062
- type: "cf_agent_mcp_servers",
1531
+ type: MessageType.CF_AGENT_MCP_SERVERS
1063
1532
  })
1064
1533
  );
1065
1534
  }
@@ -1069,24 +1538,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1069
1538
  prompts: this.mcp.listPrompts(),
1070
1539
  resources: this.mcp.listResources(),
1071
1540
  servers: {},
1072
- tools: this.mcp.listTools(),
1541
+ tools: this.mcp.listTools()
1073
1542
  };
1074
1543
 
1075
1544
  const servers = this.sql<MCPServerRow>`
1076
1545
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1077
1546
  `;
1078
1547
 
1079
- for (const server of servers) {
1080
- const serverConn = this.mcp.mcpConnections[server.id];
1081
- mcpState.servers[server.id] = {
1082
- auth_url: server.auth_url,
1083
- capabilities: serverConn?.serverCapabilities ?? null,
1084
- instructions: serverConn?.instructions ?? null,
1085
- name: server.name,
1086
- server_url: server.server_url,
1087
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1088
- state: serverConn?.connectionState ?? "authenticating",
1089
- };
1548
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1549
+ for (const server of servers) {
1550
+ const serverConn = this.mcp.mcpConnections[server.id];
1551
+ mcpState.servers[server.id] = {
1552
+ auth_url: server.auth_url,
1553
+ capabilities: serverConn?.serverCapabilities ?? null,
1554
+ instructions: serverConn?.instructions ?? null,
1555
+ name: server.name,
1556
+ server_url: server.server_url,
1557
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1558
+ state: serverConn?.connectionState ?? "authenticating"
1559
+ };
1560
+ }
1090
1561
  }
1091
1562
 
1092
1563
  return mcpState;
@@ -1133,14 +1604,14 @@ export async function routeAgentRequest<Env>(
1133
1604
  "Access-Control-Allow-Credentials": "true",
1134
1605
  "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1135
1606
  "Access-Control-Allow-Origin": "*",
1136
- "Access-Control-Max-Age": "86400",
1607
+ "Access-Control-Max-Age": "86400"
1137
1608
  }
1138
1609
  : options?.cors;
1139
1610
 
1140
1611
  if (request.method === "OPTIONS") {
1141
1612
  if (corsHeaders) {
1142
1613
  return new Response(null, {
1143
- headers: corsHeaders,
1614
+ headers: corsHeaders
1144
1615
  });
1145
1616
  }
1146
1617
  console.warn(
@@ -1153,7 +1624,7 @@ export async function routeAgentRequest<Env>(
1153
1624
  env as Record<string, unknown>,
1154
1625
  {
1155
1626
  prefix: "agents",
1156
- ...(options as PartyServerOptions<Record<string, unknown>>),
1627
+ ...(options as PartyServerOptions<Record<string, unknown>>)
1157
1628
  }
1158
1629
  );
1159
1630
 
@@ -1166,24 +1637,238 @@ export async function routeAgentRequest<Env>(
1166
1637
  response = new Response(response.body, {
1167
1638
  headers: {
1168
1639
  ...response.headers,
1169
- ...corsHeaders,
1170
- },
1640
+ ...corsHeaders
1641
+ }
1171
1642
  });
1172
1643
  }
1173
1644
  return response;
1174
1645
  }
1175
1646
 
1647
+ export type EmailResolver<Env> = (
1648
+ email: ForwardableEmailMessage,
1649
+ env: Env
1650
+ ) => Promise<{
1651
+ agentName: string;
1652
+ agentId: string;
1653
+ } | null>;
1654
+
1655
+ /**
1656
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1657
+ * @returns A function that resolves the agent to route the email to
1658
+ */
1659
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1660
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1661
+ const messageId = email.headers.get("message-id");
1662
+ if (messageId) {
1663
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1664
+ if (messageIdMatch) {
1665
+ const [, agentId, domain] = messageIdMatch;
1666
+ const agentName = domain.split(".")[0];
1667
+ return { agentName, agentId };
1668
+ }
1669
+ }
1670
+
1671
+ const references = email.headers.get("references");
1672
+ if (references) {
1673
+ const referencesMatch = references.match(
1674
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1675
+ );
1676
+ if (referencesMatch) {
1677
+ const [, base64Id, domain] = referencesMatch;
1678
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1679
+ const agentName = domain.split(".")[0];
1680
+ return { agentName, agentId };
1681
+ }
1682
+ }
1683
+
1684
+ const agentName = email.headers.get("x-agent-name");
1685
+ const agentId = email.headers.get("x-agent-id");
1686
+ if (agentName && agentId) {
1687
+ return { agentName, agentId };
1688
+ }
1689
+
1690
+ return null;
1691
+ };
1692
+ }
1693
+
1694
+ /**
1695
+ * Create a resolver that uses the email address to determine the agent to route the email to
1696
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1697
+ * @returns A function that resolves the agent to route the email to
1698
+ */
1699
+ export function createAddressBasedEmailResolver<Env>(
1700
+ defaultAgentName: string
1701
+ ): EmailResolver<Env> {
1702
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1703
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1704
+ if (!emailMatch) {
1705
+ return null;
1706
+ }
1707
+
1708
+ const [, localPart, subAddress] = emailMatch;
1709
+
1710
+ if (subAddress) {
1711
+ return {
1712
+ agentName: localPart,
1713
+ agentId: subAddress
1714
+ };
1715
+ }
1716
+
1717
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1718
+ // Common for catch-all email routing to a single EmailAgent namespace
1719
+ return {
1720
+ agentName: defaultAgentName,
1721
+ agentId: localPart
1722
+ };
1723
+ };
1724
+ }
1725
+
1726
+ /**
1727
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1728
+ * @param agentName The name of the agent to route the email to
1729
+ * @param agentId The id of the agent to route the email to
1730
+ * @returns A function that resolves the agent to route the email to
1731
+ */
1732
+ export function createCatchAllEmailResolver<Env>(
1733
+ agentName: string,
1734
+ agentId: string
1735
+ ): EmailResolver<Env> {
1736
+ return async () => ({ agentName, agentId });
1737
+ }
1738
+
1739
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1740
+ resolver: EmailResolver<Env>;
1741
+ };
1742
+
1743
+ // Cache the agent namespace map for email routing
1744
+ // This maps both kebab-case and original names to namespaces
1745
+ const agentMapCache = new WeakMap<
1746
+ Record<string, unknown>,
1747
+ Record<string, unknown>
1748
+ >();
1749
+
1176
1750
  /**
1177
1751
  * Route an email to the appropriate Agent
1178
- * @param email Email message to route
1179
- * @param env Environment containing Agent bindings
1180
- * @param options Routing options
1752
+ * @param email The email to route
1753
+ * @param env The environment containing the Agent bindings
1754
+ * @param options The options for routing the email
1755
+ * @returns A promise that resolves when the email has been routed
1181
1756
  */
1182
1757
  export async function routeAgentEmail<Env>(
1183
- _email: ForwardableEmailMessage,
1184
- _env: Env,
1185
- _options?: AgentOptions<Env>
1186
- ): Promise<void> {}
1758
+ email: ForwardableEmailMessage,
1759
+ env: Env,
1760
+ options: EmailRoutingOptions<Env>
1761
+ ): Promise<void> {
1762
+ const routingInfo = await options.resolver(email, env);
1763
+
1764
+ if (!routingInfo) {
1765
+ console.warn("No routing information found for email, dropping message");
1766
+ return;
1767
+ }
1768
+
1769
+ // Build a map that includes both original names and kebab-case versions
1770
+ if (!agentMapCache.has(env as Record<string, unknown>)) {
1771
+ const map: Record<string, unknown> = {};
1772
+ for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1773
+ if (
1774
+ value &&
1775
+ typeof value === "object" &&
1776
+ "idFromName" in value &&
1777
+ typeof value.idFromName === "function"
1778
+ ) {
1779
+ // Add both the original name and kebab-case version
1780
+ map[key] = value;
1781
+ map[camelCaseToKebabCase(key)] = value;
1782
+ }
1783
+ }
1784
+ agentMapCache.set(env as Record<string, unknown>, map);
1785
+ }
1786
+
1787
+ const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
1788
+ const namespace = agentMap[routingInfo.agentName];
1789
+
1790
+ if (!namespace) {
1791
+ // Provide helpful error message listing available agents
1792
+ const availableAgents = Object.keys(agentMap)
1793
+ .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
1794
+ .join(", ");
1795
+ throw new Error(
1796
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1797
+ );
1798
+ }
1799
+
1800
+ const agent = await getAgentByName(
1801
+ namespace as unknown as AgentNamespace<Agent<Env>>,
1802
+ routingInfo.agentId
1803
+ );
1804
+
1805
+ // let's make a serialisable version of the email
1806
+ const serialisableEmail: AgentEmail = {
1807
+ getRaw: async () => {
1808
+ const reader = email.raw.getReader();
1809
+ const chunks: Uint8Array[] = [];
1810
+
1811
+ let done = false;
1812
+ while (!done) {
1813
+ const { value, done: readerDone } = await reader.read();
1814
+ done = readerDone;
1815
+ if (value) {
1816
+ chunks.push(value);
1817
+ }
1818
+ }
1819
+
1820
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1821
+ const combined = new Uint8Array(totalLength);
1822
+ let offset = 0;
1823
+ for (const chunk of chunks) {
1824
+ combined.set(chunk, offset);
1825
+ offset += chunk.length;
1826
+ }
1827
+
1828
+ return combined;
1829
+ },
1830
+ headers: email.headers,
1831
+ rawSize: email.rawSize,
1832
+ setReject: (reason: string) => {
1833
+ email.setReject(reason);
1834
+ },
1835
+ forward: (rcptTo: string, headers?: Headers) => {
1836
+ return email.forward(rcptTo, headers);
1837
+ },
1838
+ reply: (options: { from: string; to: string; raw: string }) => {
1839
+ return email.reply(
1840
+ new EmailMessage(options.from, options.to, options.raw)
1841
+ );
1842
+ },
1843
+ from: email.from,
1844
+ to: email.to
1845
+ };
1846
+
1847
+ await agent._onEmail(serialisableEmail);
1848
+ }
1849
+
1850
+ export type AgentEmail = {
1851
+ from: string;
1852
+ to: string;
1853
+ getRaw: () => Promise<Uint8Array>;
1854
+ headers: Headers;
1855
+ rawSize: number;
1856
+ setReject: (reason: string) => void;
1857
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
1858
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
1859
+ };
1860
+
1861
+ export type EmailSendOptions = {
1862
+ to: string;
1863
+ subject: string;
1864
+ body: string;
1865
+ contentType?: string;
1866
+ headers?: Record<string, string>;
1867
+ includeRoutingHeaders?: boolean;
1868
+ agentName?: string;
1869
+ agentId?: string;
1870
+ domain?: string;
1871
+ };
1187
1872
 
1188
1873
  /**
1189
1874
  * Get or create an Agent by name
@@ -1194,12 +1879,17 @@ export async function routeAgentEmail<Env>(
1194
1879
  * @param options Options for Agent creation
1195
1880
  * @returns Promise resolving to an Agent instance stub
1196
1881
  */
1197
- export async function getAgentByName<Env, T extends Agent<Env>>(
1882
+ export async function getAgentByName<
1883
+ Env,
1884
+ T extends Agent<Env>,
1885
+ Props extends Record<string, unknown> = Record<string, unknown>
1886
+ >(
1198
1887
  namespace: AgentNamespace<T>,
1199
1888
  name: string,
1200
1889
  options?: {
1201
1890
  jurisdiction?: DurableObjectJurisdiction;
1202
1891
  locationHint?: DurableObjectLocationHint;
1892
+ props?: Props;
1203
1893
  }
1204
1894
  ) {
1205
1895
  return getServerByName<Env, T>(namespace, name, options);
@@ -1231,7 +1921,7 @@ export class StreamingResponse {
1231
1921
  id: this._id,
1232
1922
  result: chunk,
1233
1923
  success: true,
1234
- type: "rpc",
1924
+ type: MessageType.RPC
1235
1925
  };
1236
1926
  this._connection.send(JSON.stringify(response));
1237
1927
  }
@@ -1250,7 +1940,7 @@ export class StreamingResponse {
1250
1940
  id: this._id,
1251
1941
  result: finalChunk,
1252
1942
  success: true,
1253
- type: "rpc",
1943
+ type: MessageType.RPC
1254
1944
  };
1255
1945
  this._connection.send(JSON.stringify(response));
1256
1946
  }