agents 0.0.0-33ff003 → 0.0.0-352d62c

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