agents 0.0.0-54e1986 → 0.0.0-579b228

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 (44) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +5 -4
  3. package/dist/ai-chat-agent.js +64 -26
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +10 -9
  6. package/dist/ai-react.js +27 -27
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/{chunk-RIYR6FR6.js → chunk-CKHRUXM5.js} +623 -130
  9. package/dist/chunk-CKHRUXM5.js.map +1 -0
  10. package/dist/{chunk-QSGN3REV.js → chunk-KUH345EY.js} +8 -15
  11. package/dist/chunk-KUH345EY.js.map +1 -0
  12. package/dist/{chunk-Y67CHZBI.js → chunk-MW5BQ2FW.js} +23 -18
  13. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  14. package/dist/{chunk-BZXOAZUX.js → chunk-PVQZBKN7.js} +5 -5
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +8 -2
  17. package/dist/client.js +1 -1
  18. package/dist/index-BIJvkfYt.d.ts +614 -0
  19. package/dist/index.d.ts +33 -394
  20. package/dist/index.js +10 -4
  21. package/dist/mcp/client.d.ts +281 -9
  22. package/dist/mcp/client.js +1 -1
  23. package/dist/mcp/do-oauth-client-provider.js +1 -1
  24. package/dist/mcp/index.d.ts +9 -9
  25. package/dist/mcp/index.js +55 -51
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/observability/index.d.ts +12 -0
  28. package/dist/observability/index.js +10 -0
  29. package/dist/observability/index.js.map +1 -0
  30. package/dist/react.d.ts +76 -10
  31. package/dist/react.js +16 -6
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.d.ts +6 -6
  34. package/dist/schedule.js +4 -4
  35. package/dist/schedule.js.map +1 -1
  36. package/dist/serializable.d.ts +32 -0
  37. package/dist/serializable.js +1 -0
  38. package/dist/serializable.js.map +1 -0
  39. package/package.json +76 -71
  40. package/src/index.ts +828 -177
  41. package/dist/chunk-BZXOAZUX.js.map +0 -1
  42. package/dist/chunk-QSGN3REV.js.map +0 -1
  43. package/dist/chunk-RIYR6FR6.js.map +0 -1
  44. package/dist/chunk-Y67CHZBI.js.map +0 -1
package/src/index.ts CHANGED
@@ -1,34 +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";
15
- import { MCPClientManager } from "./mcp/client";
16
- import {
17
- DurableObjectOAuthClientProvider,
18
- type AgentsOAuthProvider,
19
- } from "./mcp/do-oauth-client-provider";
20
- import type {
21
- Tool,
22
- Resource,
23
- Prompt,
24
- } from "@modelcontextprotocol/sdk/types.js";
25
-
26
- import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
27
- import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
28
-
29
23
  import { camelCaseToKebabCase } from "./client";
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";
30
28
 
31
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
29
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
32
30
 
33
31
  /**
34
32
  * RPC request message from client
@@ -112,7 +110,6 @@ export type CallableMetadata = {
112
110
  streaming?: boolean;
113
111
  };
114
112
 
115
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
116
113
  const callableMetadata = new Map<Function, CallableMetadata>();
117
114
 
118
115
  /**
@@ -122,6 +119,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
122
119
  export function unstable_callable(metadata: CallableMetadata = {}) {
123
120
  return function callableDecorator<This, Args extends unknown[], Return>(
124
121
  target: (this: This, ...args: Args) => Return,
122
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
125
123
  context: ClassMethodDecoratorContext
126
124
  ) {
127
125
  if (!callableMetadata.has(target)) {
@@ -132,6 +130,13 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
132
130
  };
133
131
  }
134
132
 
133
+ export type QueueItem<T = string> = {
134
+ id: string;
135
+ payload: T;
136
+ callback: keyof Agent<unknown>;
137
+ created_at: number;
138
+ };
139
+
135
140
  /**
136
141
  * Represents a scheduled task within an Agent
137
142
  * @template T Type of the payload data
@@ -194,7 +199,12 @@ export type MCPServer = {
194
199
  name: string;
195
200
  server_url: string;
196
201
  auth_url: string | null;
202
+ // This state is specifically about the temporary process of getting a token (if needed).
203
+ // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
204
+ // to communicate a change to a non-ready state.
197
205
  state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
206
+ instructions: string | null;
207
+ capabilities: ServerCapabilities | null;
198
208
  };
199
209
 
200
210
  /**
@@ -216,23 +226,26 @@ const STATE_WAS_CHANGED = "cf_state_was_changed";
216
226
  const DEFAULT_STATE = {} as unknown;
217
227
 
218
228
  const agentContext = new AsyncLocalStorage<{
219
- agent: Agent<unknown>;
229
+ agent: Agent<unknown, unknown>;
220
230
  connection: Connection | undefined;
221
231
  request: Request | undefined;
232
+ email: AgentEmail | undefined;
222
233
  }>();
223
234
 
224
235
  export function getCurrentAgent<
225
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
236
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
226
237
  >(): {
227
238
  agent: T | undefined;
228
239
  connection: Connection | undefined;
229
- request: Request<unknown, CfProperties<unknown>> | undefined;
240
+ request: Request | undefined;
241
+ email: AgentEmail | undefined;
230
242
  } {
231
243
  const store = agentContext.getStore() as
232
244
  | {
233
245
  agent: T;
234
246
  connection: Connection | undefined;
235
- request: Request<unknown, CfProperties<unknown>> | undefined;
247
+ request: Request | undefined;
248
+ email: AgentEmail | undefined;
236
249
  }
237
250
  | undefined;
238
251
  if (!store) {
@@ -240,11 +253,31 @@ export function getCurrentAgent<
240
253
  agent: undefined,
241
254
  connection: undefined,
242
255
  request: undefined,
256
+ email: undefined
243
257
  };
244
258
  }
245
259
  return store;
246
260
  }
247
261
 
262
+ /**
263
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
264
+ * @param agent The agent instance
265
+ * @param method The method to wrap
266
+ * @returns A wrapped method that runs within the agent context
267
+ */
268
+
269
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
270
+ function withAgentContext<T extends (...args: any[]) => any>(
271
+ method: T
272
+ ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
273
+ return function (...args: Parameters<T>): ReturnType<T> {
274
+ const { connection, request, email } = getCurrentAgent();
275
+ return agentContext.run({ agent: this, connection, request, email }, () => {
276
+ return method.apply(this, args);
277
+ });
278
+ };
279
+ }
280
+
248
281
  /**
249
282
  * Base class for creating Agent implementations
250
283
  * @template Env Environment type containing bindings
@@ -312,9 +345,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
312
345
  */
313
346
  static options = {
314
347
  /** Whether the Agent should hibernate when inactive */
315
- hibernate: true, // default to hibernate
348
+ hibernate: true // default to hibernate
316
349
  };
317
350
 
351
+ /**
352
+ * The observability implementation to use for the Agent
353
+ */
354
+ observability?: Observability = genericObservability;
355
+
318
356
  /**
319
357
  * Execute SQL queries against the Agent's database
320
358
  * @template T Type of the returned rows
@@ -344,6 +382,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
344
382
  constructor(ctx: AgentContext, env: Env) {
345
383
  super(ctx, env);
346
384
 
385
+ // Auto-wrap custom methods with agent context
386
+ this._autoWrapCustomMethods();
387
+
347
388
  this.sql`
348
389
  CREATE TABLE IF NOT EXISTS cf_agents_state (
349
390
  id TEXT PRIMARY KEY NOT NULL,
@@ -351,6 +392,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
351
392
  )
352
393
  `;
353
394
 
395
+ this.sql`
396
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
397
+ id TEXT PRIMARY KEY NOT NULL,
398
+ payload TEXT,
399
+ callback TEXT,
400
+ created_at INTEGER DEFAULT (unixepoch())
401
+ )
402
+ `;
403
+
354
404
  void this.ctx.blockConcurrencyWhile(async () => {
355
405
  return this._tryCatch(async () => {
356
406
  // Create alarms table if it doesn't exist
@@ -387,7 +437,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
387
437
  const _onRequest = this.onRequest.bind(this);
388
438
  this.onRequest = (request: Request) => {
389
439
  return agentContext.run(
390
- { agent: this, connection: undefined, request },
440
+ { agent: this, connection: undefined, request, email: undefined },
391
441
  async () => {
392
442
  if (this.mcp.isCallbackRequest(request)) {
393
443
  await this.mcp.handleCallbackRequest(request);
@@ -395,15 +445,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
395
445
  // after the MCP connection handshake, we can send updated mcp state
396
446
  this.broadcast(
397
447
  JSON.stringify({
398
- type: "cf_agent_mcp_servers",
399
- mcp: this._getMcpServerStateInternal(),
448
+ mcp: this.getMcpServers(),
449
+ type: "cf_agent_mcp_servers"
400
450
  })
401
451
  );
402
452
 
403
453
  // We probably should let the user configure this response/redirect, but this is fine for now.
404
454
  return new Response("<script>window.close();</script>", {
405
- status: 200,
406
455
  headers: { "content-type": "text/html" },
456
+ status: 200
407
457
  });
408
458
  }
409
459
 
@@ -415,7 +465,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
415
465
  const _onMessage = this.onMessage.bind(this);
416
466
  this.onMessage = async (connection: Connection, message: WSMessage) => {
417
467
  return agentContext.run(
418
- { agent: this, connection, request: undefined },
468
+ { agent: this, connection, request: undefined, email: undefined },
419
469
  async () => {
420
470
  if (typeof message !== "string") {
421
471
  return this._tryCatch(() => _onMessage(connection, message));
@@ -424,7 +474,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
424
474
  let parsed: unknown;
425
475
  try {
426
476
  parsed = JSON.parse(message);
427
- } catch (e) {
477
+ } catch (_e) {
428
478
  // silently fail and let the onMessage handler handle it
429
479
  return this._tryCatch(() => _onMessage(connection, message));
430
480
  }
@@ -448,7 +498,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
448
498
  throw new Error(`Method ${method} is not callable`);
449
499
  }
450
500
 
451
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
452
501
  const metadata = callableMetadata.get(methodFn as Function);
453
502
 
454
503
  // For streaming methods, pass a StreamingResponse object
@@ -460,22 +509,39 @@ export class Agent<Env, State = unknown> extends Server<Env> {
460
509
 
461
510
  // For regular methods, execute and send response
462
511
  const result = await methodFn.apply(this, args);
512
+
513
+ this.observability?.emit(
514
+ {
515
+ displayMessage: `RPC call to ${method}`,
516
+ id: nanoid(),
517
+ payload: {
518
+ args,
519
+ method,
520
+ streaming: metadata?.streaming,
521
+ success: true
522
+ },
523
+ timestamp: Date.now(),
524
+ type: "rpc"
525
+ },
526
+ this.ctx
527
+ );
528
+
463
529
  const response: RPCResponse = {
464
- type: "rpc",
530
+ done: true,
465
531
  id,
466
- success: true,
467
532
  result,
468
- done: true,
533
+ success: true,
534
+ type: "rpc"
469
535
  };
470
536
  connection.send(JSON.stringify(response));
471
537
  } catch (e) {
472
538
  // Send error response
473
539
  const response: RPCResponse = {
474
- type: "rpc",
475
- id: parsed.id,
476
- success: false,
477
540
  error:
478
541
  e instanceof Error ? e.message : "Unknown error occurred",
542
+ id: parsed.id,
543
+ success: false,
544
+ type: "rpc"
479
545
  };
480
546
  connection.send(JSON.stringify(response));
481
547
  console.error("RPC error:", e);
@@ -493,25 +559,37 @@ export class Agent<Env, State = unknown> extends Server<Env> {
493
559
  // TODO: This is a hack to ensure the state is sent after the connection is established
494
560
  // must fix this
495
561
  return agentContext.run(
496
- { agent: this, connection, request: ctx.request },
562
+ { agent: this, connection, request: ctx.request, email: undefined },
497
563
  async () => {
498
564
  setTimeout(() => {
499
565
  if (this.state) {
500
566
  connection.send(
501
567
  JSON.stringify({
502
- type: "cf_agent_state",
503
568
  state: this.state,
569
+ type: "cf_agent_state"
504
570
  })
505
571
  );
506
572
  }
507
573
 
508
574
  connection.send(
509
575
  JSON.stringify({
510
- type: "cf_agent_mcp_servers",
511
- mcp: this._getMcpServerStateInternal(),
576
+ mcp: this.getMcpServers(),
577
+ type: "cf_agent_mcp_servers"
512
578
  })
513
579
  );
514
580
 
581
+ this.observability?.emit(
582
+ {
583
+ displayMessage: "Connection established",
584
+ id: nanoid(),
585
+ payload: {
586
+ connectionId: connection.id
587
+ },
588
+ timestamp: Date.now(),
589
+ type: "connect"
590
+ },
591
+ this.ctx
592
+ );
515
593
  return this._tryCatch(() => _onConnect(connection, ctx));
516
594
  }, 20);
517
595
  }
@@ -521,37 +599,43 @@ export class Agent<Env, State = unknown> extends Server<Env> {
521
599
  const _onStart = this.onStart.bind(this);
522
600
  this.onStart = async () => {
523
601
  return agentContext.run(
524
- { agent: this, connection: undefined, request: undefined },
602
+ {
603
+ agent: this,
604
+ connection: undefined,
605
+ request: undefined,
606
+ email: undefined
607
+ },
525
608
  async () => {
526
609
  const servers = this.sql<MCPServerRow>`
527
610
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
528
611
  `;
529
612
 
530
- // from DO storage, reconnect to all servers using our saved auth information
531
- await 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
- }
613
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
614
+ if (servers && Array.isArray(servers) && servers.length > 0) {
615
+ Promise.allSettled(
616
+ servers.map((server) => {
617
+ return this._connectToMcpServerInternal(
618
+ server.name,
619
+ server.server_url,
620
+ server.callback_url,
621
+ server.server_options
622
+ ? JSON.parse(server.server_options)
623
+ : undefined,
624
+ {
625
+ id: server.id,
626
+ oauthClientId: server.client_id ?? undefined
627
+ }
628
+ );
629
+ })
630
+ ).then((_results) => {
631
+ this.broadcast(
632
+ JSON.stringify({
633
+ mcp: this.getMcpServers(),
634
+ type: "cf_agent_mcp_servers"
635
+ })
544
636
  );
545
- })
546
- );
547
-
548
- this.broadcast(
549
- JSON.stringify({
550
- type: "cf_agent_mcp_servers",
551
- mcp: this._getMcpServerStateInternal(),
552
- })
553
- );
554
-
637
+ });
638
+ }
555
639
  await this._tryCatch(() => _onStart());
556
640
  }
557
641
  );
@@ -562,6 +646,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
562
646
  state: State,
563
647
  source: Connection | "server" = "server"
564
648
  ) {
649
+ const previousState = this._state;
565
650
  this._state = state;
566
651
  this.sql`
567
652
  INSERT OR REPLACE INTO cf_agents_state (id, state)
@@ -573,16 +658,29 @@ export class Agent<Env, State = unknown> extends Server<Env> {
573
658
  `;
574
659
  this.broadcast(
575
660
  JSON.stringify({
576
- type: "cf_agent_state",
577
661
  state: state,
662
+ type: "cf_agent_state"
578
663
  }),
579
664
  source !== "server" ? [source.id] : []
580
665
  );
581
666
  return this._tryCatch(() => {
582
- const { connection, request } = agentContext.getStore() || {};
667
+ const { connection, request, email } = agentContext.getStore() || {};
583
668
  return agentContext.run(
584
- { agent: this, connection, request },
669
+ { agent: this, connection, request, email },
585
670
  async () => {
671
+ this.observability?.emit(
672
+ {
673
+ displayMessage: "State updated",
674
+ id: nanoid(),
675
+ payload: {
676
+ previousState,
677
+ state
678
+ },
679
+ timestamp: Date.now(),
680
+ type: "state:update"
681
+ },
682
+ this.ctx
683
+ );
586
684
  return this.onStateUpdate(state, source);
587
685
  }
588
686
  );
@@ -602,23 +700,89 @@ export class Agent<Env, State = unknown> extends Server<Env> {
602
700
  * @param state Updated state
603
701
  * @param source Source of the state update ("server" or a client connection)
604
702
  */
703
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
605
704
  onStateUpdate(state: State | undefined, source: Connection | "server") {
606
705
  // override this to handle state updates
607
706
  }
608
707
 
609
708
  /**
610
- * Called when the Agent receives an email
709
+ * Called when the Agent receives an email via routeAgentEmail()
710
+ * Override this method to handle incoming emails
611
711
  * @param email Email message to process
612
712
  */
613
- onEmail(email: ForwardableEmailMessage) {
713
+ async _onEmail(email: AgentEmail) {
714
+ // nb: we use this roundabout way of getting to onEmail
715
+ // because of https://github.com/cloudflare/workerd/issues/4499
614
716
  return agentContext.run(
615
- { agent: this, connection: undefined, request: undefined },
717
+ { agent: this, connection: undefined, request: undefined, email: email },
616
718
  async () => {
617
- console.error("onEmail not implemented");
719
+ if ("onEmail" in this && typeof this.onEmail === "function") {
720
+ return this._tryCatch(() =>
721
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
722
+ );
723
+ } else {
724
+ console.log("Received email from:", email.from, "to:", email.to);
725
+ console.log("Subject:", email.headers.get("subject"));
726
+ console.log(
727
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
728
+ );
729
+ }
618
730
  }
619
731
  );
620
732
  }
621
733
 
734
+ /**
735
+ * Reply to an email
736
+ * @param email The email to reply to
737
+ * @param options Options for the reply
738
+ * @returns void
739
+ */
740
+ async replyToEmail(
741
+ email: AgentEmail,
742
+ options: {
743
+ fromName: string;
744
+ subject?: string | undefined;
745
+ body: string;
746
+ contentType?: string;
747
+ headers?: Record<string, string>;
748
+ }
749
+ ): Promise<void> {
750
+ return this._tryCatch(async () => {
751
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
752
+ const agentId = this.name;
753
+
754
+ const { createMimeMessage } = await import("mimetext");
755
+ const msg = createMimeMessage();
756
+ msg.setSender({ addr: email.to, name: options.fromName });
757
+ msg.setRecipient(email.from);
758
+ msg.setSubject(
759
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
760
+ );
761
+ msg.addMessage({
762
+ contentType: options.contentType || "text/plain",
763
+ data: options.body
764
+ });
765
+
766
+ const domain = email.from.split("@")[1];
767
+ const messageId = `<${agentId}@${domain}>`;
768
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
769
+ msg.setHeader("Message-ID", messageId);
770
+ msg.setHeader("X-Agent-Name", agentName);
771
+ msg.setHeader("X-Agent-ID", agentId);
772
+
773
+ if (options.headers) {
774
+ for (const [key, value] of Object.entries(options.headers)) {
775
+ msg.setHeader(key, value);
776
+ }
777
+ }
778
+ await email.reply({
779
+ from: email.to,
780
+ raw: msg.asRaw(),
781
+ to: email.from
782
+ });
783
+ });
784
+ }
785
+
622
786
  private async _tryCatch<T>(fn: () => T | Promise<T>) {
623
787
  try {
624
788
  return await fn();
@@ -627,6 +791,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
627
791
  }
628
792
  }
629
793
 
794
+ /**
795
+ * Automatically wrap custom methods with agent context
796
+ * This ensures getCurrentAgent() works in all custom methods without decorators
797
+ */
798
+ private _autoWrapCustomMethods() {
799
+ // Collect all methods from base prototypes (Agent and Server)
800
+ const basePrototypes = [Agent.prototype, Server.prototype];
801
+ const baseMethods = new Set<string>();
802
+ for (const baseProto of basePrototypes) {
803
+ let proto = baseProto;
804
+ while (proto && proto !== Object.prototype) {
805
+ const methodNames = Object.getOwnPropertyNames(proto);
806
+ for (const methodName of methodNames) {
807
+ baseMethods.add(methodName);
808
+ }
809
+ proto = Object.getPrototypeOf(proto);
810
+ }
811
+ }
812
+ // Get all methods from the current instance's prototype chain
813
+ let proto = Object.getPrototypeOf(this);
814
+ let depth = 0;
815
+ while (proto && proto !== Object.prototype && depth < 10) {
816
+ const methodNames = Object.getOwnPropertyNames(proto);
817
+ for (const methodName of methodNames) {
818
+ // Skip if it's a private method or not a function
819
+ if (
820
+ baseMethods.has(methodName) ||
821
+ methodName.startsWith("_") ||
822
+ typeof this[methodName as keyof this] !== "function"
823
+ ) {
824
+ continue;
825
+ }
826
+ // If the method doesn't exist in base prototypes, it's a custom method
827
+ if (!baseMethods.has(methodName)) {
828
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
829
+ if (descriptor && typeof descriptor.value === "function") {
830
+ // Wrap the custom method with context
831
+
832
+ const wrappedFunction = withAgentContext(
833
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
834
+ this[methodName as keyof this] as (...args: any[]) => any
835
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
836
+ ) as any;
837
+
838
+ // if the method is callable, copy the metadata from the original method
839
+ if (this._isCallable(methodName)) {
840
+ callableMetadata.set(
841
+ wrappedFunction,
842
+ callableMetadata.get(
843
+ this[methodName as keyof this] as Function
844
+ )!
845
+ );
846
+ }
847
+
848
+ // set the wrapped function on the prototype
849
+ this.constructor.prototype[methodName as keyof this] =
850
+ wrappedFunction;
851
+ }
852
+ }
853
+ }
854
+
855
+ proto = Object.getPrototypeOf(proto);
856
+ depth++;
857
+ }
858
+ }
859
+
630
860
  override onError(
631
861
  connection: Connection,
632
862
  error: unknown
@@ -661,6 +891,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
661
891
  throw new Error("Not implemented");
662
892
  }
663
893
 
894
+ /**
895
+ * Queue a task to be executed in the future
896
+ * @param payload Payload to pass to the callback
897
+ * @param callback Name of the method to call
898
+ * @returns The ID of the queued task
899
+ */
900
+ async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
901
+ const id = nanoid(9);
902
+ if (typeof callback !== "string") {
903
+ throw new Error("Callback must be a string");
904
+ }
905
+
906
+ if (typeof this[callback] !== "function") {
907
+ throw new Error(`this.${callback} is not a function`);
908
+ }
909
+
910
+ this.sql`
911
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
912
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
913
+ `;
914
+
915
+ void this._flushQueue().catch((e) => {
916
+ console.error("Error flushing queue:", e);
917
+ });
918
+
919
+ return id;
920
+ }
921
+
922
+ private _flushingQueue = false;
923
+
924
+ private async _flushQueue() {
925
+ if (this._flushingQueue) {
926
+ return;
927
+ }
928
+ this._flushingQueue = true;
929
+ while (true) {
930
+ const result = this.sql<QueueItem<string>>`
931
+ SELECT * FROM cf_agents_queues
932
+ ORDER BY created_at ASC
933
+ `;
934
+
935
+ if (!result || result.length === 0) {
936
+ break;
937
+ }
938
+
939
+ for (const row of result || []) {
940
+ const callback = this[row.callback as keyof Agent<Env>];
941
+ if (!callback) {
942
+ console.error(`callback ${row.callback} not found`);
943
+ continue;
944
+ }
945
+ const { connection, request, email } = agentContext.getStore() || {};
946
+ await agentContext.run(
947
+ {
948
+ agent: this,
949
+ connection,
950
+ request,
951
+ email
952
+ },
953
+ async () => {
954
+ // TODO: add retries and backoff
955
+ await (
956
+ callback as (
957
+ payload: unknown,
958
+ queueItem: QueueItem<string>
959
+ ) => Promise<void>
960
+ ).bind(this)(JSON.parse(row.payload as string), row);
961
+ await this.dequeue(row.id);
962
+ }
963
+ );
964
+ }
965
+ }
966
+ this._flushingQueue = false;
967
+ }
968
+
969
+ /**
970
+ * Dequeue a task by ID
971
+ * @param id ID of the task to dequeue
972
+ */
973
+ async dequeue(id: string) {
974
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
975
+ }
976
+
977
+ /**
978
+ * Dequeue all tasks
979
+ */
980
+ async dequeueAll() {
981
+ this.sql`DELETE FROM cf_agents_queues`;
982
+ }
983
+
984
+ /**
985
+ * Dequeue all tasks by callback
986
+ * @param callback Name of the callback to dequeue
987
+ */
988
+ async dequeueAllByCallback(callback: string) {
989
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
990
+ }
991
+
992
+ /**
993
+ * Get a queued task by ID
994
+ * @param id ID of the task to get
995
+ * @returns The task or undefined if not found
996
+ */
997
+ async getQueue(id: string): Promise<QueueItem<string> | undefined> {
998
+ const result = this.sql<QueueItem<string>>`
999
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1000
+ `;
1001
+ return result
1002
+ ? { ...result[0], payload: JSON.parse(result[0].payload) }
1003
+ : undefined;
1004
+ }
1005
+
1006
+ /**
1007
+ * Get all queues by key and value
1008
+ * @param key Key to filter by
1009
+ * @param value Value to filter by
1010
+ * @returns Array of matching QueueItem objects
1011
+ */
1012
+ async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1013
+ const result = this.sql<QueueItem<string>>`
1014
+ SELECT * FROM cf_agents_queues
1015
+ `;
1016
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
1017
+ }
1018
+
664
1019
  /**
665
1020
  * Schedule a task to be executed in the future
666
1021
  * @template T Type of the payload data
@@ -676,6 +1031,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
676
1031
  ): Promise<Schedule<T>> {
677
1032
  const id = nanoid(9);
678
1033
 
1034
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
1035
+ this.observability?.emit(
1036
+ {
1037
+ displayMessage: `Schedule ${schedule.id} created`,
1038
+ id: nanoid(),
1039
+ payload: schedule,
1040
+ timestamp: Date.now(),
1041
+ type: "schedule:create"
1042
+ },
1043
+ this.ctx
1044
+ );
1045
+
679
1046
  if (typeof callback !== "string") {
680
1047
  throw new Error("Callback must be a string");
681
1048
  }
@@ -695,13 +1062,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
695
1062
 
696
1063
  await this._scheduleNextAlarm();
697
1064
 
698
- return {
699
- id,
1065
+ const schedule: Schedule<T> = {
700
1066
  callback: callback,
1067
+ id,
701
1068
  payload: payload as T,
702
1069
  time: timestamp,
703
- type: "scheduled",
1070
+ type: "scheduled"
704
1071
  };
1072
+
1073
+ emitScheduleCreate(schedule);
1074
+
1075
+ return schedule;
705
1076
  }
706
1077
  if (typeof when === "number") {
707
1078
  const time = new Date(Date.now() + when * 1000);
@@ -716,14 +1087,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
716
1087
 
717
1088
  await this._scheduleNextAlarm();
718
1089
 
719
- return {
720
- id,
1090
+ const schedule: Schedule<T> = {
721
1091
  callback: callback,
722
- payload: payload as T,
723
1092
  delayInSeconds: when,
1093
+ id,
1094
+ payload: payload as T,
724
1095
  time: timestamp,
725
- type: "delayed",
1096
+ type: "delayed"
726
1097
  };
1098
+
1099
+ emitScheduleCreate(schedule);
1100
+
1101
+ return schedule;
727
1102
  }
728
1103
  if (typeof when === "string") {
729
1104
  const nextExecutionTime = getNextCronTime(when);
@@ -738,14 +1113,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
738
1113
 
739
1114
  await this._scheduleNextAlarm();
740
1115
 
741
- return {
742
- id,
1116
+ const schedule: Schedule<T> = {
743
1117
  callback: callback,
744
- payload: payload as T,
745
1118
  cron: when,
1119
+ id,
1120
+ payload: payload as T,
746
1121
  time: timestamp,
747
- type: "cron",
1122
+ type: "cron"
748
1123
  };
1124
+
1125
+ emitScheduleCreate(schedule);
1126
+
1127
+ return schedule;
749
1128
  }
750
1129
  throw new Error("Invalid schedule type");
751
1130
  }
@@ -809,7 +1188,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
809
1188
  .toArray()
810
1189
  .map((row) => ({
811
1190
  ...row,
812
- payload: JSON.parse(row.payload as string) as T,
1191
+ payload: JSON.parse(row.payload as string) as T
813
1192
  })) as Schedule<T>[];
814
1193
 
815
1194
  return result;
@@ -821,6 +1200,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
821
1200
  * @returns true if the task was cancelled, false otherwise
822
1201
  */
823
1202
  async cancelSchedule(id: string): Promise<boolean> {
1203
+ const schedule = await this.getSchedule(id);
1204
+ if (schedule) {
1205
+ this.observability?.emit(
1206
+ {
1207
+ displayMessage: `Schedule ${id} cancelled`,
1208
+ id: nanoid(),
1209
+ payload: schedule,
1210
+ timestamp: Date.now(),
1211
+ type: "schedule:cancel"
1212
+ },
1213
+ this.ctx
1214
+ );
1215
+ }
824
1216
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
825
1217
 
826
1218
  await this._scheduleNextAlarm();
@@ -830,9 +1222,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
830
1222
  private async _scheduleNextAlarm() {
831
1223
  // Find the next schedule that needs to be executed
832
1224
  const result = this.sql`
833
- SELECT time FROM cf_agents_schedules
1225
+ SELECT time FROM cf_agents_schedules
834
1226
  WHERE time > ${Math.floor(Date.now() / 1000)}
835
- ORDER BY time ASC
1227
+ ORDER BY time ASC
836
1228
  LIMIT 1
837
1229
  `;
838
1230
  if (!result) return;
@@ -859,40 +1251,58 @@ export class Agent<Env, State = unknown> extends Server<Env> {
859
1251
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
860
1252
  `;
861
1253
 
862
- for (const row of result || []) {
863
- const callback = this[row.callback as keyof Agent<Env>];
864
- if (!callback) {
865
- console.error(`callback ${row.callback} not found`);
866
- continue;
867
- }
868
- await agentContext.run(
869
- { agent: this, connection: undefined, request: undefined },
870
- async () => {
871
- try {
872
- await (
873
- callback as (
874
- payload: unknown,
875
- schedule: Schedule<unknown>
876
- ) => Promise<void>
877
- ).bind(this)(JSON.parse(row.payload as string), row);
878
- } catch (e) {
879
- console.error(`error executing callback "${row.callback}"`, e);
880
- }
1254
+ if (result && Array.isArray(result)) {
1255
+ for (const row of result) {
1256
+ const callback = this[row.callback as keyof Agent<Env>];
1257
+ if (!callback) {
1258
+ console.error(`callback ${row.callback} not found`);
1259
+ continue;
881
1260
  }
882
- );
883
- if (row.type === "cron") {
884
- // Update next execution time for cron schedules
885
- const nextExecutionTime = getNextCronTime(row.cron);
886
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1261
+ await agentContext.run(
1262
+ {
1263
+ agent: this,
1264
+ connection: undefined,
1265
+ request: undefined,
1266
+ email: undefined
1267
+ },
1268
+ async () => {
1269
+ try {
1270
+ this.observability?.emit(
1271
+ {
1272
+ displayMessage: `Schedule ${row.id} executed`,
1273
+ id: nanoid(),
1274
+ payload: row,
1275
+ timestamp: Date.now(),
1276
+ type: "schedule:execute"
1277
+ },
1278
+ this.ctx
1279
+ );
887
1280
 
888
- this.sql`
1281
+ await (
1282
+ callback as (
1283
+ payload: unknown,
1284
+ schedule: Schedule<unknown>
1285
+ ) => Promise<void>
1286
+ ).bind(this)(JSON.parse(row.payload as string), row);
1287
+ } catch (e) {
1288
+ console.error(`error executing callback "${row.callback}"`, e);
1289
+ }
1290
+ }
1291
+ );
1292
+ if (row.type === "cron") {
1293
+ // Update next execution time for cron schedules
1294
+ const nextExecutionTime = getNextCronTime(row.cron);
1295
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1296
+
1297
+ this.sql`
889
1298
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
890
1299
  `;
891
- } else {
892
- // Delete one-time schedules after execution
893
- this.sql`
1300
+ } else {
1301
+ // Delete one-time schedules after execution
1302
+ this.sql`
894
1303
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
895
1304
  `;
1305
+ }
896
1306
  }
897
1307
  }
898
1308
 
@@ -908,14 +1318,30 @@ export class Agent<Env, State = unknown> extends Server<Env> {
908
1318
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
909
1319
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
910
1320
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1321
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
911
1322
 
912
1323
  // delete all alarms
913
1324
  await this.ctx.storage.deleteAlarm();
914
1325
  await this.ctx.storage.deleteAll();
1326
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
1327
+
1328
+ this.observability?.emit(
1329
+ {
1330
+ displayMessage: "Agent destroyed",
1331
+ id: nanoid(),
1332
+ payload: {},
1333
+ timestamp: Date.now(),
1334
+ type: "destroy"
1335
+ },
1336
+ this.ctx
1337
+ );
915
1338
  }
916
1339
 
1340
+ /**
1341
+ * Get all methods marked as callable on this Agent
1342
+ * @returns A map of method names to their metadata
1343
+ */
917
1344
  private _isCallable(method: string): boolean {
918
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
919
1345
  return callableMetadata.has(this[method as keyof this] as Function);
920
1346
  }
921
1347
 
@@ -948,11 +1374,24 @@ export class Agent<Env, State = unknown> extends Server<Env> {
948
1374
  callbackUrl,
949
1375
  options
950
1376
  );
1377
+ this.sql`
1378
+ INSERT
1379
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1380
+ VALUES (
1381
+ ${result.id},
1382
+ ${serverName},
1383
+ ${url},
1384
+ ${result.clientId ?? null},
1385
+ ${result.authUrl ?? null},
1386
+ ${callbackUrl},
1387
+ ${options ? JSON.stringify(options) : null}
1388
+ );
1389
+ `;
951
1390
 
952
1391
  this.broadcast(
953
1392
  JSON.stringify({
954
- type: "cf_agent_mcp_servers",
955
- mcp: this._getMcpServerStateInternal(),
1393
+ mcp: this.getMcpServers(),
1394
+ type: "cf_agent_mcp_servers"
956
1395
  })
957
1396
  );
958
1397
 
@@ -960,7 +1399,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
960
1399
  }
961
1400
 
962
1401
  async _connectToMcpServerInternal(
963
- serverName: string,
1402
+ _serverName: string,
964
1403
  url: string,
965
1404
  callbackUrl: string,
966
1405
  // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
@@ -981,7 +1420,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
981
1420
  id: string;
982
1421
  oauthClientId?: string;
983
1422
  }
984
- ): Promise<{ id: string; authUrl: string | undefined }> {
1423
+ ): Promise<{
1424
+ id: string;
1425
+ authUrl: string | undefined;
1426
+ clientId: string | undefined;
1427
+ }> {
985
1428
  const authProvider = new DurableObjectOAuthClientProvider(
986
1429
  this.ctx.storage,
987
1430
  this.name,
@@ -1004,40 +1447,28 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1004
1447
  fetch: (url, init) =>
1005
1448
  fetch(url, {
1006
1449
  ...init,
1007
- headers: options?.transport?.headers,
1008
- }),
1450
+ headers: options?.transport?.headers
1451
+ })
1009
1452
  },
1010
1453
  requestInit: {
1011
- headers: options?.transport?.headers,
1012
- },
1454
+ headers: options?.transport?.headers
1455
+ }
1013
1456
  };
1014
1457
  }
1015
1458
 
1016
1459
  const { id, authUrl, clientId } = await this.mcp.connect(url, {
1460
+ client: options?.client,
1017
1461
  reconnect,
1018
1462
  transport: {
1019
1463
  ...headerTransportOpts,
1020
- authProvider,
1021
- },
1022
- client: options?.client,
1464
+ authProvider
1465
+ }
1023
1466
  });
1024
1467
 
1025
- this.sql`
1026
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1027
- VALUES (
1028
- ${id},
1029
- ${serverName},
1030
- ${url},
1031
- ${clientId ?? null},
1032
- ${authUrl ?? null},
1033
- ${callbackUrl},
1034
- ${options ? JSON.stringify(options) : null}
1035
- );
1036
- `;
1037
-
1038
1468
  return {
1039
- id,
1040
1469
  authUrl,
1470
+ clientId,
1471
+ id
1041
1472
  };
1042
1473
  }
1043
1474
 
@@ -1048,31 +1479,37 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1048
1479
  `;
1049
1480
  this.broadcast(
1050
1481
  JSON.stringify({
1051
- type: "cf_agent_mcp_servers",
1052
- mcp: this._getMcpServerStateInternal(),
1482
+ mcp: this.getMcpServers(),
1483
+ type: "cf_agent_mcp_servers"
1053
1484
  })
1054
1485
  );
1055
1486
  }
1056
1487
 
1057
- private _getMcpServerStateInternal(): MCPServersState {
1488
+ getMcpServers(): MCPServersState {
1058
1489
  const mcpState: MCPServersState = {
1059
- servers: {},
1060
- tools: this.mcp.listTools(),
1061
1490
  prompts: this.mcp.listPrompts(),
1062
1491
  resources: this.mcp.listResources(),
1492
+ servers: {},
1493
+ tools: this.mcp.listTools()
1063
1494
  };
1064
1495
 
1065
1496
  const servers = this.sql<MCPServerRow>`
1066
1497
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1067
1498
  `;
1068
1499
 
1069
- for (const server of servers) {
1070
- mcpState.servers[server.id] = {
1071
- name: server.name,
1072
- server_url: server.server_url,
1073
- auth_url: server.auth_url,
1074
- state: this.mcp.mcpConnections[server.id].connectionState,
1075
- };
1500
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1501
+ for (const server of servers) {
1502
+ const serverConn = this.mcp.mcpConnections[server.id];
1503
+ mcpState.servers[server.id] = {
1504
+ auth_url: server.auth_url,
1505
+ capabilities: serverConn?.serverCapabilities ?? null,
1506
+ instructions: serverConn?.instructions ?? null,
1507
+ name: server.name,
1508
+ server_url: server.server_url,
1509
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1510
+ state: serverConn?.connectionState ?? "authenticating"
1511
+ };
1512
+ }
1076
1513
  }
1077
1514
 
1078
1515
  return mcpState;
@@ -1116,17 +1553,17 @@ export async function routeAgentRequest<Env>(
1116
1553
  const corsHeaders =
1117
1554
  options?.cors === true
1118
1555
  ? {
1119
- "Access-Control-Allow-Origin": "*",
1120
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1121
1556
  "Access-Control-Allow-Credentials": "true",
1122
- "Access-Control-Max-Age": "86400",
1557
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1558
+ "Access-Control-Allow-Origin": "*",
1559
+ "Access-Control-Max-Age": "86400"
1123
1560
  }
1124
1561
  : options?.cors;
1125
1562
 
1126
1563
  if (request.method === "OPTIONS") {
1127
1564
  if (corsHeaders) {
1128
1565
  return new Response(null, {
1129
- headers: corsHeaders,
1566
+ headers: corsHeaders
1130
1567
  });
1131
1568
  }
1132
1569
  console.warn(
@@ -1139,7 +1576,7 @@ export async function routeAgentRequest<Env>(
1139
1576
  env as Record<string, unknown>,
1140
1577
  {
1141
1578
  prefix: "agents",
1142
- ...(options as PartyServerOptions<Record<string, unknown>>),
1579
+ ...(options as PartyServerOptions<Record<string, unknown>>)
1143
1580
  }
1144
1581
  );
1145
1582
 
@@ -1152,24 +1589,238 @@ export async function routeAgentRequest<Env>(
1152
1589
  response = new Response(response.body, {
1153
1590
  headers: {
1154
1591
  ...response.headers,
1155
- ...corsHeaders,
1156
- },
1592
+ ...corsHeaders
1593
+ }
1157
1594
  });
1158
1595
  }
1159
1596
  return response;
1160
1597
  }
1161
1598
 
1599
+ export type EmailResolver<Env> = (
1600
+ email: ForwardableEmailMessage,
1601
+ env: Env
1602
+ ) => Promise<{
1603
+ agentName: string;
1604
+ agentId: string;
1605
+ } | null>;
1606
+
1607
+ /**
1608
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1609
+ * @returns A function that resolves the agent to route the email to
1610
+ */
1611
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1612
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1613
+ const messageId = email.headers.get("message-id");
1614
+ if (messageId) {
1615
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1616
+ if (messageIdMatch) {
1617
+ const [, agentId, domain] = messageIdMatch;
1618
+ const agentName = domain.split(".")[0];
1619
+ return { agentName, agentId };
1620
+ }
1621
+ }
1622
+
1623
+ const references = email.headers.get("references");
1624
+ if (references) {
1625
+ const referencesMatch = references.match(
1626
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1627
+ );
1628
+ if (referencesMatch) {
1629
+ const [, base64Id, domain] = referencesMatch;
1630
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1631
+ const agentName = domain.split(".")[0];
1632
+ return { agentName, agentId };
1633
+ }
1634
+ }
1635
+
1636
+ const agentName = email.headers.get("x-agent-name");
1637
+ const agentId = email.headers.get("x-agent-id");
1638
+ if (agentName && agentId) {
1639
+ return { agentName, agentId };
1640
+ }
1641
+
1642
+ return null;
1643
+ };
1644
+ }
1645
+
1646
+ /**
1647
+ * Create a resolver that uses the email address to determine the agent to route the email to
1648
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1649
+ * @returns A function that resolves the agent to route the email to
1650
+ */
1651
+ export function createAddressBasedEmailResolver<Env>(
1652
+ defaultAgentName: string
1653
+ ): EmailResolver<Env> {
1654
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1655
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1656
+ if (!emailMatch) {
1657
+ return null;
1658
+ }
1659
+
1660
+ const [, localPart, subAddress] = emailMatch;
1661
+
1662
+ if (subAddress) {
1663
+ return {
1664
+ agentName: localPart,
1665
+ agentId: subAddress
1666
+ };
1667
+ }
1668
+
1669
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1670
+ // Common for catch-all email routing to a single EmailAgent namespace
1671
+ return {
1672
+ agentName: defaultAgentName,
1673
+ agentId: localPart
1674
+ };
1675
+ };
1676
+ }
1677
+
1678
+ /**
1679
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1680
+ * @param agentName The name of the agent to route the email to
1681
+ * @param agentId The id of the agent to route the email to
1682
+ * @returns A function that resolves the agent to route the email to
1683
+ */
1684
+ export function createCatchAllEmailResolver<Env>(
1685
+ agentName: string,
1686
+ agentId: string
1687
+ ): EmailResolver<Env> {
1688
+ return async () => ({ agentName, agentId });
1689
+ }
1690
+
1691
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1692
+ resolver: EmailResolver<Env>;
1693
+ };
1694
+
1695
+ // Cache the agent namespace map for email routing
1696
+ // This maps both kebab-case and original names to namespaces
1697
+ const agentMapCache = new WeakMap<
1698
+ Record<string, unknown>,
1699
+ Record<string, unknown>
1700
+ >();
1701
+
1162
1702
  /**
1163
1703
  * Route an email to the appropriate Agent
1164
- * @param email Email message to route
1165
- * @param env Environment containing Agent bindings
1166
- * @param options Routing options
1704
+ * @param email The email to route
1705
+ * @param env The environment containing the Agent bindings
1706
+ * @param options The options for routing the email
1707
+ * @returns A promise that resolves when the email has been routed
1167
1708
  */
1168
1709
  export async function routeAgentEmail<Env>(
1169
1710
  email: ForwardableEmailMessage,
1170
1711
  env: Env,
1171
- options?: AgentOptions<Env>
1172
- ): Promise<void> {}
1712
+ options: EmailRoutingOptions<Env>
1713
+ ): Promise<void> {
1714
+ const routingInfo = await options.resolver(email, env);
1715
+
1716
+ if (!routingInfo) {
1717
+ console.warn("No routing information found for email, dropping message");
1718
+ return;
1719
+ }
1720
+
1721
+ // Build a map that includes both original names and kebab-case versions
1722
+ if (!agentMapCache.has(env as Record<string, unknown>)) {
1723
+ const map: Record<string, unknown> = {};
1724
+ for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1725
+ if (
1726
+ value &&
1727
+ typeof value === "object" &&
1728
+ "idFromName" in value &&
1729
+ typeof value.idFromName === "function"
1730
+ ) {
1731
+ // Add both the original name and kebab-case version
1732
+ map[key] = value;
1733
+ map[camelCaseToKebabCase(key)] = value;
1734
+ }
1735
+ }
1736
+ agentMapCache.set(env as Record<string, unknown>, map);
1737
+ }
1738
+
1739
+ const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
1740
+ const namespace = agentMap[routingInfo.agentName];
1741
+
1742
+ if (!namespace) {
1743
+ // Provide helpful error message listing available agents
1744
+ const availableAgents = Object.keys(agentMap)
1745
+ .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
1746
+ .join(", ");
1747
+ throw new Error(
1748
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1749
+ );
1750
+ }
1751
+
1752
+ const agent = await getAgentByName(
1753
+ namespace as unknown as AgentNamespace<Agent<Env>>,
1754
+ routingInfo.agentId
1755
+ );
1756
+
1757
+ // let's make a serialisable version of the email
1758
+ const serialisableEmail: AgentEmail = {
1759
+ getRaw: async () => {
1760
+ const reader = email.raw.getReader();
1761
+ const chunks: Uint8Array[] = [];
1762
+
1763
+ let done = false;
1764
+ while (!done) {
1765
+ const { value, done: readerDone } = await reader.read();
1766
+ done = readerDone;
1767
+ if (value) {
1768
+ chunks.push(value);
1769
+ }
1770
+ }
1771
+
1772
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1773
+ const combined = new Uint8Array(totalLength);
1774
+ let offset = 0;
1775
+ for (const chunk of chunks) {
1776
+ combined.set(chunk, offset);
1777
+ offset += chunk.length;
1778
+ }
1779
+
1780
+ return combined;
1781
+ },
1782
+ headers: email.headers,
1783
+ rawSize: email.rawSize,
1784
+ setReject: (reason: string) => {
1785
+ email.setReject(reason);
1786
+ },
1787
+ forward: (rcptTo: string, headers?: Headers) => {
1788
+ return email.forward(rcptTo, headers);
1789
+ },
1790
+ reply: (options: { from: string; to: string; raw: string }) => {
1791
+ return email.reply(
1792
+ new EmailMessage(options.from, options.to, options.raw)
1793
+ );
1794
+ },
1795
+ from: email.from,
1796
+ to: email.to
1797
+ };
1798
+
1799
+ await agent._onEmail(serialisableEmail);
1800
+ }
1801
+
1802
+ export type AgentEmail = {
1803
+ from: string;
1804
+ to: string;
1805
+ getRaw: () => Promise<Uint8Array>;
1806
+ headers: Headers;
1807
+ rawSize: number;
1808
+ setReject: (reason: string) => void;
1809
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
1810
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
1811
+ };
1812
+
1813
+ export type EmailSendOptions = {
1814
+ to: string;
1815
+ subject: string;
1816
+ body: string;
1817
+ contentType?: string;
1818
+ headers?: Record<string, string>;
1819
+ includeRoutingHeaders?: boolean;
1820
+ agentName?: string;
1821
+ agentId?: string;
1822
+ domain?: string;
1823
+ };
1173
1824
 
1174
1825
  /**
1175
1826
  * Get or create an Agent by name
@@ -1213,11 +1864,11 @@ export class StreamingResponse {
1213
1864
  throw new Error("StreamingResponse is already closed");
1214
1865
  }
1215
1866
  const response: RPCResponse = {
1216
- type: "rpc",
1867
+ done: false,
1217
1868
  id: this._id,
1218
- success: true,
1219
1869
  result: chunk,
1220
- done: false,
1870
+ success: true,
1871
+ type: "rpc"
1221
1872
  };
1222
1873
  this._connection.send(JSON.stringify(response));
1223
1874
  }
@@ -1232,11 +1883,11 @@ export class StreamingResponse {
1232
1883
  }
1233
1884
  this._closed = true;
1234
1885
  const response: RPCResponse = {
1235
- type: "rpc",
1886
+ done: true,
1236
1887
  id: this._id,
1237
- success: true,
1238
1888
  result: finalChunk,
1239
- done: true,
1889
+ success: true,
1890
+ type: "rpc"
1240
1891
  };
1241
1892
  this._connection.send(JSON.stringify(response));
1242
1893
  }