agents 0.0.0-2801d35 → 0.0.0-2a0b252

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