agents 0.0.0-569680f → 0.0.0-569e184

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 (84) hide show
  1. package/README.md +257 -27
  2. package/dist/ai-chat-agent.d.ts +104 -20
  3. package/dist/ai-chat-agent.js +812 -260
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
  6. package/dist/ai-chat-v5-migration-DguhuLKF.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +79 -85
  10. package/dist/ai-react.js +411 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-CwgHzwUb.js +24 -0
  13. package/dist/ai-types-CwgHzwUb.js.map +1 -0
  14. package/dist/ai-types-D_hTbf25.d.ts +103 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-CcyhkGfN.js +117 -0
  21. package/dist/client-CcyhkGfN.js.map +1 -0
  22. package/dist/client-ClORm6f0.d.ts +104 -0
  23. package/dist/client-DfIOsabL.d.ts +834 -0
  24. package/dist/client-QZa2Rq0l.js +1105 -0
  25. package/dist/client-QZa2Rq0l.js.map +1 -0
  26. package/dist/client.d.ts +12 -93
  27. package/dist/client.js +4 -11
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +152 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/context-BkKbAa1R.js +8 -0
  32. package/dist/context-BkKbAa1R.js.map +1 -0
  33. package/dist/context-_sPQqJWv.d.ts +24 -0
  34. package/dist/context.d.ts +6 -0
  35. package/dist/context.js +3 -0
  36. package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  38. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  39. package/dist/index-CyDpAVHZ.d.ts +58 -0
  40. package/dist/{index-aBwVVXj7.d.ts → index-DPJ32qQn.d.ts} +219 -171
  41. package/dist/index.d.ts +69 -37
  42. package/dist/index.js +8 -30
  43. package/dist/mcp/client.d.ts +4 -1055
  44. package/dist/mcp/client.js +4 -9
  45. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  46. package/dist/mcp/do-oauth-client-provider.js +3 -7
  47. package/dist/mcp/index.d.ts +191 -81
  48. package/dist/mcp/index.js +1457 -770
  49. package/dist/mcp/index.js.map +1 -1
  50. package/dist/mcp/x402.d.ts +34 -0
  51. package/dist/mcp/x402.js +198 -0
  52. package/dist/mcp/x402.js.map +1 -0
  53. package/dist/mcp-CzbSsLfc.d.ts +61 -0
  54. package/dist/observability/index.d.ts +3 -12
  55. package/dist/observability/index.js +8 -10
  56. package/dist/react-DTzwSLAh.d.ts +137 -0
  57. package/dist/react.d.ts +15 -119
  58. package/dist/react.js +190 -110
  59. package/dist/react.js.map +1 -1
  60. package/dist/schedule.d.ts +91 -14
  61. package/dist/schedule.js +46 -21
  62. package/dist/schedule.js.map +1 -1
  63. package/dist/serializable-C4GLimgv.d.ts +39 -0
  64. package/dist/serializable.d.ts +7 -32
  65. package/dist/serializable.js +1 -1
  66. package/dist/src-BmbDclOA.js +1181 -0
  67. package/dist/src-BmbDclOA.js.map +1 -0
  68. package/package.json +79 -30
  69. package/dist/ai-types.js.map +0 -1
  70. package/dist/chunk-767EASBA.js +0 -106
  71. package/dist/chunk-767EASBA.js.map +0 -1
  72. package/dist/chunk-NKZZ66QY.js +0 -116
  73. package/dist/chunk-NKZZ66QY.js.map +0 -1
  74. package/dist/chunk-RX76B6DL.js +0 -1025
  75. package/dist/chunk-RX76B6DL.js.map +0 -1
  76. package/dist/chunk-TN7QOY4S.js +0 -469
  77. package/dist/chunk-TN7QOY4S.js.map +0 -1
  78. package/dist/client.js.map +0 -1
  79. package/dist/index.js.map +0 -1
  80. package/dist/mcp/client.js.map +0 -1
  81. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  82. package/dist/observability/index.js.map +0 -1
  83. package/dist/serializable.js.map +0 -1
  84. package/src/index.ts +0 -1538
package/src/index.ts DELETED
@@ -1,1538 +0,0 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
- import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
4
-
5
- import type {
6
- Prompt,
7
- Resource,
8
- ServerCapabilities,
9
- Tool,
10
- } from "@modelcontextprotocol/sdk/types.js";
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
- import { EmailMessage } from "cloudflare:email";
14
- import {
15
- type Connection,
16
- type ConnectionContext,
17
- type PartyServerOptions,
18
- Server,
19
- type WSMessage,
20
- getServerByName,
21
- routePartykitRequest,
22
- } from "partyserver";
23
- import { camelCaseToKebabCase } from "./client";
24
- import { MCPClientManager } from "./mcp/client";
25
- // import type { MCPClientConnection } from "./mcp/client-connection";
26
- import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
27
- import { genericObservability, type Observability } from "./observability";
28
-
29
- export type { Connection, ConnectionContext, WSMessage } from "partyserver";
30
-
31
- /**
32
- * RPC request message from client
33
- */
34
- export type RPCRequest = {
35
- type: "rpc";
36
- id: string;
37
- method: string;
38
- args: unknown[];
39
- };
40
-
41
- /**
42
- * State update message from client
43
- */
44
- export type StateUpdateMessage = {
45
- type: "cf_agent_state";
46
- state: unknown;
47
- };
48
-
49
- /**
50
- * RPC response message to client
51
- */
52
- export type RPCResponse = {
53
- type: "rpc";
54
- id: string;
55
- } & (
56
- | {
57
- success: true;
58
- result: unknown;
59
- done?: false;
60
- }
61
- | {
62
- success: true;
63
- result: unknown;
64
- done: true;
65
- }
66
- | {
67
- success: false;
68
- error: string;
69
- }
70
- );
71
-
72
- /**
73
- * Type guard for RPC request messages
74
- */
75
- function isRPCRequest(msg: unknown): msg is RPCRequest {
76
- return (
77
- typeof msg === "object" &&
78
- msg !== null &&
79
- "type" in msg &&
80
- msg.type === "rpc" &&
81
- "id" in msg &&
82
- typeof msg.id === "string" &&
83
- "method" in msg &&
84
- typeof msg.method === "string" &&
85
- "args" in msg &&
86
- Array.isArray((msg as RPCRequest).args)
87
- );
88
- }
89
-
90
- /**
91
- * Type guard for state update messages
92
- */
93
- function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
94
- return (
95
- typeof msg === "object" &&
96
- msg !== null &&
97
- "type" in msg &&
98
- msg.type === "cf_agent_state" &&
99
- "state" in msg
100
- );
101
- }
102
-
103
- /**
104
- * Metadata for a callable method
105
- */
106
- export type CallableMetadata = {
107
- /** Optional description of what the method does */
108
- description?: string;
109
- /** Whether the method supports streaming responses */
110
- streaming?: boolean;
111
- };
112
-
113
- const callableMetadata = new Map<Function, CallableMetadata>();
114
-
115
- /**
116
- * Decorator that marks a method as callable by clients
117
- * @param metadata Optional metadata about the callable method
118
- */
119
- export function unstable_callable(metadata: CallableMetadata = {}) {
120
- return function callableDecorator<This, Args extends unknown[], Return>(
121
- target: (this: This, ...args: Args) => Return,
122
- // biome-ignore lint/correctness/noUnusedFunctionParameters: later
123
- context: ClassMethodDecoratorContext
124
- ) {
125
- if (!callableMetadata.has(target)) {
126
- callableMetadata.set(target, metadata);
127
- }
128
-
129
- return target;
130
- };
131
- }
132
-
133
- /**
134
- * Represents a scheduled task within an Agent
135
- * @template T Type of the payload data
136
- */
137
- export type Schedule<T = string> = {
138
- /** Unique identifier for the schedule */
139
- id: string;
140
- /** Name of the method to be called */
141
- callback: string;
142
- /** Data to be passed to the callback */
143
- payload: T;
144
- } & (
145
- | {
146
- /** Type of schedule for one-time execution at a specific time */
147
- type: "scheduled";
148
- /** Timestamp when the task should execute */
149
- time: number;
150
- }
151
- | {
152
- /** Type of schedule for delayed execution */
153
- type: "delayed";
154
- /** Timestamp when the task should execute */
155
- time: number;
156
- /** Number of seconds to delay execution */
157
- delayInSeconds: number;
158
- }
159
- | {
160
- /** Type of schedule for recurring execution based on cron expression */
161
- type: "cron";
162
- /** Timestamp for the next execution */
163
- time: number;
164
- /** Cron expression defining the schedule */
165
- cron: string;
166
- }
167
- );
168
-
169
- function getNextCronTime(cron: string) {
170
- const interval = parseCronExpression(cron);
171
- return interval.getNextDate();
172
- }
173
-
174
- /**
175
- * MCP Server state update message from server -> Client
176
- */
177
- export type MCPServerMessage = {
178
- type: "cf_agent_mcp_servers";
179
- mcp: MCPServersState;
180
- };
181
-
182
- export type MCPServersState = {
183
- servers: {
184
- [id: string]: MCPServer;
185
- };
186
- tools: Tool[];
187
- prompts: Prompt[];
188
- resources: Resource[];
189
- };
190
-
191
- export type MCPServer = {
192
- name: string;
193
- server_url: string;
194
- auth_url: string | null;
195
- // This state is specifically about the temporary process of getting a token (if needed).
196
- // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
197
- // to communicate a change to a non-ready state.
198
- state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
199
- instructions: string | null;
200
- capabilities: ServerCapabilities | null;
201
- };
202
-
203
- /**
204
- * MCP Server data stored in DO SQL for resuming MCP Server connections
205
- */
206
- type MCPServerRow = {
207
- id: string;
208
- name: string;
209
- server_url: string;
210
- client_id: string | null;
211
- auth_url: string | null;
212
- callback_url: string;
213
- server_options: string;
214
- };
215
-
216
- const STATE_ROW_ID = "cf_state_row_id";
217
- const STATE_WAS_CHANGED = "cf_state_was_changed";
218
-
219
- const DEFAULT_STATE = {} as unknown;
220
-
221
- const agentContext = new AsyncLocalStorage<{
222
- agent: Agent<unknown>;
223
- connection: Connection | undefined;
224
- request: Request | undefined;
225
- }>();
226
-
227
- export function getCurrentAgent<
228
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
229
- >(): {
230
- agent: T | undefined;
231
- connection: Connection | undefined;
232
- request: Request<unknown, CfProperties<unknown>> | undefined;
233
- } {
234
- const store = agentContext.getStore() as
235
- | {
236
- agent: T;
237
- connection: Connection | undefined;
238
- request: Request<unknown, CfProperties<unknown>> | undefined;
239
- }
240
- | undefined;
241
- if (!store) {
242
- return {
243
- agent: undefined,
244
- connection: undefined,
245
- request: undefined,
246
- };
247
- }
248
- return store;
249
- }
250
-
251
- /**
252
- * Base class for creating Agent implementations
253
- * @template Env Environment type containing bindings
254
- * @template State State type to store within the Agent
255
- */
256
- export class Agent<Env, State = unknown> extends Server<Env> {
257
- private _state = DEFAULT_STATE as State;
258
-
259
- private _ParentClass: typeof Agent<Env, State> =
260
- Object.getPrototypeOf(this).constructor;
261
-
262
- mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
263
-
264
- /**
265
- * Initial state for the Agent
266
- * Override to provide default state values
267
- */
268
- initialState: State = DEFAULT_STATE as State;
269
-
270
- /**
271
- * Current state of the Agent
272
- */
273
- get state(): State {
274
- if (this._state !== DEFAULT_STATE) {
275
- // state was previously set, and populated internal state
276
- return this._state;
277
- }
278
- // looks like this is the first time the state is being accessed
279
- // check if the state was set in a previous life
280
- const wasChanged = this.sql<{ state: "true" | undefined }>`
281
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
282
- `;
283
-
284
- // ok, let's pick up the actual state from the db
285
- const result = this.sql<{ state: State | undefined }>`
286
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
287
- `;
288
-
289
- if (
290
- wasChanged[0]?.state === "true" ||
291
- // we do this check for people who updated their code before we shipped wasChanged
292
- result[0]?.state
293
- ) {
294
- const state = result[0]?.state as string; // could be null?
295
-
296
- this._state = JSON.parse(state);
297
- return this._state;
298
- }
299
-
300
- // ok, this is the first time the state is being accessed
301
- // and the state was not set in a previous life
302
- // so we need to set the initial state (if provided)
303
- if (this.initialState === DEFAULT_STATE) {
304
- // no initial state provided, so we return undefined
305
- return undefined as State;
306
- }
307
- // initial state provided, so we set the state,
308
- // update db and return the initial state
309
- this.setState(this.initialState);
310
- return this.initialState;
311
- }
312
-
313
- /**
314
- * Agent configuration options
315
- */
316
- static options = {
317
- /** Whether the Agent should hibernate when inactive */
318
- hibernate: true, // default to hibernate
319
- };
320
-
321
- /**
322
- * The observability implementation to use for the Agent
323
- */
324
- observability?: Observability = genericObservability;
325
-
326
- /**
327
- * Execute SQL queries against the Agent's database
328
- * @template T Type of the returned rows
329
- * @param strings SQL query template strings
330
- * @param values Values to be inserted into the query
331
- * @returns Array of query results
332
- */
333
- sql<T = Record<string, string | number | boolean | null>>(
334
- strings: TemplateStringsArray,
335
- ...values: (string | number | boolean | null)[]
336
- ) {
337
- let query = "";
338
- try {
339
- // Construct the SQL query with placeholders
340
- query = strings.reduce(
341
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
342
- ""
343
- );
344
-
345
- // Execute the SQL query with the provided values
346
- return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
347
- } catch (e) {
348
- console.error(`failed to execute sql query: ${query}`, e);
349
- throw this.onError(e);
350
- }
351
- }
352
- constructor(ctx: AgentContext, env: Env) {
353
- super(ctx, env);
354
-
355
- this.sql`
356
- CREATE TABLE IF NOT EXISTS cf_agents_state (
357
- id TEXT PRIMARY KEY NOT NULL,
358
- state TEXT
359
- )
360
- `;
361
-
362
- void this.ctx.blockConcurrencyWhile(async () => {
363
- return this._tryCatch(async () => {
364
- // Create alarms table if it doesn't exist
365
- this.sql`
366
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
367
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
368
- callback TEXT,
369
- payload TEXT,
370
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
371
- time INTEGER,
372
- delayInSeconds INTEGER,
373
- cron TEXT,
374
- created_at INTEGER DEFAULT (unixepoch())
375
- )
376
- `;
377
-
378
- // execute any pending alarms and schedule the next alarm
379
- await this.alarm();
380
- });
381
- });
382
-
383
- this.sql`
384
- CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
385
- id TEXT PRIMARY KEY NOT NULL,
386
- name TEXT NOT NULL,
387
- server_url TEXT NOT NULL,
388
- callback_url TEXT NOT NULL,
389
- client_id TEXT,
390
- auth_url TEXT,
391
- server_options TEXT
392
- )
393
- `;
394
-
395
- const _onRequest = this.onRequest.bind(this);
396
- this.onRequest = (request: Request) => {
397
- return agentContext.run(
398
- { agent: this, connection: undefined, request },
399
- async () => {
400
- if (this.mcp.isCallbackRequest(request)) {
401
- await this.mcp.handleCallbackRequest(request);
402
-
403
- // after the MCP connection handshake, we can send updated mcp state
404
- this.broadcast(
405
- JSON.stringify({
406
- mcp: this.getMcpServers(),
407
- type: "cf_agent_mcp_servers",
408
- })
409
- );
410
-
411
- // We probably should let the user configure this response/redirect, but this is fine for now.
412
- return new Response("<script>window.close();</script>", {
413
- headers: { "content-type": "text/html" },
414
- status: 200,
415
- });
416
- }
417
-
418
- return this._tryCatch(() => _onRequest(request));
419
- }
420
- );
421
- };
422
-
423
- const _onMessage = this.onMessage.bind(this);
424
- this.onMessage = async (connection: Connection, message: WSMessage) => {
425
- return agentContext.run(
426
- { agent: this, connection, request: undefined },
427
- async () => {
428
- if (typeof message !== "string") {
429
- return this._tryCatch(() => _onMessage(connection, message));
430
- }
431
-
432
- let parsed: unknown;
433
- try {
434
- parsed = JSON.parse(message);
435
- } catch (_e) {
436
- // silently fail and let the onMessage handler handle it
437
- return this._tryCatch(() => _onMessage(connection, message));
438
- }
439
-
440
- if (isStateUpdateMessage(parsed)) {
441
- this._setStateInternal(parsed.state as State, connection);
442
- return;
443
- }
444
-
445
- if (isRPCRequest(parsed)) {
446
- try {
447
- const { id, method, args } = parsed;
448
-
449
- // Check if method exists and is callable
450
- const methodFn = this[method as keyof this];
451
- if (typeof methodFn !== "function") {
452
- throw new Error(`Method ${method} does not exist`);
453
- }
454
-
455
- if (!this._isCallable(method)) {
456
- throw new Error(`Method ${method} is not callable`);
457
- }
458
-
459
- const metadata = callableMetadata.get(methodFn as Function);
460
-
461
- // For streaming methods, pass a StreamingResponse object
462
- if (metadata?.streaming) {
463
- const stream = new StreamingResponse(connection, id);
464
- await methodFn.apply(this, [stream, ...args]);
465
- return;
466
- }
467
-
468
- // For regular methods, execute and send response
469
- const result = await methodFn.apply(this, args);
470
-
471
- this.observability?.emit(
472
- {
473
- displayMessage: `RPC call to ${method}`,
474
- id: nanoid(),
475
- payload: {
476
- args,
477
- method,
478
- streaming: metadata?.streaming,
479
- success: true,
480
- },
481
- timestamp: Date.now(),
482
- type: "rpc",
483
- },
484
- this.ctx
485
- );
486
-
487
- const response: RPCResponse = {
488
- done: true,
489
- id,
490
- result,
491
- success: true,
492
- type: "rpc",
493
- };
494
- connection.send(JSON.stringify(response));
495
- } catch (e) {
496
- // Send error response
497
- const response: RPCResponse = {
498
- error:
499
- e instanceof Error ? e.message : "Unknown error occurred",
500
- id: parsed.id,
501
- success: false,
502
- type: "rpc",
503
- };
504
- connection.send(JSON.stringify(response));
505
- console.error("RPC error:", e);
506
- }
507
- return;
508
- }
509
-
510
- return this._tryCatch(() => _onMessage(connection, message));
511
- }
512
- );
513
- };
514
-
515
- const _onConnect = this.onConnect.bind(this);
516
- this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
517
- // TODO: This is a hack to ensure the state is sent after the connection is established
518
- // must fix this
519
- return agentContext.run(
520
- { agent: this, connection, request: ctx.request },
521
- async () => {
522
- setTimeout(() => {
523
- if (this.state) {
524
- connection.send(
525
- JSON.stringify({
526
- state: this.state,
527
- type: "cf_agent_state",
528
- })
529
- );
530
- }
531
-
532
- connection.send(
533
- JSON.stringify({
534
- mcp: this.getMcpServers(),
535
- type: "cf_agent_mcp_servers",
536
- })
537
- );
538
-
539
- this.observability?.emit(
540
- {
541
- displayMessage: "Connection established",
542
- id: nanoid(),
543
- payload: {
544
- connectionId: connection.id,
545
- },
546
- timestamp: Date.now(),
547
- type: "connect",
548
- },
549
- this.ctx
550
- );
551
- return this._tryCatch(() => _onConnect(connection, ctx));
552
- }, 20);
553
- }
554
- );
555
- };
556
-
557
- const _onStart = this.onStart.bind(this);
558
- this.onStart = async () => {
559
- return agentContext.run(
560
- { agent: this, connection: undefined, request: undefined },
561
- async () => {
562
- const servers = this.sql<MCPServerRow>`
563
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
564
- `;
565
-
566
- // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
567
- Promise.allSettled(
568
- servers.map((server) => {
569
- return this._connectToMcpServerInternal(
570
- server.name,
571
- server.server_url,
572
- server.callback_url,
573
- server.server_options
574
- ? JSON.parse(server.server_options)
575
- : undefined,
576
- {
577
- id: server.id,
578
- oauthClientId: server.client_id ?? undefined,
579
- }
580
- );
581
- })
582
- ).then((_results) => {
583
- this.broadcast(
584
- JSON.stringify({
585
- mcp: this.getMcpServers(),
586
- type: "cf_agent_mcp_servers",
587
- })
588
- );
589
- });
590
- await this._tryCatch(() => _onStart());
591
- }
592
- );
593
- };
594
- }
595
-
596
- private _setStateInternal(
597
- state: State,
598
- source: Connection | "server" = "server"
599
- ) {
600
- const previousState = this._state;
601
- this._state = state;
602
- this.sql`
603
- INSERT OR REPLACE INTO cf_agents_state (id, state)
604
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
605
- `;
606
- this.sql`
607
- INSERT OR REPLACE INTO cf_agents_state (id, state)
608
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
609
- `;
610
- this.broadcast(
611
- JSON.stringify({
612
- state: state,
613
- type: "cf_agent_state",
614
- }),
615
- source !== "server" ? [source.id] : []
616
- );
617
- return this._tryCatch(() => {
618
- const { connection, request } = agentContext.getStore() || {};
619
- return agentContext.run(
620
- { agent: this, connection, request },
621
- async () => {
622
- this.observability?.emit(
623
- {
624
- displayMessage: "State updated",
625
- id: nanoid(),
626
- payload: {
627
- previousState,
628
- state,
629
- },
630
- timestamp: Date.now(),
631
- type: "state:update",
632
- },
633
- this.ctx
634
- );
635
- return this.onStateUpdate(state, source);
636
- }
637
- );
638
- });
639
- }
640
-
641
- /**
642
- * Update the Agent's state
643
- * @param state New state to set
644
- */
645
- setState(state: State) {
646
- this._setStateInternal(state, "server");
647
- }
648
-
649
- /**
650
- * Called when the Agent's state is updated
651
- * @param state Updated state
652
- * @param source Source of the state update ("server" or a client connection)
653
- */
654
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
655
- onStateUpdate(state: State | undefined, source: Connection | "server") {
656
- // override this to handle state updates
657
- }
658
-
659
- /**
660
- * Called when the Agent receives an email
661
- * Override this method to handle incoming emails
662
- * @param email Email message to process
663
- */
664
- async onEmail(email: ForwardableEmailMessage) {
665
- return agentContext.run(
666
- { agent: this, connection: undefined, request: undefined },
667
- async () => {
668
- console.log("Received email from:", email.from, "to:", email.to);
669
- console.log("Subject:", email.headers.get("subject"));
670
- console.log("Override onEmail() in your agent to process emails");
671
- }
672
- );
673
- }
674
-
675
- async sendEmail(
676
- emailBinding: SendEmail,
677
- from: string,
678
- fromName: string,
679
- options: Omit<EmailSendOptions, "agentName" | "agentId">
680
- ): Promise<void> {
681
- const agentName = camelCaseToKebabCase(this._ParentClass.name);
682
- const agentId = this.name;
683
-
684
- return sendEmailWithRouting(emailBinding, from, fromName, {
685
- ...options,
686
- agentName,
687
- agentId,
688
- includeRoutingHeaders: true,
689
- });
690
- }
691
-
692
- private async _tryCatch<T>(fn: () => T | Promise<T>) {
693
- try {
694
- return await fn();
695
- } catch (e) {
696
- throw this.onError(e);
697
- }
698
- }
699
-
700
- override onError(
701
- connection: Connection,
702
- error: unknown
703
- ): void | Promise<void>;
704
- override onError(error: unknown): void | Promise<void>;
705
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
706
- let theError: unknown;
707
- if (connectionOrError && error) {
708
- theError = error;
709
- // this is a websocket connection error
710
- console.error(
711
- "Error on websocket connection:",
712
- (connectionOrError as Connection).id,
713
- theError
714
- );
715
- console.error(
716
- "Override onError(connection, error) to handle websocket connection errors"
717
- );
718
- } else {
719
- theError = connectionOrError;
720
- // this is a server error
721
- console.error("Error on server:", theError);
722
- console.error("Override onError(error) to handle server errors");
723
- }
724
- throw theError;
725
- }
726
-
727
- /**
728
- * Render content (not implemented in base class)
729
- */
730
- render() {
731
- throw new Error("Not implemented");
732
- }
733
-
734
- /**
735
- * Schedule a task to be executed in the future
736
- * @template T Type of the payload data
737
- * @param when When to execute the task (Date, seconds delay, or cron expression)
738
- * @param callback Name of the method to call
739
- * @param payload Data to pass to the callback
740
- * @returns Schedule object representing the scheduled task
741
- */
742
- async schedule<T = string>(
743
- when: Date | string | number,
744
- callback: keyof this,
745
- payload?: T
746
- ): Promise<Schedule<T>> {
747
- const id = nanoid(9);
748
-
749
- const emitScheduleCreate = (schedule: Schedule<T>) =>
750
- this.observability?.emit(
751
- {
752
- displayMessage: `Schedule ${schedule.id} created`,
753
- id: nanoid(),
754
- payload: schedule,
755
- timestamp: Date.now(),
756
- type: "schedule:create",
757
- },
758
- this.ctx
759
- );
760
-
761
- if (typeof callback !== "string") {
762
- throw new Error("Callback must be a string");
763
- }
764
-
765
- if (typeof this[callback] !== "function") {
766
- throw new Error(`this.${callback} is not a function`);
767
- }
768
-
769
- if (when instanceof Date) {
770
- const timestamp = Math.floor(when.getTime() / 1000);
771
- this.sql`
772
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
773
- VALUES (${id}, ${callback}, ${JSON.stringify(
774
- payload
775
- )}, 'scheduled', ${timestamp})
776
- `;
777
-
778
- await this._scheduleNextAlarm();
779
-
780
- const schedule: Schedule<T> = {
781
- callback: callback,
782
- id,
783
- payload: payload as T,
784
- time: timestamp,
785
- type: "scheduled",
786
- };
787
-
788
- emitScheduleCreate(schedule);
789
-
790
- return schedule;
791
- }
792
- if (typeof when === "number") {
793
- const time = new Date(Date.now() + when * 1000);
794
- const timestamp = Math.floor(time.getTime() / 1000);
795
-
796
- this.sql`
797
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
798
- VALUES (${id}, ${callback}, ${JSON.stringify(
799
- payload
800
- )}, 'delayed', ${when}, ${timestamp})
801
- `;
802
-
803
- await this._scheduleNextAlarm();
804
-
805
- const schedule: Schedule<T> = {
806
- callback: callback,
807
- delayInSeconds: when,
808
- id,
809
- payload: payload as T,
810
- time: timestamp,
811
- type: "delayed",
812
- };
813
-
814
- emitScheduleCreate(schedule);
815
-
816
- return schedule;
817
- }
818
- if (typeof when === "string") {
819
- const nextExecutionTime = getNextCronTime(when);
820
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
821
-
822
- this.sql`
823
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
824
- VALUES (${id}, ${callback}, ${JSON.stringify(
825
- payload
826
- )}, 'cron', ${when}, ${timestamp})
827
- `;
828
-
829
- await this._scheduleNextAlarm();
830
-
831
- const schedule: Schedule<T> = {
832
- callback: callback,
833
- cron: when,
834
- id,
835
- payload: payload as T,
836
- time: timestamp,
837
- type: "cron",
838
- };
839
-
840
- emitScheduleCreate(schedule);
841
-
842
- return schedule;
843
- }
844
- throw new Error("Invalid schedule type");
845
- }
846
-
847
- /**
848
- * Get a scheduled task by ID
849
- * @template T Type of the payload data
850
- * @param id ID of the scheduled task
851
- * @returns The Schedule object or undefined if not found
852
- */
853
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
854
- const result = this.sql<Schedule<string>>`
855
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
856
- `;
857
- if (!result) {
858
- console.error(`schedule ${id} not found`);
859
- return undefined;
860
- }
861
-
862
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
863
- }
864
-
865
- /**
866
- * Get scheduled tasks matching the given criteria
867
- * @template T Type of the payload data
868
- * @param criteria Criteria to filter schedules
869
- * @returns Array of matching Schedule objects
870
- */
871
- getSchedules<T = string>(
872
- criteria: {
873
- id?: string;
874
- type?: "scheduled" | "delayed" | "cron";
875
- timeRange?: { start?: Date; end?: Date };
876
- } = {}
877
- ): Schedule<T>[] {
878
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
879
- const params = [];
880
-
881
- if (criteria.id) {
882
- query += " AND id = ?";
883
- params.push(criteria.id);
884
- }
885
-
886
- if (criteria.type) {
887
- query += " AND type = ?";
888
- params.push(criteria.type);
889
- }
890
-
891
- if (criteria.timeRange) {
892
- query += " AND time >= ? AND time <= ?";
893
- const start = criteria.timeRange.start || new Date(0);
894
- const end = criteria.timeRange.end || new Date(999999999999999);
895
- params.push(
896
- Math.floor(start.getTime() / 1000),
897
- Math.floor(end.getTime() / 1000)
898
- );
899
- }
900
-
901
- const result = this.ctx.storage.sql
902
- .exec(query, ...params)
903
- .toArray()
904
- .map((row) => ({
905
- ...row,
906
- payload: JSON.parse(row.payload as string) as T,
907
- })) as Schedule<T>[];
908
-
909
- return result;
910
- }
911
-
912
- /**
913
- * Cancel a scheduled task
914
- * @param id ID of the task to cancel
915
- * @returns true if the task was cancelled, false otherwise
916
- */
917
- async cancelSchedule(id: string): Promise<boolean> {
918
- const schedule = await this.getSchedule(id);
919
- if (schedule) {
920
- this.observability?.emit(
921
- {
922
- displayMessage: `Schedule ${id} cancelled`,
923
- id: nanoid(),
924
- payload: schedule,
925
- timestamp: Date.now(),
926
- type: "schedule:cancel",
927
- },
928
- this.ctx
929
- );
930
- }
931
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
932
-
933
- await this._scheduleNextAlarm();
934
- return true;
935
- }
936
-
937
- private async _scheduleNextAlarm() {
938
- // Find the next schedule that needs to be executed
939
- const result = this.sql`
940
- SELECT time FROM cf_agents_schedules
941
- WHERE time > ${Math.floor(Date.now() / 1000)}
942
- ORDER BY time ASC
943
- LIMIT 1
944
- `;
945
- if (!result) return;
946
-
947
- if (result.length > 0 && "time" in result[0]) {
948
- const nextTime = (result[0].time as number) * 1000;
949
- await this.ctx.storage.setAlarm(nextTime);
950
- }
951
- }
952
-
953
- /**
954
- * Method called when an alarm fires.
955
- * Executes any scheduled tasks that are due.
956
- *
957
- * @remarks
958
- * To schedule a task, please use the `this.schedule` method instead.
959
- * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
960
- */
961
- public readonly alarm = async () => {
962
- const now = Math.floor(Date.now() / 1000);
963
-
964
- // Get all schedules that should be executed now
965
- const result = this.sql<Schedule<string>>`
966
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
967
- `;
968
-
969
- for (const row of result || []) {
970
- const callback = this[row.callback as keyof Agent<Env>];
971
- if (!callback) {
972
- console.error(`callback ${row.callback} not found`);
973
- continue;
974
- }
975
- await agentContext.run(
976
- { agent: this, connection: undefined, request: undefined },
977
- async () => {
978
- try {
979
- this.observability?.emit(
980
- {
981
- displayMessage: `Schedule ${row.id} executed`,
982
- id: nanoid(),
983
- payload: row,
984
- timestamp: Date.now(),
985
- type: "schedule:execute",
986
- },
987
- this.ctx
988
- );
989
-
990
- await (
991
- callback as (
992
- payload: unknown,
993
- schedule: Schedule<unknown>
994
- ) => Promise<void>
995
- ).bind(this)(JSON.parse(row.payload as string), row);
996
- } catch (e) {
997
- console.error(`error executing callback "${row.callback}"`, e);
998
- }
999
- }
1000
- );
1001
- if (row.type === "cron") {
1002
- // Update next execution time for cron schedules
1003
- const nextExecutionTime = getNextCronTime(row.cron);
1004
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1005
-
1006
- this.sql`
1007
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1008
- `;
1009
- } else {
1010
- // Delete one-time schedules after execution
1011
- this.sql`
1012
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1013
- `;
1014
- }
1015
- }
1016
-
1017
- // Schedule the next alarm
1018
- await this._scheduleNextAlarm();
1019
- };
1020
-
1021
- /**
1022
- * Destroy the Agent, removing all state and scheduled tasks
1023
- */
1024
- async destroy() {
1025
- // drop all tables
1026
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
1027
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1028
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1029
-
1030
- // delete all alarms
1031
- await this.ctx.storage.deleteAlarm();
1032
- await this.ctx.storage.deleteAll();
1033
- this.ctx.abort("destroyed"); // enforce that the agent is evicted
1034
-
1035
- this.observability?.emit(
1036
- {
1037
- displayMessage: "Agent destroyed",
1038
- id: nanoid(),
1039
- payload: {},
1040
- timestamp: Date.now(),
1041
- type: "destroy",
1042
- },
1043
- this.ctx
1044
- );
1045
- }
1046
-
1047
- /**
1048
- * Get all methods marked as callable on this Agent
1049
- * @returns A map of method names to their metadata
1050
- */
1051
- private _isCallable(method: string): boolean {
1052
- return callableMetadata.has(this[method as keyof this] as Function);
1053
- }
1054
-
1055
- /**
1056
- * Connect to a new MCP Server
1057
- *
1058
- * @param url MCP Server SSE URL
1059
- * @param callbackHost Base host for the agent, used for the redirect URI.
1060
- * @param agentsPrefix agents routing prefix if not using `agents`
1061
- * @param options MCP client and transport (header) options
1062
- * @returns authUrl
1063
- */
1064
- async addMcpServer(
1065
- serverName: string,
1066
- url: string,
1067
- callbackHost: string,
1068
- agentsPrefix = "agents",
1069
- options?: {
1070
- client?: ConstructorParameters<typeof Client>[1];
1071
- transport?: {
1072
- headers: HeadersInit;
1073
- };
1074
- }
1075
- ): Promise<{ id: string; authUrl: string | undefined }> {
1076
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1077
-
1078
- const result = await this._connectToMcpServerInternal(
1079
- serverName,
1080
- url,
1081
- callbackUrl,
1082
- options
1083
- );
1084
- this.sql`
1085
- INSERT
1086
- OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1087
- VALUES (
1088
- ${result.id},
1089
- ${serverName},
1090
- ${url},
1091
- ${result.clientId ?? null},
1092
- ${result.authUrl ?? null},
1093
- ${callbackUrl},
1094
- ${options ? JSON.stringify(options) : null}
1095
- );
1096
- `;
1097
-
1098
- this.broadcast(
1099
- JSON.stringify({
1100
- mcp: this.getMcpServers(),
1101
- type: "cf_agent_mcp_servers",
1102
- })
1103
- );
1104
-
1105
- return result;
1106
- }
1107
-
1108
- async _connectToMcpServerInternal(
1109
- _serverName: string,
1110
- url: string,
1111
- callbackUrl: string,
1112
- // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
1113
- options?: {
1114
- client?: ConstructorParameters<typeof Client>[1];
1115
- /**
1116
- * We don't expose the normal set of transport options because:
1117
- * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
1118
- * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
1119
- *
1120
- * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
1121
- */
1122
- transport?: {
1123
- headers?: HeadersInit;
1124
- };
1125
- },
1126
- reconnect?: {
1127
- id: string;
1128
- oauthClientId?: string;
1129
- }
1130
- ): Promise<{
1131
- id: string;
1132
- authUrl: string | undefined;
1133
- clientId: string | undefined;
1134
- }> {
1135
- const authProvider = new DurableObjectOAuthClientProvider(
1136
- this.ctx.storage,
1137
- this.name,
1138
- callbackUrl
1139
- );
1140
-
1141
- if (reconnect) {
1142
- authProvider.serverId = reconnect.id;
1143
- if (reconnect.oauthClientId) {
1144
- authProvider.clientId = reconnect.oauthClientId;
1145
- }
1146
- }
1147
-
1148
- // allows passing through transport headers if necessary
1149
- // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1150
- let headerTransportOpts: SSEClientTransportOptions = {};
1151
- if (options?.transport?.headers) {
1152
- headerTransportOpts = {
1153
- eventSourceInit: {
1154
- fetch: (url, init) =>
1155
- fetch(url, {
1156
- ...init,
1157
- headers: options?.transport?.headers,
1158
- }),
1159
- },
1160
- requestInit: {
1161
- headers: options?.transport?.headers,
1162
- },
1163
- };
1164
- }
1165
-
1166
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
1167
- client: options?.client,
1168
- reconnect,
1169
- transport: {
1170
- ...headerTransportOpts,
1171
- authProvider,
1172
- },
1173
- });
1174
-
1175
- return {
1176
- authUrl,
1177
- clientId,
1178
- id,
1179
- };
1180
- }
1181
-
1182
- async removeMcpServer(id: string) {
1183
- this.mcp.closeConnection(id);
1184
- this.sql`
1185
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1186
- `;
1187
- this.broadcast(
1188
- JSON.stringify({
1189
- mcp: this.getMcpServers(),
1190
- type: "cf_agent_mcp_servers",
1191
- })
1192
- );
1193
- }
1194
-
1195
- getMcpServers(): MCPServersState {
1196
- const mcpState: MCPServersState = {
1197
- prompts: this.mcp.listPrompts(),
1198
- resources: this.mcp.listResources(),
1199
- servers: {},
1200
- tools: this.mcp.listTools(),
1201
- };
1202
-
1203
- const servers = this.sql<MCPServerRow>`
1204
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1205
- `;
1206
-
1207
- for (const server of servers) {
1208
- const serverConn = this.mcp.mcpConnections[server.id];
1209
- mcpState.servers[server.id] = {
1210
- auth_url: server.auth_url,
1211
- capabilities: serverConn?.serverCapabilities ?? null,
1212
- instructions: serverConn?.instructions ?? null,
1213
- name: server.name,
1214
- server_url: server.server_url,
1215
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1216
- state: serverConn?.connectionState ?? "authenticating",
1217
- };
1218
- }
1219
-
1220
- return mcpState;
1221
- }
1222
- }
1223
-
1224
- /**
1225
- * Namespace for creating Agent instances
1226
- * @template Agentic Type of the Agent class
1227
- */
1228
- export type AgentNamespace<Agentic extends Agent<unknown>> =
1229
- DurableObjectNamespace<Agentic>;
1230
-
1231
- /**
1232
- * Agent's durable context
1233
- */
1234
- export type AgentContext = DurableObjectState;
1235
-
1236
- /**
1237
- * Configuration options for Agent routing
1238
- */
1239
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
1240
- /**
1241
- * Whether to enable CORS for the Agent
1242
- */
1243
- cors?: boolean | HeadersInit | undefined;
1244
- };
1245
-
1246
- /**
1247
- * Route a request to the appropriate Agent
1248
- * @param request Request to route
1249
- * @param env Environment containing Agent bindings
1250
- * @param options Routing options
1251
- * @returns Response from the Agent or undefined if no route matched
1252
- */
1253
- export async function routeAgentRequest<Env>(
1254
- request: Request,
1255
- env: Env,
1256
- options?: AgentOptions<Env>
1257
- ) {
1258
- const corsHeaders =
1259
- options?.cors === true
1260
- ? {
1261
- "Access-Control-Allow-Credentials": "true",
1262
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1263
- "Access-Control-Allow-Origin": "*",
1264
- "Access-Control-Max-Age": "86400",
1265
- }
1266
- : options?.cors;
1267
-
1268
- if (request.method === "OPTIONS") {
1269
- if (corsHeaders) {
1270
- return new Response(null, {
1271
- headers: corsHeaders,
1272
- });
1273
- }
1274
- console.warn(
1275
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1276
- );
1277
- }
1278
-
1279
- let response = await routePartykitRequest(
1280
- request,
1281
- env as Record<string, unknown>,
1282
- {
1283
- prefix: "agents",
1284
- ...(options as PartyServerOptions<Record<string, unknown>>),
1285
- }
1286
- );
1287
-
1288
- if (
1289
- response &&
1290
- corsHeaders &&
1291
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
1292
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
1293
- ) {
1294
- response = new Response(response.body, {
1295
- headers: {
1296
- ...response.headers,
1297
- ...corsHeaders,
1298
- },
1299
- });
1300
- }
1301
- return response;
1302
- }
1303
-
1304
- export type EmailResolver<Env> = (
1305
- email: ForwardableEmailMessage,
1306
- env: Env
1307
- ) => Promise<{
1308
- agentName: string;
1309
- agentId: string;
1310
- } | null>;
1311
-
1312
- export function createHeaderBasedResolver<Env>(): EmailResolver<Env> {
1313
- return async (email: ForwardableEmailMessage, _env: Env) => {
1314
- const messageId = email.headers.get("message-id");
1315
- if (messageId) {
1316
- const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1317
- if (messageIdMatch) {
1318
- const [, agentId, domain] = messageIdMatch;
1319
- const agentName = domain.split(".")[0];
1320
- return { agentName, agentId };
1321
- }
1322
- }
1323
-
1324
- const references = email.headers.get("references");
1325
- if (references) {
1326
- const referencesMatch = references.match(
1327
- /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1328
- );
1329
- if (referencesMatch) {
1330
- const [, base64Id, domain] = referencesMatch;
1331
- const agentId = Buffer.from(base64Id, "base64").toString("hex");
1332
- const agentName = domain.split(".")[0];
1333
- return { agentName, agentId };
1334
- }
1335
- }
1336
-
1337
- const agentName = email.headers.get("x-agent-name");
1338
- const agentId = email.headers.get("x-agent-id");
1339
- if (agentName && agentId) {
1340
- return { agentName, agentId };
1341
- }
1342
-
1343
- return null;
1344
- };
1345
- }
1346
-
1347
- export function createAddressBasedResolver<Env>(
1348
- defaultAgentName: string
1349
- ): EmailResolver<Env> {
1350
- return async (email: ForwardableEmailMessage, _env: Env) => {
1351
- const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1352
- if (!emailMatch) {
1353
- return null;
1354
- }
1355
-
1356
- const [, localPart, subAddress] = emailMatch;
1357
-
1358
- if (subAddress) {
1359
- return {
1360
- agentName: localPart,
1361
- agentId: subAddress,
1362
- };
1363
- }
1364
-
1365
- // Option 2: Use defaultAgentName namespace, localPart as agentId
1366
- // Common for catch-all email routing to a single EmailAgent namespace
1367
- return {
1368
- agentName: defaultAgentName,
1369
- agentId: localPart,
1370
- };
1371
- };
1372
- }
1373
-
1374
- export function createCatchAllResolver<Env>(
1375
- agentName: string,
1376
- agentId: string
1377
- ): EmailResolver<Env> {
1378
- return async () => ({ agentName, agentId });
1379
- }
1380
-
1381
- export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1382
- resolver: EmailResolver<Env>;
1383
- };
1384
-
1385
- export async function routeAgentEmail<Env>(
1386
- email: ForwardableEmailMessage,
1387
- env: Env,
1388
- options: EmailRoutingOptions<Env>
1389
- ): Promise<void> {
1390
- const routingInfo = await options.resolver(email, env);
1391
-
1392
- if (!routingInfo) {
1393
- console.warn("No routing information found for email, dropping message");
1394
- return;
1395
- }
1396
-
1397
- const namespaceBinding = env[routingInfo.agentName as keyof Env];
1398
- if (!namespaceBinding) {
1399
- console.error(
1400
- `Agent namespace '${routingInfo.agentName}' not found in environment`
1401
- );
1402
- return;
1403
- }
1404
-
1405
- // Type guard to check if this is actually a DurableObjectNamespace (AgentNamespace)
1406
- if (
1407
- typeof namespaceBinding !== "object" ||
1408
- !("idFromName" in namespaceBinding) ||
1409
- typeof namespaceBinding.idFromName !== "function"
1410
- ) {
1411
- console.error(
1412
- `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1413
- );
1414
- return;
1415
- }
1416
-
1417
- // Safe cast after runtime validation
1418
- const namespace = namespaceBinding as unknown as AgentNamespace<Agent<Env>>;
1419
-
1420
- const agent = await getAgentByName(namespace, routingInfo.agentId);
1421
- await agent.onEmail(email);
1422
- }
1423
-
1424
- export type EmailSendOptions = {
1425
- to: string;
1426
- subject: string;
1427
- body: string;
1428
- contentType?: string;
1429
- headers?: Record<string, string>;
1430
- includeRoutingHeaders?: boolean;
1431
- agentName?: string;
1432
- agentId?: string;
1433
- domain?: string;
1434
- };
1435
-
1436
- export async function sendEmailWithRouting(
1437
- emailBinding: SendEmail,
1438
- from: string,
1439
- fromName: string,
1440
- options: EmailSendOptions
1441
- ): Promise<void> {
1442
- const { createMimeMessage } = await import("mimetext");
1443
- const msg = createMimeMessage();
1444
- msg.setSender({ addr: from, name: fromName });
1445
- msg.setRecipient(options.to);
1446
- msg.setSubject(options.subject);
1447
- msg.addMessage({
1448
- contentType: options.contentType || "text/plain",
1449
- data: options.body,
1450
- });
1451
-
1452
- if (options.includeRoutingHeaders && options.agentName && options.agentId) {
1453
- const domain = options.domain || from.split("@")[1];
1454
- const messageId = `<${options.agentId}@${domain}>`;
1455
- msg.setHeader("Message-ID", messageId);
1456
- msg.setHeader("X-Agent-Name", options.agentName);
1457
- msg.setHeader("X-Agent-ID", options.agentId);
1458
- }
1459
-
1460
- if (options.headers) {
1461
- for (const [key, value] of Object.entries(options.headers)) {
1462
- msg.setHeader(key, value);
1463
- }
1464
- }
1465
-
1466
- await emailBinding.send(new EmailMessage(from, options.to, msg.asRaw()));
1467
- }
1468
-
1469
- /**
1470
- * Get or create an Agent by name
1471
- * @template Env Environment type containing bindings
1472
- * @template T Type of the Agent class
1473
- * @param namespace Agent namespace
1474
- * @param name Name of the Agent instance
1475
- * @param options Options for Agent creation
1476
- * @returns Promise resolving to an Agent instance stub
1477
- */
1478
- export async function getAgentByName<Env, T extends Agent<Env>>(
1479
- namespace: AgentNamespace<T>,
1480
- name: string,
1481
- options?: {
1482
- jurisdiction?: DurableObjectJurisdiction;
1483
- locationHint?: DurableObjectLocationHint;
1484
- }
1485
- ) {
1486
- return getServerByName<Env, T>(namespace, name, options);
1487
- }
1488
-
1489
- /**
1490
- * A wrapper for streaming responses in callable methods
1491
- */
1492
- export class StreamingResponse {
1493
- private _connection: Connection;
1494
- private _id: string;
1495
- private _closed = false;
1496
-
1497
- constructor(connection: Connection, id: string) {
1498
- this._connection = connection;
1499
- this._id = id;
1500
- }
1501
-
1502
- /**
1503
- * Send a chunk of data to the client
1504
- * @param chunk The data to send
1505
- */
1506
- send(chunk: unknown) {
1507
- if (this._closed) {
1508
- throw new Error("StreamingResponse is already closed");
1509
- }
1510
- const response: RPCResponse = {
1511
- done: false,
1512
- id: this._id,
1513
- result: chunk,
1514
- success: true,
1515
- type: "rpc",
1516
- };
1517
- this._connection.send(JSON.stringify(response));
1518
- }
1519
-
1520
- /**
1521
- * End the stream and send the final chunk (if any)
1522
- * @param finalChunk Optional final chunk of data to send
1523
- */
1524
- end(finalChunk?: unknown) {
1525
- if (this._closed) {
1526
- throw new Error("StreamingResponse is already closed");
1527
- }
1528
- this._closed = true;
1529
- const response: RPCResponse = {
1530
- done: true,
1531
- id: this._id,
1532
- result: finalChunk,
1533
- success: true,
1534
- type: "rpc",
1535
- };
1536
- this._connection.send(JSON.stringify(response));
1537
- }
1538
- }