agents 0.0.0-df41827 → 0.0.0-df52d4b

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 (38) hide show
  1. package/README.md +128 -22
  2. package/dist/ai-chat-agent.d.ts +5 -2
  3. package/dist/ai-chat-agent.js +24 -4
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +6 -3
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/{chunk-ZRRXJUAA.js → chunk-DQJFYHG3.js} +595 -93
  8. package/dist/chunk-DQJFYHG3.js.map +1 -0
  9. package/dist/{chunk-E3LCYPCB.js → chunk-EM3J4KV7.js} +147 -18
  10. package/dist/chunk-EM3J4KV7.js.map +1 -0
  11. package/dist/{chunk-NKZZ66QY.js → chunk-KUH345EY.js} +1 -1
  12. package/dist/chunk-KUH345EY.js.map +1 -0
  13. package/dist/{chunk-767EASBA.js → chunk-PVQZBKN7.js} +1 -1
  14. package/dist/chunk-PVQZBKN7.js.map +1 -0
  15. package/dist/client-DgyzBU_8.d.ts +4601 -0
  16. package/dist/client.d.ts +2 -2
  17. package/dist/client.js +1 -1
  18. package/dist/index.d.ts +152 -16
  19. package/dist/index.js +10 -4
  20. package/dist/mcp/client.d.ts +9 -781
  21. package/dist/mcp/client.js +1 -1
  22. package/dist/mcp/do-oauth-client-provider.js +1 -1
  23. package/dist/mcp/index.d.ts +35 -7
  24. package/dist/mcp/index.js +190 -18
  25. package/dist/mcp/index.js.map +1 -1
  26. package/dist/observability/index.d.ts +46 -0
  27. package/dist/observability/index.js +10 -0
  28. package/dist/observability/index.js.map +1 -0
  29. package/dist/react.d.ts +8 -5
  30. package/dist/react.js.map +1 -1
  31. package/dist/schedule.d.ts +4 -4
  32. package/dist/schedule.js.map +1 -1
  33. package/package.json +34 -26
  34. package/src/index.ts +799 -134
  35. package/dist/chunk-767EASBA.js.map +0 -1
  36. package/dist/chunk-E3LCYPCB.js.map +0 -1
  37. package/dist/chunk-NKZZ66QY.js.map +0 -1
  38. package/dist/chunk-ZRRXJUAA.js.map +0 -1
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { env } from "cloudflare:workers";
1
2
  import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
4
  import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
@@ -6,23 +7,25 @@ import type {
6
7
  Prompt,
7
8
  Resource,
8
9
  ServerCapabilities,
9
- Tool,
10
+ Tool
10
11
  } from "@modelcontextprotocol/sdk/types.js";
11
12
  import { parseCronExpression } from "cron-schedule";
12
13
  import { nanoid } from "nanoid";
14
+ import { EmailMessage } from "cloudflare:email";
13
15
  import {
14
16
  type Connection,
15
17
  type ConnectionContext,
16
- getServerByName,
17
18
  type PartyServerOptions,
18
- routePartykitRequest,
19
19
  Server,
20
20
  type WSMessage,
21
+ getServerByName,
22
+ routePartykitRequest
21
23
  } from "partyserver";
22
24
  import { camelCaseToKebabCase } from "./client";
23
25
  import { MCPClientManager } from "./mcp/client";
24
26
  // import type { MCPClientConnection } from "./mcp/client-connection";
25
27
  import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
+ import { genericObservability, type Observability } from "./observability";
26
29
 
27
30
  export type { Connection, ConnectionContext, WSMessage } from "partyserver";
28
31
 
@@ -128,6 +131,13 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
128
131
  };
129
132
  }
130
133
 
134
+ export type QueueItem<T = string> = {
135
+ id: string;
136
+ payload: T;
137
+ callback: keyof Agent<unknown>;
138
+ created_at: number;
139
+ };
140
+
131
141
  /**
132
142
  * Represents a scheduled task within an Agent
133
143
  * @template T Type of the payload data
@@ -217,23 +227,26 @@ const STATE_WAS_CHANGED = "cf_state_was_changed";
217
227
  const DEFAULT_STATE = {} as unknown;
218
228
 
219
229
  const agentContext = new AsyncLocalStorage<{
220
- agent: Agent<unknown>;
230
+ agent: Agent<unknown, unknown>;
221
231
  connection: Connection | undefined;
222
232
  request: Request | undefined;
233
+ email: AgentEmail | undefined;
223
234
  }>();
224
235
 
225
236
  export function getCurrentAgent<
226
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
237
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
227
238
  >(): {
228
239
  agent: T | undefined;
229
240
  connection: Connection | undefined;
230
- request: Request<unknown, CfProperties<unknown>> | undefined;
241
+ request: Request | undefined;
242
+ email: AgentEmail | undefined;
231
243
  } {
232
244
  const store = agentContext.getStore() as
233
245
  | {
234
246
  agent: T;
235
247
  connection: Connection | undefined;
236
- request: Request<unknown, CfProperties<unknown>> | undefined;
248
+ request: Request | undefined;
249
+ email: AgentEmail | undefined;
237
250
  }
238
251
  | undefined;
239
252
  if (!store) {
@@ -241,17 +254,37 @@ export function getCurrentAgent<
241
254
  agent: undefined,
242
255
  connection: undefined,
243
256
  request: undefined,
257
+ email: undefined
244
258
  };
245
259
  }
246
260
  return store;
247
261
  }
248
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
+
249
282
  /**
250
283
  * Base class for creating Agent implementations
251
284
  * @template Env Environment type containing bindings
252
285
  * @template State State type to store within the Agent
253
286
  */
254
- export class Agent<Env, State = unknown> extends Server<Env> {
287
+ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
255
288
  private _state = DEFAULT_STATE as State;
256
289
 
257
290
  private _ParentClass: typeof Agent<Env, State> =
@@ -313,9 +346,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
313
346
  */
314
347
  static options = {
315
348
  /** Whether the Agent should hibernate when inactive */
316
- hibernate: true, // default to hibernate
349
+ hibernate: true // default to hibernate
317
350
  };
318
351
 
352
+ /**
353
+ * The observability implementation to use for the Agent
354
+ */
355
+ observability?: Observability = genericObservability;
356
+
319
357
  /**
320
358
  * Execute SQL queries against the Agent's database
321
359
  * @template T Type of the returned rows
@@ -345,6 +383,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
345
383
  constructor(ctx: AgentContext, env: Env) {
346
384
  super(ctx, env);
347
385
 
386
+ // Auto-wrap custom methods with agent context
387
+ this._autoWrapCustomMethods();
388
+
348
389
  this.sql`
349
390
  CREATE TABLE IF NOT EXISTS cf_agents_state (
350
391
  id TEXT PRIMARY KEY NOT NULL,
@@ -352,6 +393,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
352
393
  )
353
394
  `;
354
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
+
355
405
  void this.ctx.blockConcurrencyWhile(async () => {
356
406
  return this._tryCatch(async () => {
357
407
  // Create alarms table if it doesn't exist
@@ -388,7 +438,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
388
438
  const _onRequest = this.onRequest.bind(this);
389
439
  this.onRequest = (request: Request) => {
390
440
  return agentContext.run(
391
- { agent: this, connection: undefined, request },
441
+ { agent: this, connection: undefined, request, email: undefined },
392
442
  async () => {
393
443
  if (this.mcp.isCallbackRequest(request)) {
394
444
  await this.mcp.handleCallbackRequest(request);
@@ -397,14 +447,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
397
447
  this.broadcast(
398
448
  JSON.stringify({
399
449
  mcp: this.getMcpServers(),
400
- type: "cf_agent_mcp_servers",
450
+ type: "cf_agent_mcp_servers"
401
451
  })
402
452
  );
403
453
 
404
454
  // We probably should let the user configure this response/redirect, but this is fine for now.
405
455
  return new Response("<script>window.close();</script>", {
406
456
  headers: { "content-type": "text/html" },
407
- status: 200,
457
+ status: 200
408
458
  });
409
459
  }
410
460
 
@@ -416,7 +466,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
416
466
  const _onMessage = this.onMessage.bind(this);
417
467
  this.onMessage = async (connection: Connection, message: WSMessage) => {
418
468
  return agentContext.run(
419
- { agent: this, connection, request: undefined },
469
+ { agent: this, connection, request: undefined, email: undefined },
420
470
  async () => {
421
471
  if (typeof message !== "string") {
422
472
  return this._tryCatch(() => _onMessage(connection, message));
@@ -460,12 +510,27 @@ export class Agent<Env, State = unknown> extends Server<Env> {
460
510
 
461
511
  // For regular methods, execute and send response
462
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
+ method,
520
+ streaming: metadata?.streaming
521
+ },
522
+ timestamp: Date.now(),
523
+ type: "rpc"
524
+ },
525
+ this.ctx
526
+ );
527
+
463
528
  const response: RPCResponse = {
464
529
  done: true,
465
530
  id,
466
531
  result,
467
532
  success: true,
468
- type: "rpc",
533
+ type: "rpc"
469
534
  };
470
535
  connection.send(JSON.stringify(response));
471
536
  } catch (e) {
@@ -475,7 +540,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
475
540
  e instanceof Error ? e.message : "Unknown error occurred",
476
541
  id: parsed.id,
477
542
  success: false,
478
- type: "rpc",
543
+ type: "rpc"
479
544
  };
480
545
  connection.send(JSON.stringify(response));
481
546
  console.error("RPC error:", e);
@@ -493,14 +558,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
493
558
  // TODO: This is a hack to ensure the state is sent after the connection is established
494
559
  // must fix this
495
560
  return agentContext.run(
496
- { agent: this, connection, request: ctx.request },
561
+ { agent: this, connection, request: ctx.request, email: undefined },
497
562
  async () => {
498
563
  setTimeout(() => {
499
564
  if (this.state) {
500
565
  connection.send(
501
566
  JSON.stringify({
502
567
  state: this.state,
503
- type: "cf_agent_state",
568
+ type: "cf_agent_state"
504
569
  })
505
570
  );
506
571
  }
@@ -508,10 +573,22 @@ export class Agent<Env, State = unknown> extends Server<Env> {
508
573
  connection.send(
509
574
  JSON.stringify({
510
575
  mcp: this.getMcpServers(),
511
- type: "cf_agent_mcp_servers",
576
+ type: "cf_agent_mcp_servers"
512
577
  })
513
578
  );
514
579
 
580
+ this.observability?.emit(
581
+ {
582
+ displayMessage: "Connection established",
583
+ id: nanoid(),
584
+ payload: {
585
+ connectionId: connection.id
586
+ },
587
+ timestamp: Date.now(),
588
+ type: "connect"
589
+ },
590
+ this.ctx
591
+ );
515
592
  return this._tryCatch(() => _onConnect(connection, ctx));
516
593
  }, 20);
517
594
  }
@@ -521,18 +598,29 @@ export class Agent<Env, State = unknown> extends Server<Env> {
521
598
  const _onStart = this.onStart.bind(this);
522
599
  this.onStart = async () => {
523
600
  return agentContext.run(
524
- { agent: this, connection: undefined, request: undefined },
601
+ {
602
+ agent: this,
603
+ connection: undefined,
604
+ request: undefined,
605
+ email: undefined
606
+ },
525
607
  async () => {
526
- const servers = this.sql<MCPServerRow>`
608
+ await this._tryCatch(() => {
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 not currently in the oauth flow using our saved auth information
531
- await Promise.allSettled(
532
- servers
533
- .filter((server) => server.auth_url === null)
534
- .map((server) => {
535
- return this._connectToMcpServerInternal(
613
+ this.broadcast(
614
+ JSON.stringify({
615
+ mcp: this.getMcpServers(),
616
+ type: "cf_agent_mcp_servers"
617
+ })
618
+ );
619
+
620
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
621
+ if (servers && Array.isArray(servers) && servers.length > 0) {
622
+ servers.forEach((server) => {
623
+ this._connectToMcpServerInternal(
536
624
  server.name,
537
625
  server.server_url,
538
626
  server.callback_url,
@@ -541,20 +629,35 @@ export class Agent<Env, State = unknown> extends Server<Env> {
541
629
  : undefined,
542
630
  {
543
631
  id: server.id,
544
- oauthClientId: server.client_id ?? undefined,
632
+ oauthClientId: server.client_id ?? undefined
545
633
  }
546
- );
547
- })
548
- );
549
-
550
- this.broadcast(
551
- JSON.stringify({
552
- mcp: this.getMcpServers(),
553
- type: "cf_agent_mcp_servers",
554
- })
555
- );
556
-
557
- await this._tryCatch(() => _onStart());
634
+ )
635
+ .then(() => {
636
+ // Broadcast updated MCP servers state after each server connects
637
+ this.broadcast(
638
+ JSON.stringify({
639
+ mcp: this.getMcpServers(),
640
+ type: "cf_agent_mcp_servers"
641
+ })
642
+ );
643
+ })
644
+ .catch((error) => {
645
+ console.error(
646
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
647
+ error
648
+ );
649
+ // Still broadcast even if connection fails, so clients know about the failure
650
+ this.broadcast(
651
+ JSON.stringify({
652
+ mcp: this.getMcpServers(),
653
+ type: "cf_agent_mcp_servers"
654
+ })
655
+ );
656
+ });
657
+ });
658
+ }
659
+ return _onStart();
660
+ });
558
661
  }
559
662
  );
560
663
  };
@@ -576,15 +679,25 @@ export class Agent<Env, State = unknown> extends Server<Env> {
576
679
  this.broadcast(
577
680
  JSON.stringify({
578
681
  state: state,
579
- type: "cf_agent_state",
682
+ type: "cf_agent_state"
580
683
  }),
581
684
  source !== "server" ? [source.id] : []
582
685
  );
583
686
  return this._tryCatch(() => {
584
- const { connection, request } = agentContext.getStore() || {};
687
+ const { connection, request, email } = agentContext.getStore() || {};
585
688
  return agentContext.run(
586
- { agent: this, connection, request },
689
+ { agent: this, connection, request, email },
587
690
  async () => {
691
+ this.observability?.emit(
692
+ {
693
+ displayMessage: "State updated",
694
+ id: nanoid(),
695
+ payload: {},
696
+ timestamp: Date.now(),
697
+ type: "state:update"
698
+ },
699
+ this.ctx
700
+ );
588
701
  return this.onStateUpdate(state, source);
589
702
  }
590
703
  );
@@ -610,19 +723,83 @@ export class Agent<Env, State = unknown> extends Server<Env> {
610
723
  }
611
724
 
612
725
  /**
613
- * Called when the Agent receives an email
726
+ * Called when the Agent receives an email via routeAgentEmail()
727
+ * Override this method to handle incoming emails
614
728
  * @param email Email message to process
615
729
  */
616
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
617
- onEmail(email: ForwardableEmailMessage) {
730
+ async _onEmail(email: AgentEmail) {
731
+ // nb: we use this roundabout way of getting to onEmail
732
+ // because of https://github.com/cloudflare/workerd/issues/4499
618
733
  return agentContext.run(
619
- { agent: this, connection: undefined, request: undefined },
734
+ { agent: this, connection: undefined, request: undefined, email: email },
620
735
  async () => {
621
- console.error("onEmail not implemented");
736
+ if ("onEmail" in this && typeof this.onEmail === "function") {
737
+ return this._tryCatch(() =>
738
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
739
+ );
740
+ } else {
741
+ console.log("Received email from:", email.from, "to:", email.to);
742
+ console.log("Subject:", email.headers.get("subject"));
743
+ console.log(
744
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
745
+ );
746
+ }
622
747
  }
623
748
  );
624
749
  }
625
750
 
751
+ /**
752
+ * Reply to an email
753
+ * @param email The email to reply to
754
+ * @param options Options for the reply
755
+ * @returns void
756
+ */
757
+ async replyToEmail(
758
+ email: AgentEmail,
759
+ options: {
760
+ fromName: string;
761
+ subject?: string | undefined;
762
+ body: string;
763
+ contentType?: string;
764
+ headers?: Record<string, string>;
765
+ }
766
+ ): Promise<void> {
767
+ return this._tryCatch(async () => {
768
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
769
+ const agentId = this.name;
770
+
771
+ const { createMimeMessage } = await import("mimetext");
772
+ const msg = createMimeMessage();
773
+ msg.setSender({ addr: email.to, name: options.fromName });
774
+ msg.setRecipient(email.from);
775
+ msg.setSubject(
776
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
777
+ );
778
+ msg.addMessage({
779
+ contentType: options.contentType || "text/plain",
780
+ data: options.body
781
+ });
782
+
783
+ const domain = email.from.split("@")[1];
784
+ const messageId = `<${agentId}@${domain}>`;
785
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
786
+ msg.setHeader("Message-ID", messageId);
787
+ msg.setHeader("X-Agent-Name", agentName);
788
+ msg.setHeader("X-Agent-ID", agentId);
789
+
790
+ if (options.headers) {
791
+ for (const [key, value] of Object.entries(options.headers)) {
792
+ msg.setHeader(key, value);
793
+ }
794
+ }
795
+ await email.reply({
796
+ from: email.to,
797
+ raw: msg.asRaw(),
798
+ to: email.from
799
+ });
800
+ });
801
+ }
802
+
626
803
  private async _tryCatch<T>(fn: () => T | Promise<T>) {
627
804
  try {
628
805
  return await fn();
@@ -631,6 +808,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
631
808
  }
632
809
  }
633
810
 
811
+ /**
812
+ * Automatically wrap custom methods with agent context
813
+ * This ensures getCurrentAgent() works in all custom methods without decorators
814
+ */
815
+ private _autoWrapCustomMethods() {
816
+ // Collect all methods from base prototypes (Agent and Server)
817
+ const basePrototypes = [Agent.prototype, Server.prototype];
818
+ const baseMethods = new Set<string>();
819
+ for (const baseProto of basePrototypes) {
820
+ let proto = baseProto;
821
+ while (proto && proto !== Object.prototype) {
822
+ const methodNames = Object.getOwnPropertyNames(proto);
823
+ for (const methodName of methodNames) {
824
+ baseMethods.add(methodName);
825
+ }
826
+ proto = Object.getPrototypeOf(proto);
827
+ }
828
+ }
829
+ // Get all methods from the current instance's prototype chain
830
+ let proto = Object.getPrototypeOf(this);
831
+ let depth = 0;
832
+ while (proto && proto !== Object.prototype && depth < 10) {
833
+ const methodNames = Object.getOwnPropertyNames(proto);
834
+ for (const methodName of methodNames) {
835
+ // Skip if it's a private method or not a function
836
+ if (
837
+ baseMethods.has(methodName) ||
838
+ methodName.startsWith("_") ||
839
+ typeof this[methodName as keyof this] !== "function"
840
+ ) {
841
+ continue;
842
+ }
843
+ // If the method doesn't exist in base prototypes, it's a custom method
844
+ if (!baseMethods.has(methodName)) {
845
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
846
+ if (descriptor && typeof descriptor.value === "function") {
847
+ // Wrap the custom method with context
848
+
849
+ const wrappedFunction = withAgentContext(
850
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
851
+ this[methodName as keyof this] as (...args: any[]) => any
852
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
853
+ ) as any;
854
+
855
+ // if the method is callable, copy the metadata from the original method
856
+ if (this._isCallable(methodName)) {
857
+ callableMetadata.set(
858
+ wrappedFunction,
859
+ callableMetadata.get(
860
+ this[methodName as keyof this] as Function
861
+ )!
862
+ );
863
+ }
864
+
865
+ // set the wrapped function on the prototype
866
+ this.constructor.prototype[methodName as keyof this] =
867
+ wrappedFunction;
868
+ }
869
+ }
870
+ }
871
+
872
+ proto = Object.getPrototypeOf(proto);
873
+ depth++;
874
+ }
875
+ }
876
+
634
877
  override onError(
635
878
  connection: Connection,
636
879
  error: unknown
@@ -665,6 +908,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
665
908
  throw new Error("Not implemented");
666
909
  }
667
910
 
911
+ /**
912
+ * Queue a task to be executed in the future
913
+ * @param payload Payload to pass to the callback
914
+ * @param callback Name of the method to call
915
+ * @returns The ID of the queued task
916
+ */
917
+ async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
918
+ const id = nanoid(9);
919
+ if (typeof callback !== "string") {
920
+ throw new Error("Callback must be a string");
921
+ }
922
+
923
+ if (typeof this[callback] !== "function") {
924
+ throw new Error(`this.${callback} is not a function`);
925
+ }
926
+
927
+ this.sql`
928
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
929
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
930
+ `;
931
+
932
+ void this._flushQueue().catch((e) => {
933
+ console.error("Error flushing queue:", e);
934
+ });
935
+
936
+ return id;
937
+ }
938
+
939
+ private _flushingQueue = false;
940
+
941
+ private async _flushQueue() {
942
+ if (this._flushingQueue) {
943
+ return;
944
+ }
945
+ this._flushingQueue = true;
946
+ while (true) {
947
+ const result = this.sql<QueueItem<string>>`
948
+ SELECT * FROM cf_agents_queues
949
+ ORDER BY created_at ASC
950
+ `;
951
+
952
+ if (!result || result.length === 0) {
953
+ break;
954
+ }
955
+
956
+ for (const row of result || []) {
957
+ const callback = this[row.callback as keyof Agent<Env>];
958
+ if (!callback) {
959
+ console.error(`callback ${row.callback} not found`);
960
+ continue;
961
+ }
962
+ const { connection, request, email } = agentContext.getStore() || {};
963
+ await agentContext.run(
964
+ {
965
+ agent: this,
966
+ connection,
967
+ request,
968
+ email
969
+ },
970
+ async () => {
971
+ // TODO: add retries and backoff
972
+ await (
973
+ callback as (
974
+ payload: unknown,
975
+ queueItem: QueueItem<string>
976
+ ) => Promise<void>
977
+ ).bind(this)(JSON.parse(row.payload as string), row);
978
+ await this.dequeue(row.id);
979
+ }
980
+ );
981
+ }
982
+ }
983
+ this._flushingQueue = false;
984
+ }
985
+
986
+ /**
987
+ * Dequeue a task by ID
988
+ * @param id ID of the task to dequeue
989
+ */
990
+ async dequeue(id: string) {
991
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
992
+ }
993
+
994
+ /**
995
+ * Dequeue all tasks
996
+ */
997
+ async dequeueAll() {
998
+ this.sql`DELETE FROM cf_agents_queues`;
999
+ }
1000
+
1001
+ /**
1002
+ * Dequeue all tasks by callback
1003
+ * @param callback Name of the callback to dequeue
1004
+ */
1005
+ async dequeueAllByCallback(callback: string) {
1006
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1007
+ }
1008
+
1009
+ /**
1010
+ * Get a queued task by ID
1011
+ * @param id ID of the task to get
1012
+ * @returns The task or undefined if not found
1013
+ */
1014
+ async getQueue(id: string): Promise<QueueItem<string> | undefined> {
1015
+ const result = this.sql<QueueItem<string>>`
1016
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1017
+ `;
1018
+ return result
1019
+ ? { ...result[0], payload: JSON.parse(result[0].payload) }
1020
+ : undefined;
1021
+ }
1022
+
1023
+ /**
1024
+ * Get all queues by key and value
1025
+ * @param key Key to filter by
1026
+ * @param value Value to filter by
1027
+ * @returns Array of matching QueueItem objects
1028
+ */
1029
+ async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1030
+ const result = this.sql<QueueItem<string>>`
1031
+ SELECT * FROM cf_agents_queues
1032
+ `;
1033
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
1034
+ }
1035
+
668
1036
  /**
669
1037
  * Schedule a task to be executed in the future
670
1038
  * @template T Type of the payload data
@@ -680,6 +1048,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
680
1048
  ): Promise<Schedule<T>> {
681
1049
  const id = nanoid(9);
682
1050
 
1051
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
1052
+ this.observability?.emit(
1053
+ {
1054
+ displayMessage: `Schedule ${schedule.id} created`,
1055
+ id: nanoid(),
1056
+ payload: {
1057
+ callback: callback as string,
1058
+ id: id
1059
+ },
1060
+ timestamp: Date.now(),
1061
+ type: "schedule:create"
1062
+ },
1063
+ this.ctx
1064
+ );
1065
+
683
1066
  if (typeof callback !== "string") {
684
1067
  throw new Error("Callback must be a string");
685
1068
  }
@@ -699,13 +1082,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
699
1082
 
700
1083
  await this._scheduleNextAlarm();
701
1084
 
702
- return {
1085
+ const schedule: Schedule<T> = {
703
1086
  callback: callback,
704
1087
  id,
705
1088
  payload: payload as T,
706
1089
  time: timestamp,
707
- type: "scheduled",
1090
+ type: "scheduled"
708
1091
  };
1092
+
1093
+ emitScheduleCreate(schedule);
1094
+
1095
+ return schedule;
709
1096
  }
710
1097
  if (typeof when === "number") {
711
1098
  const time = new Date(Date.now() + when * 1000);
@@ -720,14 +1107,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
720
1107
 
721
1108
  await this._scheduleNextAlarm();
722
1109
 
723
- return {
1110
+ const schedule: Schedule<T> = {
724
1111
  callback: callback,
725
1112
  delayInSeconds: when,
726
1113
  id,
727
1114
  payload: payload as T,
728
1115
  time: timestamp,
729
- type: "delayed",
1116
+ type: "delayed"
730
1117
  };
1118
+
1119
+ emitScheduleCreate(schedule);
1120
+
1121
+ return schedule;
731
1122
  }
732
1123
  if (typeof when === "string") {
733
1124
  const nextExecutionTime = getNextCronTime(when);
@@ -742,14 +1133,18 @@ export class Agent<Env, State = unknown> extends Server<Env> {
742
1133
 
743
1134
  await this._scheduleNextAlarm();
744
1135
 
745
- return {
1136
+ const schedule: Schedule<T> = {
746
1137
  callback: callback,
747
1138
  cron: when,
748
1139
  id,
749
1140
  payload: payload as T,
750
1141
  time: timestamp,
751
- type: "cron",
1142
+ type: "cron"
752
1143
  };
1144
+
1145
+ emitScheduleCreate(schedule);
1146
+
1147
+ return schedule;
753
1148
  }
754
1149
  throw new Error("Invalid schedule type");
755
1150
  }
@@ -813,7 +1208,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
813
1208
  .toArray()
814
1209
  .map((row) => ({
815
1210
  ...row,
816
- payload: JSON.parse(row.payload as string) as T,
1211
+ payload: JSON.parse(row.payload as string) as T
817
1212
  })) as Schedule<T>[];
818
1213
 
819
1214
  return result;
@@ -825,6 +1220,22 @@ export class Agent<Env, State = unknown> extends Server<Env> {
825
1220
  * @returns true if the task was cancelled, false otherwise
826
1221
  */
827
1222
  async cancelSchedule(id: string): Promise<boolean> {
1223
+ const schedule = await this.getSchedule(id);
1224
+ if (schedule) {
1225
+ this.observability?.emit(
1226
+ {
1227
+ displayMessage: `Schedule ${id} cancelled`,
1228
+ id: nanoid(),
1229
+ payload: {
1230
+ callback: schedule.callback,
1231
+ id: schedule.id
1232
+ },
1233
+ timestamp: Date.now(),
1234
+ type: "schedule:cancel"
1235
+ },
1236
+ this.ctx
1237
+ );
1238
+ }
828
1239
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
829
1240
 
830
1241
  await this._scheduleNextAlarm();
@@ -834,9 +1245,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
834
1245
  private async _scheduleNextAlarm() {
835
1246
  // Find the next schedule that needs to be executed
836
1247
  const result = this.sql`
837
- SELECT time FROM cf_agents_schedules
1248
+ SELECT time FROM cf_agents_schedules
838
1249
  WHERE time > ${Math.floor(Date.now() / 1000)}
839
- ORDER BY time ASC
1250
+ ORDER BY time ASC
840
1251
  LIMIT 1
841
1252
  `;
842
1253
  if (!result) return;
@@ -863,40 +1274,61 @@ export class Agent<Env, State = unknown> extends Server<Env> {
863
1274
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
864
1275
  `;
865
1276
 
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
- }
1277
+ if (result && Array.isArray(result)) {
1278
+ for (const row of result) {
1279
+ const callback = this[row.callback as keyof Agent<Env>];
1280
+ if (!callback) {
1281
+ console.error(`callback ${row.callback} not found`);
1282
+ continue;
885
1283
  }
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);
1284
+ await agentContext.run(
1285
+ {
1286
+ agent: this,
1287
+ connection: undefined,
1288
+ request: undefined,
1289
+ email: undefined
1290
+ },
1291
+ async () => {
1292
+ try {
1293
+ this.observability?.emit(
1294
+ {
1295
+ displayMessage: `Schedule ${row.id} executed`,
1296
+ id: nanoid(),
1297
+ payload: {
1298
+ callback: row.callback,
1299
+ id: row.id
1300
+ },
1301
+ timestamp: Date.now(),
1302
+ type: "schedule:execute"
1303
+ },
1304
+ this.ctx
1305
+ );
891
1306
 
892
- this.sql`
1307
+ await (
1308
+ callback as (
1309
+ payload: unknown,
1310
+ schedule: Schedule<unknown>
1311
+ ) => Promise<void>
1312
+ ).bind(this)(JSON.parse(row.payload as string), row);
1313
+ } catch (e) {
1314
+ console.error(`error executing callback "${row.callback}"`, e);
1315
+ }
1316
+ }
1317
+ );
1318
+ if (row.type === "cron") {
1319
+ // Update next execution time for cron schedules
1320
+ const nextExecutionTime = getNextCronTime(row.cron);
1321
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1322
+
1323
+ this.sql`
893
1324
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
894
1325
  `;
895
- } else {
896
- // Delete one-time schedules after execution
897
- this.sql`
1326
+ } else {
1327
+ // Delete one-time schedules after execution
1328
+ this.sql`
898
1329
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
899
1330
  `;
1331
+ }
900
1332
  }
901
1333
  }
902
1334
 
@@ -912,11 +1344,23 @@ export class Agent<Env, State = unknown> extends Server<Env> {
912
1344
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
913
1345
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
914
1346
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1347
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
915
1348
 
916
1349
  // delete all alarms
917
1350
  await this.ctx.storage.deleteAlarm();
918
1351
  await this.ctx.storage.deleteAll();
919
1352
  this.ctx.abort("destroyed"); // enforce that the agent is evicted
1353
+
1354
+ this.observability?.emit(
1355
+ {
1356
+ displayMessage: "Agent destroyed",
1357
+ id: nanoid(),
1358
+ payload: {},
1359
+ timestamp: Date.now(),
1360
+ type: "destroy"
1361
+ },
1362
+ this.ctx
1363
+ );
920
1364
  }
921
1365
 
922
1366
  /**
@@ -956,11 +1400,24 @@ export class Agent<Env, State = unknown> extends Server<Env> {
956
1400
  callbackUrl,
957
1401
  options
958
1402
  );
1403
+ this.sql`
1404
+ INSERT
1405
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1406
+ VALUES (
1407
+ ${result.id},
1408
+ ${serverName},
1409
+ ${url},
1410
+ ${result.clientId ?? null},
1411
+ ${result.authUrl ?? null},
1412
+ ${callbackUrl},
1413
+ ${options ? JSON.stringify(options) : null}
1414
+ );
1415
+ `;
959
1416
 
960
1417
  this.broadcast(
961
1418
  JSON.stringify({
962
1419
  mcp: this.getMcpServers(),
963
- type: "cf_agent_mcp_servers",
1420
+ type: "cf_agent_mcp_servers"
964
1421
  })
965
1422
  );
966
1423
 
@@ -968,7 +1425,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
968
1425
  }
969
1426
 
970
1427
  async _connectToMcpServerInternal(
971
- serverName: string,
1428
+ _serverName: string,
972
1429
  url: string,
973
1430
  callbackUrl: string,
974
1431
  // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
@@ -989,7 +1446,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
989
1446
  id: string;
990
1447
  oauthClientId?: string;
991
1448
  }
992
- ): Promise<{ id: string; authUrl: string | undefined }> {
1449
+ ): Promise<{
1450
+ id: string;
1451
+ authUrl: string | undefined;
1452
+ clientId: string | undefined;
1453
+ }> {
993
1454
  const authProvider = new DurableObjectOAuthClientProvider(
994
1455
  this.ctx.storage,
995
1456
  this.name,
@@ -1012,12 +1473,12 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1012
1473
  fetch: (url, init) =>
1013
1474
  fetch(url, {
1014
1475
  ...init,
1015
- headers: options?.transport?.headers,
1016
- }),
1476
+ headers: options?.transport?.headers
1477
+ })
1017
1478
  },
1018
1479
  requestInit: {
1019
- headers: options?.transport?.headers,
1020
- },
1480
+ headers: options?.transport?.headers
1481
+ }
1021
1482
  };
1022
1483
  }
1023
1484
 
@@ -1026,26 +1487,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1026
1487
  reconnect,
1027
1488
  transport: {
1028
1489
  ...headerTransportOpts,
1029
- authProvider,
1030
- },
1490
+ authProvider
1491
+ }
1031
1492
  });
1032
1493
 
1033
- this.sql`
1034
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1035
- VALUES (
1036
- ${id},
1037
- ${serverName},
1038
- ${url},
1039
- ${clientId ?? null},
1040
- ${authUrl ?? null},
1041
- ${callbackUrl},
1042
- ${options ? JSON.stringify(options) : null}
1043
- );
1044
- `;
1045
-
1046
1494
  return {
1047
1495
  authUrl,
1048
- id,
1496
+ clientId,
1497
+ id
1049
1498
  };
1050
1499
  }
1051
1500
 
@@ -1057,7 +1506,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1057
1506
  this.broadcast(
1058
1507
  JSON.stringify({
1059
1508
  mcp: this.getMcpServers(),
1060
- type: "cf_agent_mcp_servers",
1509
+ type: "cf_agent_mcp_servers"
1061
1510
  })
1062
1511
  );
1063
1512
  }
@@ -1067,24 +1516,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
1067
1516
  prompts: this.mcp.listPrompts(),
1068
1517
  resources: this.mcp.listResources(),
1069
1518
  servers: {},
1070
- tools: this.mcp.listTools(),
1519
+ tools: this.mcp.listTools()
1071
1520
  };
1072
1521
 
1073
1522
  const servers = this.sql<MCPServerRow>`
1074
1523
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1075
1524
  `;
1076
1525
 
1077
- for (const server of servers) {
1078
- const serverConn = this.mcp.mcpConnections[server.id];
1079
- mcpState.servers[server.id] = {
1080
- auth_url: server.auth_url,
1081
- capabilities: serverConn?.serverCapabilities ?? null,
1082
- instructions: serverConn?.instructions ?? null,
1083
- name: server.name,
1084
- server_url: server.server_url,
1085
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1086
- state: serverConn?.connectionState ?? "authenticating",
1087
- };
1526
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1527
+ for (const server of servers) {
1528
+ const serverConn = this.mcp.mcpConnections[server.id];
1529
+ mcpState.servers[server.id] = {
1530
+ auth_url: server.auth_url,
1531
+ capabilities: serverConn?.serverCapabilities ?? null,
1532
+ instructions: serverConn?.instructions ?? null,
1533
+ name: server.name,
1534
+ server_url: server.server_url,
1535
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1536
+ state: serverConn?.connectionState ?? "authenticating"
1537
+ };
1538
+ }
1088
1539
  }
1089
1540
 
1090
1541
  return mcpState;
@@ -1131,14 +1582,14 @@ export async function routeAgentRequest<Env>(
1131
1582
  "Access-Control-Allow-Credentials": "true",
1132
1583
  "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1133
1584
  "Access-Control-Allow-Origin": "*",
1134
- "Access-Control-Max-Age": "86400",
1585
+ "Access-Control-Max-Age": "86400"
1135
1586
  }
1136
1587
  : options?.cors;
1137
1588
 
1138
1589
  if (request.method === "OPTIONS") {
1139
1590
  if (corsHeaders) {
1140
1591
  return new Response(null, {
1141
- headers: corsHeaders,
1592
+ headers: corsHeaders
1142
1593
  });
1143
1594
  }
1144
1595
  console.warn(
@@ -1151,7 +1602,7 @@ export async function routeAgentRequest<Env>(
1151
1602
  env as Record<string, unknown>,
1152
1603
  {
1153
1604
  prefix: "agents",
1154
- ...(options as PartyServerOptions<Record<string, unknown>>),
1605
+ ...(options as PartyServerOptions<Record<string, unknown>>)
1155
1606
  }
1156
1607
  );
1157
1608
 
@@ -1164,24 +1615,238 @@ export async function routeAgentRequest<Env>(
1164
1615
  response = new Response(response.body, {
1165
1616
  headers: {
1166
1617
  ...response.headers,
1167
- ...corsHeaders,
1168
- },
1618
+ ...corsHeaders
1619
+ }
1169
1620
  });
1170
1621
  }
1171
1622
  return response;
1172
1623
  }
1173
1624
 
1625
+ export type EmailResolver<Env> = (
1626
+ email: ForwardableEmailMessage,
1627
+ env: Env
1628
+ ) => Promise<{
1629
+ agentName: string;
1630
+ agentId: string;
1631
+ } | null>;
1632
+
1633
+ /**
1634
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1635
+ * @returns A function that resolves the agent to route the email to
1636
+ */
1637
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1638
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1639
+ const messageId = email.headers.get("message-id");
1640
+ if (messageId) {
1641
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1642
+ if (messageIdMatch) {
1643
+ const [, agentId, domain] = messageIdMatch;
1644
+ const agentName = domain.split(".")[0];
1645
+ return { agentName, agentId };
1646
+ }
1647
+ }
1648
+
1649
+ const references = email.headers.get("references");
1650
+ if (references) {
1651
+ const referencesMatch = references.match(
1652
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1653
+ );
1654
+ if (referencesMatch) {
1655
+ const [, base64Id, domain] = referencesMatch;
1656
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1657
+ const agentName = domain.split(".")[0];
1658
+ return { agentName, agentId };
1659
+ }
1660
+ }
1661
+
1662
+ const agentName = email.headers.get("x-agent-name");
1663
+ const agentId = email.headers.get("x-agent-id");
1664
+ if (agentName && agentId) {
1665
+ return { agentName, agentId };
1666
+ }
1667
+
1668
+ return null;
1669
+ };
1670
+ }
1671
+
1672
+ /**
1673
+ * Create a resolver that uses the email address to determine the agent to route the email to
1674
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1675
+ * @returns A function that resolves the agent to route the email to
1676
+ */
1677
+ export function createAddressBasedEmailResolver<Env>(
1678
+ defaultAgentName: string
1679
+ ): EmailResolver<Env> {
1680
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1681
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1682
+ if (!emailMatch) {
1683
+ return null;
1684
+ }
1685
+
1686
+ const [, localPart, subAddress] = emailMatch;
1687
+
1688
+ if (subAddress) {
1689
+ return {
1690
+ agentName: localPart,
1691
+ agentId: subAddress
1692
+ };
1693
+ }
1694
+
1695
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1696
+ // Common for catch-all email routing to a single EmailAgent namespace
1697
+ return {
1698
+ agentName: defaultAgentName,
1699
+ agentId: localPart
1700
+ };
1701
+ };
1702
+ }
1703
+
1704
+ /**
1705
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1706
+ * @param agentName The name of the agent to route the email to
1707
+ * @param agentId The id of the agent to route the email to
1708
+ * @returns A function that resolves the agent to route the email to
1709
+ */
1710
+ export function createCatchAllEmailResolver<Env>(
1711
+ agentName: string,
1712
+ agentId: string
1713
+ ): EmailResolver<Env> {
1714
+ return async () => ({ agentName, agentId });
1715
+ }
1716
+
1717
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1718
+ resolver: EmailResolver<Env>;
1719
+ };
1720
+
1721
+ // Cache the agent namespace map for email routing
1722
+ // This maps both kebab-case and original names to namespaces
1723
+ const agentMapCache = new WeakMap<
1724
+ Record<string, unknown>,
1725
+ Record<string, unknown>
1726
+ >();
1727
+
1174
1728
  /**
1175
1729
  * Route an email to the appropriate Agent
1176
- * @param email Email message to route
1177
- * @param env Environment containing Agent bindings
1178
- * @param options Routing options
1730
+ * @param email The email to route
1731
+ * @param env The environment containing the Agent bindings
1732
+ * @param options The options for routing the email
1733
+ * @returns A promise that resolves when the email has been routed
1179
1734
  */
1180
1735
  export async function routeAgentEmail<Env>(
1181
- _email: ForwardableEmailMessage,
1182
- _env: Env,
1183
- _options?: AgentOptions<Env>
1184
- ): Promise<void> {}
1736
+ email: ForwardableEmailMessage,
1737
+ env: Env,
1738
+ options: EmailRoutingOptions<Env>
1739
+ ): Promise<void> {
1740
+ const routingInfo = await options.resolver(email, env);
1741
+
1742
+ if (!routingInfo) {
1743
+ console.warn("No routing information found for email, dropping message");
1744
+ return;
1745
+ }
1746
+
1747
+ // Build a map that includes both original names and kebab-case versions
1748
+ if (!agentMapCache.has(env as Record<string, unknown>)) {
1749
+ const map: Record<string, unknown> = {};
1750
+ for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1751
+ if (
1752
+ value &&
1753
+ typeof value === "object" &&
1754
+ "idFromName" in value &&
1755
+ typeof value.idFromName === "function"
1756
+ ) {
1757
+ // Add both the original name and kebab-case version
1758
+ map[key] = value;
1759
+ map[camelCaseToKebabCase(key)] = value;
1760
+ }
1761
+ }
1762
+ agentMapCache.set(env as Record<string, unknown>, map);
1763
+ }
1764
+
1765
+ const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
1766
+ const namespace = agentMap[routingInfo.agentName];
1767
+
1768
+ if (!namespace) {
1769
+ // Provide helpful error message listing available agents
1770
+ const availableAgents = Object.keys(agentMap)
1771
+ .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
1772
+ .join(", ");
1773
+ throw new Error(
1774
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1775
+ );
1776
+ }
1777
+
1778
+ const agent = await getAgentByName(
1779
+ namespace as unknown as AgentNamespace<Agent<Env>>,
1780
+ routingInfo.agentId
1781
+ );
1782
+
1783
+ // let's make a serialisable version of the email
1784
+ const serialisableEmail: AgentEmail = {
1785
+ getRaw: async () => {
1786
+ const reader = email.raw.getReader();
1787
+ const chunks: Uint8Array[] = [];
1788
+
1789
+ let done = false;
1790
+ while (!done) {
1791
+ const { value, done: readerDone } = await reader.read();
1792
+ done = readerDone;
1793
+ if (value) {
1794
+ chunks.push(value);
1795
+ }
1796
+ }
1797
+
1798
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1799
+ const combined = new Uint8Array(totalLength);
1800
+ let offset = 0;
1801
+ for (const chunk of chunks) {
1802
+ combined.set(chunk, offset);
1803
+ offset += chunk.length;
1804
+ }
1805
+
1806
+ return combined;
1807
+ },
1808
+ headers: email.headers,
1809
+ rawSize: email.rawSize,
1810
+ setReject: (reason: string) => {
1811
+ email.setReject(reason);
1812
+ },
1813
+ forward: (rcptTo: string, headers?: Headers) => {
1814
+ return email.forward(rcptTo, headers);
1815
+ },
1816
+ reply: (options: { from: string; to: string; raw: string }) => {
1817
+ return email.reply(
1818
+ new EmailMessage(options.from, options.to, options.raw)
1819
+ );
1820
+ },
1821
+ from: email.from,
1822
+ to: email.to
1823
+ };
1824
+
1825
+ await agent._onEmail(serialisableEmail);
1826
+ }
1827
+
1828
+ export type AgentEmail = {
1829
+ from: string;
1830
+ to: string;
1831
+ getRaw: () => Promise<Uint8Array>;
1832
+ headers: Headers;
1833
+ rawSize: number;
1834
+ setReject: (reason: string) => void;
1835
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
1836
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
1837
+ };
1838
+
1839
+ export type EmailSendOptions = {
1840
+ to: string;
1841
+ subject: string;
1842
+ body: string;
1843
+ contentType?: string;
1844
+ headers?: Record<string, string>;
1845
+ includeRoutingHeaders?: boolean;
1846
+ agentName?: string;
1847
+ agentId?: string;
1848
+ domain?: string;
1849
+ };
1185
1850
 
1186
1851
  /**
1187
1852
  * Get or create an Agent by name
@@ -1229,7 +1894,7 @@ export class StreamingResponse {
1229
1894
  id: this._id,
1230
1895
  result: chunk,
1231
1896
  success: true,
1232
- type: "rpc",
1897
+ type: "rpc"
1233
1898
  };
1234
1899
  this._connection.send(JSON.stringify(response));
1235
1900
  }
@@ -1248,7 +1913,7 @@ export class StreamingResponse {
1248
1913
  id: this._id,
1249
1914
  result: finalChunk,
1250
1915
  success: true,
1251
- type: "rpc",
1916
+ type: "rpc"
1252
1917
  };
1253
1918
  this._connection.send(JSON.stringify(response));
1254
1919
  }