agents 0.0.0-c5e3a32 → 0.0.0-c67d4b4

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