agents 0.0.0-9e2f4e7 → 0.0.0-9ef35e2

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