agents 0.0.0-b57e1d9 → 0.0.0-b5aee9f

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