agents 0.0.0-eeb70e2 → 0.0.0-f0c6dce

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