agents 0.0.0-eeb70e2 → 0.0.0-ef38e84

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 (78) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  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 +266 -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-Bws9q38u.d.ts +5427 -0
  23. package/dist/client-CbWe9FBd.d.ts +104 -0
  24. package/dist/client-DvK0u9vD.js +898 -0
  25. package/dist/client-DvK0u9vD.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 +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-CcTno-25.d.ts +142 -0
  32. package/dist/do-oauth-client-provider-D2P1lSft.js +93 -0
  33. package/dist/do-oauth-client-provider-D2P1lSft.js.map +1 -0
  34. package/dist/index-Bdzb2feZ.d.ts +572 -0
  35. package/dist/index-DhJCaDWd.d.ts +58 -0
  36. package/dist/index.d.ts +61 -402
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -783
  39. package/dist/mcp/client.js +4 -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 +1428 -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 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-DFNXTQzy.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 +89 -12
  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-C1WWpbRo.js +1247 -0
  62. package/dist/src-C1WWpbRo.js.map +1 -0
  63. package/package.json +125 -71
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-BZXOAZUX.js +0 -106
  66. package/dist/chunk-BZXOAZUX.js.map +0 -1
  67. package/dist/chunk-OYJXQRRH.js +0 -465
  68. package/dist/chunk-OYJXQRRH.js.map +0 -1
  69. package/dist/chunk-P3RZJ72N.js +0 -783
  70. package/dist/chunk-P3RZJ72N.js.map +0 -1
  71. package/dist/chunk-VCSB47AK.js +0 -116
  72. package/dist/chunk-VCSB47AK.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/serializable.js.map +0 -1
  78. package/src/index.ts +0 -1252
@@ -0,0 +1,1247 @@
1
+ import { t as MessageType } from "./ai-types-B3aQaFv3.js";
2
+ import { r as camelCaseToKebabCase } from "./client-BfiZ3HQd.js";
3
+ import { r as DisposableStore, t as MCPClientManager } from "./client-DvK0u9vD.js";
4
+ import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-D2P1lSft.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { parseCronExpression } from "cron-schedule";
7
+ import { nanoid } from "nanoid";
8
+ import { EmailMessage } from "cloudflare:email";
9
+ import { Server, getServerByName, routePartykitRequest } from "partyserver";
10
+
11
+ //#region src/mcp/client-storage.ts
12
+ /**
13
+ * SQL-based storage adapter that wraps SQL operations
14
+ * Used by Agent class to provide SQL access to MCPClientManager
15
+ */
16
+ var AgentMCPClientStorage = class {
17
+ constructor(sql, kv) {
18
+ this.sql = sql;
19
+ this.kv = kv;
20
+ }
21
+ async create() {
22
+ this.sql`
23
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
24
+ id TEXT PRIMARY KEY NOT NULL,
25
+ name TEXT NOT NULL,
26
+ server_url TEXT NOT NULL,
27
+ callback_url TEXT NOT NULL,
28
+ client_id TEXT,
29
+ auth_url TEXT,
30
+ server_options TEXT
31
+ )
32
+ `;
33
+ }
34
+ async destroy() {
35
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
36
+ }
37
+ async saveServer(server) {
38
+ this.sql`
39
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (
40
+ id,
41
+ name,
42
+ server_url,
43
+ client_id,
44
+ auth_url,
45
+ callback_url,
46
+ server_options
47
+ )
48
+ VALUES (
49
+ ${server.id},
50
+ ${server.name},
51
+ ${server.server_url},
52
+ ${server.client_id ?? null},
53
+ ${server.auth_url ?? null},
54
+ ${server.callback_url},
55
+ ${server.server_options ?? null}
56
+ )
57
+ `;
58
+ }
59
+ async removeServer(serverId) {
60
+ this.sql`
61
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${serverId}
62
+ `;
63
+ }
64
+ async listServers() {
65
+ return this.sql`
66
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
67
+ FROM cf_agents_mcp_servers
68
+ `;
69
+ }
70
+ async getServerByCallbackUrl(callbackUrl) {
71
+ const results = this.sql`
72
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
73
+ FROM cf_agents_mcp_servers
74
+ WHERE callback_url = ${callbackUrl}
75
+ LIMIT 1
76
+ `;
77
+ return results.length > 0 ? results[0] : null;
78
+ }
79
+ async clearAuthUrl(serverId) {
80
+ this.sql`
81
+ UPDATE cf_agents_mcp_servers
82
+ SET auth_url = NULL
83
+ WHERE id = ${serverId}
84
+ `;
85
+ }
86
+ async get(key) {
87
+ return this.kv.get(key);
88
+ }
89
+ async put(key, value) {
90
+ return this.kv.put(key, value);
91
+ }
92
+ };
93
+
94
+ //#endregion
95
+ //#region src/observability/index.ts
96
+ /**
97
+ * A generic observability implementation that logs events to the console.
98
+ */
99
+ const genericObservability = { emit(event) {
100
+ if (isLocalMode()) {
101
+ console.log(event.displayMessage);
102
+ return;
103
+ }
104
+ console.log(event);
105
+ } };
106
+ let localMode = false;
107
+ function isLocalMode() {
108
+ if (localMode) return true;
109
+ const { request } = getCurrentAgent();
110
+ if (!request) return false;
111
+ localMode = new URL(request.url).hostname === "localhost";
112
+ return localMode;
113
+ }
114
+
115
+ //#endregion
116
+ //#region src/index.ts
117
+ /**
118
+ * Type guard for RPC request messages
119
+ */
120
+ function isRPCRequest(msg) {
121
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.RPC && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
122
+ }
123
+ /**
124
+ * Type guard for state update messages
125
+ */
126
+ function isStateUpdateMessage(msg) {
127
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
128
+ }
129
+ const callableMetadata = /* @__PURE__ */ new Map();
130
+ /**
131
+ * Decorator that marks a method as callable by clients
132
+ * @param metadata Optional metadata about the callable method
133
+ */
134
+ function callable(metadata = {}) {
135
+ return function callableDecorator(target, context) {
136
+ if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
137
+ return target;
138
+ };
139
+ }
140
+ let didWarnAboutUnstableCallable = false;
141
+ /**
142
+ * Decorator that marks a method as callable by clients
143
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
144
+ * @param metadata Optional metadata about the callable method
145
+ */
146
+ const unstable_callable = (metadata = {}) => {
147
+ if (!didWarnAboutUnstableCallable) {
148
+ didWarnAboutUnstableCallable = true;
149
+ console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
150
+ }
151
+ callable(metadata);
152
+ };
153
+ function getNextCronTime(cron) {
154
+ return parseCronExpression(cron).getNextDate();
155
+ }
156
+ const STATE_ROW_ID = "cf_state_row_id";
157
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
158
+ const DEFAULT_STATE = {};
159
+ const agentContext = new AsyncLocalStorage();
160
+ function getCurrentAgent() {
161
+ const store = agentContext.getStore();
162
+ if (!store) return {
163
+ agent: void 0,
164
+ connection: void 0,
165
+ request: void 0,
166
+ email: void 0
167
+ };
168
+ return store;
169
+ }
170
+ /**
171
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
172
+ * @param agent The agent instance
173
+ * @param method The method to wrap
174
+ * @returns A wrapped method that runs within the agent context
175
+ */
176
+ function withAgentContext(method) {
177
+ return function(...args) {
178
+ const { connection, request, email, agent } = getCurrentAgent();
179
+ if (agent === this) return method.apply(this, args);
180
+ return agentContext.run({
181
+ agent: this,
182
+ connection,
183
+ request,
184
+ email
185
+ }, () => {
186
+ return method.apply(this, args);
187
+ });
188
+ };
189
+ }
190
+ /**
191
+ * Base class for creating Agent implementations
192
+ * @template Env Environment type containing bindings
193
+ * @template State State type to store within the Agent
194
+ */
195
+ var Agent = class Agent extends Server {
196
+ /**
197
+ * Current state of the Agent
198
+ */
199
+ get state() {
200
+ if (this._state !== DEFAULT_STATE) return this._state;
201
+ const wasChanged = this.sql`
202
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
203
+ `;
204
+ const result = this.sql`
205
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
206
+ `;
207
+ if (wasChanged[0]?.state === "true" || result[0]?.state) {
208
+ const state = result[0]?.state;
209
+ this._state = JSON.parse(state);
210
+ return this._state;
211
+ }
212
+ if (this.initialState === DEFAULT_STATE) return;
213
+ this.setState(this.initialState);
214
+ return this.initialState;
215
+ }
216
+ static {
217
+ this.options = { hibernate: true };
218
+ }
219
+ /**
220
+ * Execute SQL queries against the Agent's database
221
+ * @template T Type of the returned rows
222
+ * @param strings SQL query template strings
223
+ * @param values Values to be inserted into the query
224
+ * @returns Array of query results
225
+ */
226
+ sql(strings, ...values) {
227
+ let query = "";
228
+ try {
229
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
230
+ return [...this.ctx.storage.sql.exec(query, ...values)];
231
+ } catch (e) {
232
+ console.error(`failed to execute sql query: ${query}`, e);
233
+ throw this.onError(e);
234
+ }
235
+ }
236
+ constructor(ctx, env) {
237
+ super(ctx, env);
238
+ this._state = DEFAULT_STATE;
239
+ this._disposables = new DisposableStore();
240
+ this._destroyed = false;
241
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
242
+ this.initialState = DEFAULT_STATE;
243
+ this.observability = genericObservability;
244
+ this._flushingQueue = false;
245
+ this.alarm = async () => {
246
+ const now = Math.floor(Date.now() / 1e3);
247
+ const result = this.sql`
248
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
249
+ `;
250
+ if (result && Array.isArray(result)) for (const row of result) {
251
+ const callback = this[row.callback];
252
+ if (!callback) {
253
+ console.error(`callback ${row.callback} not found`);
254
+ continue;
255
+ }
256
+ await agentContext.run({
257
+ agent: this,
258
+ connection: void 0,
259
+ request: void 0,
260
+ email: void 0
261
+ }, async () => {
262
+ try {
263
+ this.observability?.emit({
264
+ displayMessage: `Schedule ${row.id} executed`,
265
+ id: nanoid(),
266
+ payload: {
267
+ callback: row.callback,
268
+ id: row.id
269
+ },
270
+ timestamp: Date.now(),
271
+ type: "schedule:execute"
272
+ }, this.ctx);
273
+ await callback.bind(this)(JSON.parse(row.payload), row);
274
+ } catch (e) {
275
+ console.error(`error executing callback "${row.callback}"`, e);
276
+ }
277
+ });
278
+ if (row.type === "cron") {
279
+ if (this._destroyed) return;
280
+ const nextExecutionTime = getNextCronTime(row.cron);
281
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
282
+ this.sql`
283
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
284
+ `;
285
+ } else {
286
+ if (this._destroyed) return;
287
+ this.sql`
288
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
289
+ `;
290
+ }
291
+ }
292
+ if (this._destroyed) return;
293
+ await this._scheduleNextAlarm();
294
+ };
295
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: new AgentMCPClientStorage(this.sql.bind(this), this.ctx.storage.kv) });
296
+ if (!wrappedClasses.has(this.constructor)) {
297
+ this._autoWrapCustomMethods();
298
+ wrappedClasses.add(this.constructor);
299
+ }
300
+ this._disposables.add(this.mcp.onServerStateChanged(async () => {
301
+ await this.broadcastMcpServers();
302
+ }));
303
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
304
+ this.observability?.emit(event);
305
+ }));
306
+ this.sql`
307
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
308
+ id TEXT PRIMARY KEY NOT NULL,
309
+ state TEXT
310
+ )
311
+ `;
312
+ this.sql`
313
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
314
+ id TEXT PRIMARY KEY NOT NULL,
315
+ payload TEXT,
316
+ callback TEXT,
317
+ created_at INTEGER DEFAULT (unixepoch())
318
+ )
319
+ `;
320
+ this.sql`
321
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
322
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
323
+ callback TEXT,
324
+ payload TEXT,
325
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
326
+ time INTEGER,
327
+ delayInSeconds INTEGER,
328
+ cron TEXT,
329
+ created_at INTEGER DEFAULT (unixepoch())
330
+ )
331
+ `;
332
+ const _onRequest = this.onRequest.bind(this);
333
+ this.onRequest = (request) => {
334
+ return agentContext.run({
335
+ agent: this,
336
+ connection: void 0,
337
+ request,
338
+ email: void 0
339
+ }, async () => {
340
+ await this.mcp.ensureJsonSchema();
341
+ const oauthResponse = await this.handleMcpOAuthCallback(request);
342
+ if (oauthResponse) return oauthResponse;
343
+ return this._tryCatch(() => _onRequest(request));
344
+ });
345
+ };
346
+ const _onMessage = this.onMessage.bind(this);
347
+ this.onMessage = async (connection, message) => {
348
+ return agentContext.run({
349
+ agent: this,
350
+ connection,
351
+ request: void 0,
352
+ email: void 0
353
+ }, async () => {
354
+ await this.mcp.ensureJsonSchema();
355
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
356
+ let parsed;
357
+ try {
358
+ parsed = JSON.parse(message);
359
+ } catch (_e) {
360
+ return this._tryCatch(() => _onMessage(connection, message));
361
+ }
362
+ if (isStateUpdateMessage(parsed)) {
363
+ this._setStateInternal(parsed.state, connection);
364
+ return;
365
+ }
366
+ if (isRPCRequest(parsed)) {
367
+ try {
368
+ const { id, method, args } = parsed;
369
+ const methodFn = this[method];
370
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
371
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
372
+ const metadata = callableMetadata.get(methodFn);
373
+ if (metadata?.streaming) {
374
+ const stream = new StreamingResponse(connection, id);
375
+ await methodFn.apply(this, [stream, ...args]);
376
+ return;
377
+ }
378
+ const result = await methodFn.apply(this, args);
379
+ this.observability?.emit({
380
+ displayMessage: `RPC call to ${method}`,
381
+ id: nanoid(),
382
+ payload: {
383
+ method,
384
+ streaming: metadata?.streaming
385
+ },
386
+ timestamp: Date.now(),
387
+ type: "rpc"
388
+ }, this.ctx);
389
+ const response = {
390
+ done: true,
391
+ id,
392
+ result,
393
+ success: true,
394
+ type: MessageType.RPC
395
+ };
396
+ connection.send(JSON.stringify(response));
397
+ } catch (e) {
398
+ const response = {
399
+ error: e instanceof Error ? e.message : "Unknown error occurred",
400
+ id: parsed.id,
401
+ success: false,
402
+ type: MessageType.RPC
403
+ };
404
+ connection.send(JSON.stringify(response));
405
+ console.error("RPC error:", e);
406
+ }
407
+ return;
408
+ }
409
+ return this._tryCatch(() => _onMessage(connection, message));
410
+ });
411
+ };
412
+ const _onConnect = this.onConnect.bind(this);
413
+ this.onConnect = (connection, ctx$1) => {
414
+ return agentContext.run({
415
+ agent: this,
416
+ connection,
417
+ request: ctx$1.request,
418
+ email: void 0
419
+ }, async () => {
420
+ if (this.state) connection.send(JSON.stringify({
421
+ state: this.state,
422
+ type: MessageType.CF_AGENT_STATE
423
+ }));
424
+ connection.send(JSON.stringify({
425
+ mcp: await this.getMcpServers(),
426
+ type: MessageType.CF_AGENT_MCP_SERVERS
427
+ }));
428
+ this.observability?.emit({
429
+ displayMessage: "Connection established",
430
+ id: nanoid(),
431
+ payload: { connectionId: connection.id },
432
+ timestamp: Date.now(),
433
+ type: "connect"
434
+ }, this.ctx);
435
+ return this._tryCatch(() => _onConnect(connection, ctx$1));
436
+ });
437
+ };
438
+ const _onStart = this.onStart.bind(this);
439
+ this.onStart = async (props) => {
440
+ return agentContext.run({
441
+ agent: this,
442
+ connection: void 0,
443
+ request: void 0,
444
+ email: void 0
445
+ }, async () => {
446
+ await this._tryCatch(async () => {
447
+ await this.mcp.restoreConnectionsFromStorage(this.name);
448
+ await this.broadcastMcpServers();
449
+ return _onStart(props);
450
+ });
451
+ });
452
+ };
453
+ }
454
+ _setStateInternal(state, source = "server") {
455
+ this._state = state;
456
+ this.sql`
457
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
458
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
459
+ `;
460
+ this.sql`
461
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
462
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
463
+ `;
464
+ this.broadcast(JSON.stringify({
465
+ state,
466
+ type: MessageType.CF_AGENT_STATE
467
+ }), source !== "server" ? [source.id] : []);
468
+ return this._tryCatch(() => {
469
+ const { connection, request, email } = agentContext.getStore() || {};
470
+ return agentContext.run({
471
+ agent: this,
472
+ connection,
473
+ request,
474
+ email
475
+ }, async () => {
476
+ this.observability?.emit({
477
+ displayMessage: "State updated",
478
+ id: nanoid(),
479
+ payload: {},
480
+ timestamp: Date.now(),
481
+ type: "state:update"
482
+ }, this.ctx);
483
+ return this.onStateUpdate(state, source);
484
+ });
485
+ });
486
+ }
487
+ /**
488
+ * Update the Agent's state
489
+ * @param state New state to set
490
+ */
491
+ setState(state) {
492
+ this._setStateInternal(state, "server");
493
+ }
494
+ /**
495
+ * Called when the Agent's state is updated
496
+ * @param state Updated state
497
+ * @param source Source of the state update ("server" or a client connection)
498
+ */
499
+ onStateUpdate(state, source) {}
500
+ /**
501
+ * Called when the Agent receives an email via routeAgentEmail()
502
+ * Override this method to handle incoming emails
503
+ * @param email Email message to process
504
+ */
505
+ async _onEmail(email) {
506
+ return agentContext.run({
507
+ agent: this,
508
+ connection: void 0,
509
+ request: void 0,
510
+ email
511
+ }, async () => {
512
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
513
+ else {
514
+ console.log("Received email from:", email.from, "to:", email.to);
515
+ console.log("Subject:", email.headers.get("subject"));
516
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
517
+ }
518
+ });
519
+ }
520
+ /**
521
+ * Reply to an email
522
+ * @param email The email to reply to
523
+ * @param options Options for the reply
524
+ * @returns void
525
+ */
526
+ async replyToEmail(email, options) {
527
+ return this._tryCatch(async () => {
528
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
529
+ const agentId = this.name;
530
+ const { createMimeMessage } = await import("mimetext");
531
+ const msg = createMimeMessage();
532
+ msg.setSender({
533
+ addr: email.to,
534
+ name: options.fromName
535
+ });
536
+ msg.setRecipient(email.from);
537
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
538
+ msg.addMessage({
539
+ contentType: options.contentType || "text/plain",
540
+ data: options.body
541
+ });
542
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
543
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
544
+ msg.setHeader("Message-ID", messageId);
545
+ msg.setHeader("X-Agent-Name", agentName);
546
+ msg.setHeader("X-Agent-ID", agentId);
547
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
548
+ await email.reply({
549
+ from: email.to,
550
+ raw: msg.asRaw(),
551
+ to: email.from
552
+ });
553
+ });
554
+ }
555
+ async _tryCatch(fn) {
556
+ try {
557
+ return await fn();
558
+ } catch (e) {
559
+ throw this.onError(e);
560
+ }
561
+ }
562
+ /**
563
+ * Automatically wrap custom methods with agent context
564
+ * This ensures getCurrentAgent() works in all custom methods without decorators
565
+ */
566
+ _autoWrapCustomMethods() {
567
+ const basePrototypes = [Agent.prototype, Server.prototype];
568
+ const baseMethods = /* @__PURE__ */ new Set();
569
+ for (const baseProto of basePrototypes) {
570
+ let proto$1 = baseProto;
571
+ while (proto$1 && proto$1 !== Object.prototype) {
572
+ const methodNames = Object.getOwnPropertyNames(proto$1);
573
+ for (const methodName of methodNames) baseMethods.add(methodName);
574
+ proto$1 = Object.getPrototypeOf(proto$1);
575
+ }
576
+ }
577
+ let proto = Object.getPrototypeOf(this);
578
+ let depth = 0;
579
+ while (proto && proto !== Object.prototype && depth < 10) {
580
+ const methodNames = Object.getOwnPropertyNames(proto);
581
+ for (const methodName of methodNames) {
582
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
583
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
584
+ const wrappedFunction = withAgentContext(this[methodName]);
585
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
586
+ this.constructor.prototype[methodName] = wrappedFunction;
587
+ }
588
+ proto = Object.getPrototypeOf(proto);
589
+ depth++;
590
+ }
591
+ }
592
+ onError(connectionOrError, error) {
593
+ let theError;
594
+ if (connectionOrError && error) {
595
+ theError = error;
596
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
597
+ console.error("Override onError(connection, error) to handle websocket connection errors");
598
+ } else {
599
+ theError = connectionOrError;
600
+ console.error("Error on server:", theError);
601
+ console.error("Override onError(error) to handle server errors");
602
+ }
603
+ throw theError;
604
+ }
605
+ /**
606
+ * Render content (not implemented in base class)
607
+ */
608
+ render() {
609
+ throw new Error("Not implemented");
610
+ }
611
+ /**
612
+ * Queue a task to be executed in the future
613
+ * @param payload Payload to pass to the callback
614
+ * @param callback Name of the method to call
615
+ * @returns The ID of the queued task
616
+ */
617
+ async queue(callback, payload) {
618
+ const id = nanoid(9);
619
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
620
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
621
+ this.sql`
622
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
623
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
624
+ `;
625
+ this._flushQueue().catch((e) => {
626
+ console.error("Error flushing queue:", e);
627
+ });
628
+ return id;
629
+ }
630
+ async _flushQueue() {
631
+ if (this._flushingQueue) return;
632
+ this._flushingQueue = true;
633
+ while (true) {
634
+ const result = this.sql`
635
+ SELECT * FROM cf_agents_queues
636
+ ORDER BY created_at ASC
637
+ `;
638
+ if (!result || result.length === 0) break;
639
+ for (const row of result || []) {
640
+ const callback = this[row.callback];
641
+ if (!callback) {
642
+ console.error(`callback ${row.callback} not found`);
643
+ continue;
644
+ }
645
+ const { connection, request, email } = agentContext.getStore() || {};
646
+ await agentContext.run({
647
+ agent: this,
648
+ connection,
649
+ request,
650
+ email
651
+ }, async () => {
652
+ await callback.bind(this)(JSON.parse(row.payload), row);
653
+ await this.dequeue(row.id);
654
+ });
655
+ }
656
+ }
657
+ this._flushingQueue = false;
658
+ }
659
+ /**
660
+ * Dequeue a task by ID
661
+ * @param id ID of the task to dequeue
662
+ */
663
+ async dequeue(id) {
664
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
665
+ }
666
+ /**
667
+ * Dequeue all tasks
668
+ */
669
+ async dequeueAll() {
670
+ this.sql`DELETE FROM cf_agents_queues`;
671
+ }
672
+ /**
673
+ * Dequeue all tasks by callback
674
+ * @param callback Name of the callback to dequeue
675
+ */
676
+ async dequeueAllByCallback(callback) {
677
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
678
+ }
679
+ /**
680
+ * Get a queued task by ID
681
+ * @param id ID of the task to get
682
+ * @returns The task or undefined if not found
683
+ */
684
+ async getQueue(id) {
685
+ const result = this.sql`
686
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
687
+ `;
688
+ return result ? {
689
+ ...result[0],
690
+ payload: JSON.parse(result[0].payload)
691
+ } : void 0;
692
+ }
693
+ /**
694
+ * Get all queues by key and value
695
+ * @param key Key to filter by
696
+ * @param value Value to filter by
697
+ * @returns Array of matching QueueItem objects
698
+ */
699
+ async getQueues(key, value) {
700
+ return this.sql`
701
+ SELECT * FROM cf_agents_queues
702
+ `.filter((row) => JSON.parse(row.payload)[key] === value);
703
+ }
704
+ /**
705
+ * Schedule a task to be executed in the future
706
+ * @template T Type of the payload data
707
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
708
+ * @param callback Name of the method to call
709
+ * @param payload Data to pass to the callback
710
+ * @returns Schedule object representing the scheduled task
711
+ */
712
+ async schedule(when, callback, payload) {
713
+ const id = nanoid(9);
714
+ const emitScheduleCreate = (schedule) => this.observability?.emit({
715
+ displayMessage: `Schedule ${schedule.id} created`,
716
+ id: nanoid(),
717
+ payload: {
718
+ callback,
719
+ id
720
+ },
721
+ timestamp: Date.now(),
722
+ type: "schedule:create"
723
+ }, this.ctx);
724
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
725
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
726
+ if (when instanceof Date) {
727
+ const timestamp = Math.floor(when.getTime() / 1e3);
728
+ this.sql`
729
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
730
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
731
+ `;
732
+ await this._scheduleNextAlarm();
733
+ const schedule = {
734
+ callback,
735
+ id,
736
+ payload,
737
+ time: timestamp,
738
+ type: "scheduled"
739
+ };
740
+ emitScheduleCreate(schedule);
741
+ return schedule;
742
+ }
743
+ if (typeof when === "number") {
744
+ const time = new Date(Date.now() + when * 1e3);
745
+ const timestamp = Math.floor(time.getTime() / 1e3);
746
+ this.sql`
747
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
748
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
749
+ `;
750
+ await this._scheduleNextAlarm();
751
+ const schedule = {
752
+ callback,
753
+ delayInSeconds: when,
754
+ id,
755
+ payload,
756
+ time: timestamp,
757
+ type: "delayed"
758
+ };
759
+ emitScheduleCreate(schedule);
760
+ return schedule;
761
+ }
762
+ if (typeof when === "string") {
763
+ const nextExecutionTime = getNextCronTime(when);
764
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
765
+ this.sql`
766
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
767
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
768
+ `;
769
+ await this._scheduleNextAlarm();
770
+ const schedule = {
771
+ callback,
772
+ cron: when,
773
+ id,
774
+ payload,
775
+ time: timestamp,
776
+ type: "cron"
777
+ };
778
+ emitScheduleCreate(schedule);
779
+ return schedule;
780
+ }
781
+ throw new Error("Invalid schedule type");
782
+ }
783
+ /**
784
+ * Get a scheduled task by ID
785
+ * @template T Type of the payload data
786
+ * @param id ID of the scheduled task
787
+ * @returns The Schedule object or undefined if not found
788
+ */
789
+ async getSchedule(id) {
790
+ const result = this.sql`
791
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
792
+ `;
793
+ if (!result) {
794
+ console.error(`schedule ${id} not found`);
795
+ return;
796
+ }
797
+ return {
798
+ ...result[0],
799
+ payload: JSON.parse(result[0].payload)
800
+ };
801
+ }
802
+ /**
803
+ * Get scheduled tasks matching the given criteria
804
+ * @template T Type of the payload data
805
+ * @param criteria Criteria to filter schedules
806
+ * @returns Array of matching Schedule objects
807
+ */
808
+ getSchedules(criteria = {}) {
809
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
810
+ const params = [];
811
+ if (criteria.id) {
812
+ query += " AND id = ?";
813
+ params.push(criteria.id);
814
+ }
815
+ if (criteria.type) {
816
+ query += " AND type = ?";
817
+ params.push(criteria.type);
818
+ }
819
+ if (criteria.timeRange) {
820
+ query += " AND time >= ? AND time <= ?";
821
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
822
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
823
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
824
+ }
825
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
826
+ ...row,
827
+ payload: JSON.parse(row.payload)
828
+ }));
829
+ }
830
+ /**
831
+ * Cancel a scheduled task
832
+ * @param id ID of the task to cancel
833
+ * @returns true if the task was cancelled, false otherwise
834
+ */
835
+ async cancelSchedule(id) {
836
+ const schedule = await this.getSchedule(id);
837
+ if (schedule) this.observability?.emit({
838
+ displayMessage: `Schedule ${id} cancelled`,
839
+ id: nanoid(),
840
+ payload: {
841
+ callback: schedule.callback,
842
+ id: schedule.id
843
+ },
844
+ timestamp: Date.now(),
845
+ type: "schedule:cancel"
846
+ }, this.ctx);
847
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
848
+ await this._scheduleNextAlarm();
849
+ return true;
850
+ }
851
+ async _scheduleNextAlarm() {
852
+ const result = this.sql`
853
+ SELECT time FROM cf_agents_schedules
854
+ WHERE time >= ${Math.floor(Date.now() / 1e3)}
855
+ ORDER BY time ASC
856
+ LIMIT 1
857
+ `;
858
+ if (!result) return;
859
+ if (result.length > 0 && "time" in result[0]) {
860
+ const nextTime = result[0].time * 1e3;
861
+ await this.ctx.storage.setAlarm(nextTime);
862
+ }
863
+ }
864
+ /**
865
+ * Destroy the Agent, removing all state and scheduled tasks
866
+ */
867
+ async destroy() {
868
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
869
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
870
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
871
+ await this.ctx.storage.deleteAlarm();
872
+ await this.ctx.storage.deleteAll();
873
+ this._disposables.dispose();
874
+ await this.mcp.dispose();
875
+ this._destroyed = true;
876
+ setTimeout(() => {
877
+ this.ctx.abort("destroyed");
878
+ }, 0);
879
+ this.observability?.emit({
880
+ displayMessage: "Agent destroyed",
881
+ id: nanoid(),
882
+ payload: {},
883
+ timestamp: Date.now(),
884
+ type: "destroy"
885
+ }, this.ctx);
886
+ }
887
+ /**
888
+ * Get all methods marked as callable on this Agent
889
+ * @returns A map of method names to their metadata
890
+ */
891
+ _isCallable(method) {
892
+ return callableMetadata.has(this[method]);
893
+ }
894
+ /**
895
+ * Connect to a new MCP Server
896
+ *
897
+ * @param serverName Name of the MCP server
898
+ * @param url MCP Server SSE URL
899
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
900
+ * @param agentsPrefix agents routing prefix if not using `agents`
901
+ * @param options MCP client and transport options
902
+ * @returns authUrl
903
+ */
904
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
905
+ let resolvedCallbackHost = callbackHost;
906
+ if (!resolvedCallbackHost) {
907
+ const { request } = getCurrentAgent();
908
+ if (!request) throw new Error("callbackHost is required when not called within a request context");
909
+ const requestUrl = new URL(request.url);
910
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
911
+ }
912
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
913
+ await this.mcp.ensureJsonSchema();
914
+ const id = nanoid(8);
915
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage.kv, this.name, callbackUrl);
916
+ authProvider.serverId = id;
917
+ const transportType = options?.transport?.type ?? "auto";
918
+ let headerTransportOpts = {};
919
+ if (options?.transport?.headers) headerTransportOpts = {
920
+ eventSourceInit: { fetch: (url$1, init) => fetch(url$1, {
921
+ ...init,
922
+ headers: options?.transport?.headers
923
+ }) },
924
+ requestInit: { headers: options?.transport?.headers }
925
+ };
926
+ await this.mcp.registerServer(id, {
927
+ url,
928
+ name: serverName,
929
+ callbackUrl,
930
+ client: options?.client,
931
+ transport: {
932
+ ...headerTransportOpts,
933
+ authProvider,
934
+ type: transportType
935
+ }
936
+ });
937
+ const result = await this.mcp.connectToServer(id);
938
+ return {
939
+ id,
940
+ authUrl: result.state === "authenticating" ? result.authUrl : void 0
941
+ };
942
+ }
943
+ async removeMcpServer(id) {
944
+ if (this.mcp.mcpConnections[id]) await this.mcp.closeConnection(id);
945
+ await this.mcp.removeServer(id);
946
+ }
947
+ async getMcpServers() {
948
+ const mcpState = {
949
+ prompts: this.mcp.listPrompts(),
950
+ resources: this.mcp.listResources(),
951
+ servers: {},
952
+ tools: this.mcp.listTools()
953
+ };
954
+ const servers = await this.mcp.listServers();
955
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
956
+ const serverConn = this.mcp.mcpConnections[server.id];
957
+ let defaultState = "not-connected";
958
+ if (!serverConn && server.auth_url) defaultState = "authenticating";
959
+ mcpState.servers[server.id] = {
960
+ auth_url: server.auth_url,
961
+ capabilities: serverConn?.serverCapabilities ?? null,
962
+ instructions: serverConn?.instructions ?? null,
963
+ name: server.name,
964
+ server_url: server.server_url,
965
+ state: serverConn?.connectionState ?? defaultState
966
+ };
967
+ }
968
+ return mcpState;
969
+ }
970
+ async broadcastMcpServers() {
971
+ this.broadcast(JSON.stringify({
972
+ mcp: await this.getMcpServers(),
973
+ type: MessageType.CF_AGENT_MCP_SERVERS
974
+ }));
975
+ }
976
+ /**
977
+ * Handle MCP OAuth callback request if it's an OAuth callback.
978
+ *
979
+ * This method encapsulates the entire OAuth callback flow:
980
+ * 1. Checks if the request is an MCP OAuth callback
981
+ * 2. Processes the OAuth code exchange
982
+ * 3. Establishes the connection if successful
983
+ * 4. Broadcasts MCP server state updates
984
+ * 5. Returns the appropriate HTTP response
985
+ *
986
+ * @param request The incoming HTTP request
987
+ * @returns Response if this was an OAuth callback, null otherwise
988
+ */
989
+ async handleMcpOAuthCallback(request) {
990
+ if (!await this.mcp.isCallbackRequest(request)) return null;
991
+ const result = await this.mcp.handleCallbackRequest(request);
992
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
993
+ console.error("[Agent handleMcpOAuthCallback] Background connection failed:", error);
994
+ });
995
+ return this.handleOAuthCallbackResponse(result, request);
996
+ }
997
+ /**
998
+ * Handle OAuth callback response using MCPClientManager configuration
999
+ * @param result OAuth callback result
1000
+ * @param request The original request (needed for base URL)
1001
+ * @returns Response for the OAuth callback
1002
+ */
1003
+ handleOAuthCallbackResponse(result, request) {
1004
+ const config = this.mcp.getOAuthCallbackConfig();
1005
+ if (config?.customHandler) return config.customHandler(result);
1006
+ const baseOrigin = new URL(request.url).origin;
1007
+ if (config?.successRedirect && result.authSuccess) try {
1008
+ return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
1009
+ } catch (e) {
1010
+ console.error("Invalid successRedirect URL:", config.successRedirect, e);
1011
+ return Response.redirect(baseOrigin);
1012
+ }
1013
+ if (config?.errorRedirect && !result.authSuccess) try {
1014
+ const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
1015
+ return Response.redirect(new URL(errorUrl, baseOrigin).href);
1016
+ } catch (e) {
1017
+ console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
1018
+ return Response.redirect(baseOrigin);
1019
+ }
1020
+ return Response.redirect(baseOrigin);
1021
+ }
1022
+ };
1023
+ const wrappedClasses = /* @__PURE__ */ new Set();
1024
+ /**
1025
+ * Route a request to the appropriate Agent
1026
+ * @param request Request to route
1027
+ * @param env Environment containing Agent bindings
1028
+ * @param options Routing options
1029
+ * @returns Response from the Agent or undefined if no route matched
1030
+ */
1031
+ async function routeAgentRequest(request, env, options) {
1032
+ const corsHeaders = options?.cors === true ? {
1033
+ "Access-Control-Allow-Credentials": "true",
1034
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1035
+ "Access-Control-Allow-Origin": "*",
1036
+ "Access-Control-Max-Age": "86400"
1037
+ } : options?.cors;
1038
+ if (request.method === "OPTIONS") {
1039
+ if (corsHeaders) return new Response(null, { headers: corsHeaders });
1040
+ console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
1041
+ }
1042
+ let response = await routePartykitRequest(request, env, {
1043
+ prefix: "agents",
1044
+ ...options
1045
+ });
1046
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
1047
+ const newHeaders = new Headers(response.headers);
1048
+ for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
1049
+ response = new Response(response.body, {
1050
+ status: response.status,
1051
+ statusText: response.statusText,
1052
+ headers: newHeaders
1053
+ });
1054
+ }
1055
+ return response;
1056
+ }
1057
+ /**
1058
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1059
+ * @returns A function that resolves the agent to route the email to
1060
+ */
1061
+ function createHeaderBasedEmailResolver() {
1062
+ return async (email, _env) => {
1063
+ const messageId = email.headers.get("message-id");
1064
+ if (messageId) {
1065
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1066
+ if (messageIdMatch) {
1067
+ const [, agentId$1, domain] = messageIdMatch;
1068
+ return {
1069
+ agentName: domain.split(".")[0],
1070
+ agentId: agentId$1
1071
+ };
1072
+ }
1073
+ }
1074
+ const references = email.headers.get("references");
1075
+ if (references) {
1076
+ const referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);
1077
+ if (referencesMatch) {
1078
+ const [, base64Id, domain] = referencesMatch;
1079
+ const agentId$1 = Buffer.from(base64Id, "base64").toString("hex");
1080
+ return {
1081
+ agentName: domain.split(".")[0],
1082
+ agentId: agentId$1
1083
+ };
1084
+ }
1085
+ }
1086
+ const agentName = email.headers.get("x-agent-name");
1087
+ const agentId = email.headers.get("x-agent-id");
1088
+ if (agentName && agentId) return {
1089
+ agentName,
1090
+ agentId
1091
+ };
1092
+ return null;
1093
+ };
1094
+ }
1095
+ /**
1096
+ * Create a resolver that uses the email address to determine the agent to route the email to
1097
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1098
+ * @returns A function that resolves the agent to route the email to
1099
+ */
1100
+ function createAddressBasedEmailResolver(defaultAgentName) {
1101
+ return async (email, _env) => {
1102
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1103
+ if (!emailMatch) return null;
1104
+ const [, localPart, subAddress] = emailMatch;
1105
+ if (subAddress) return {
1106
+ agentName: localPart,
1107
+ agentId: subAddress
1108
+ };
1109
+ return {
1110
+ agentName: defaultAgentName,
1111
+ agentId: localPart
1112
+ };
1113
+ };
1114
+ }
1115
+ /**
1116
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1117
+ * @param agentName The name of the agent to route the email to
1118
+ * @param agentId The id of the agent to route the email to
1119
+ * @returns A function that resolves the agent to route the email to
1120
+ */
1121
+ function createCatchAllEmailResolver(agentName, agentId) {
1122
+ return async () => ({
1123
+ agentName,
1124
+ agentId
1125
+ });
1126
+ }
1127
+ const agentMapCache = /* @__PURE__ */ new WeakMap();
1128
+ /**
1129
+ * Route an email to the appropriate Agent
1130
+ * @param email The email to route
1131
+ * @param env The environment containing the Agent bindings
1132
+ * @param options The options for routing the email
1133
+ * @returns A promise that resolves when the email has been routed
1134
+ */
1135
+ async function routeAgentEmail(email, env, options) {
1136
+ const routingInfo = await options.resolver(email, env);
1137
+ if (!routingInfo) {
1138
+ console.warn("No routing information found for email, dropping message");
1139
+ return;
1140
+ }
1141
+ if (!agentMapCache.has(env)) {
1142
+ const map = {};
1143
+ for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1144
+ map[key] = value;
1145
+ map[camelCaseToKebabCase(key)] = value;
1146
+ }
1147
+ agentMapCache.set(env, map);
1148
+ }
1149
+ const agentMap = agentMapCache.get(env);
1150
+ const namespace = agentMap[routingInfo.agentName];
1151
+ if (!namespace) {
1152
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1153
+ throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
1154
+ }
1155
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1156
+ const serialisableEmail = {
1157
+ getRaw: async () => {
1158
+ const reader = email.raw.getReader();
1159
+ const chunks = [];
1160
+ let done = false;
1161
+ while (!done) {
1162
+ const { value, done: readerDone } = await reader.read();
1163
+ done = readerDone;
1164
+ if (value) chunks.push(value);
1165
+ }
1166
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1167
+ const combined = new Uint8Array(totalLength);
1168
+ let offset = 0;
1169
+ for (const chunk of chunks) {
1170
+ combined.set(chunk, offset);
1171
+ offset += chunk.length;
1172
+ }
1173
+ return combined;
1174
+ },
1175
+ headers: email.headers,
1176
+ rawSize: email.rawSize,
1177
+ setReject: (reason) => {
1178
+ email.setReject(reason);
1179
+ },
1180
+ forward: (rcptTo, headers) => {
1181
+ return email.forward(rcptTo, headers);
1182
+ },
1183
+ reply: (options$1) => {
1184
+ return email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));
1185
+ },
1186
+ from: email.from,
1187
+ to: email.to
1188
+ };
1189
+ await agent._onEmail(serialisableEmail);
1190
+ }
1191
+ /**
1192
+ * Get or create an Agent by name
1193
+ * @template Env Environment type containing bindings
1194
+ * @template T Type of the Agent class
1195
+ * @param namespace Agent namespace
1196
+ * @param name Name of the Agent instance
1197
+ * @param options Options for Agent creation
1198
+ * @returns Promise resolving to an Agent instance stub
1199
+ */
1200
+ async function getAgentByName(namespace, name, options) {
1201
+ return getServerByName(namespace, name, options);
1202
+ }
1203
+ /**
1204
+ * A wrapper for streaming responses in callable methods
1205
+ */
1206
+ var StreamingResponse = class {
1207
+ constructor(connection, id) {
1208
+ this._closed = false;
1209
+ this._connection = connection;
1210
+ this._id = id;
1211
+ }
1212
+ /**
1213
+ * Send a chunk of data to the client
1214
+ * @param chunk The data to send
1215
+ */
1216
+ send(chunk) {
1217
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1218
+ const response = {
1219
+ done: false,
1220
+ id: this._id,
1221
+ result: chunk,
1222
+ success: true,
1223
+ type: MessageType.RPC
1224
+ };
1225
+ this._connection.send(JSON.stringify(response));
1226
+ }
1227
+ /**
1228
+ * End the stream and send the final chunk (if any)
1229
+ * @param finalChunk Optional final chunk of data to send
1230
+ */
1231
+ end(finalChunk) {
1232
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1233
+ this._closed = true;
1234
+ const response = {
1235
+ done: true,
1236
+ id: this._id,
1237
+ result: finalChunk,
1238
+ success: true,
1239
+ type: MessageType.RPC
1240
+ };
1241
+ this._connection.send(JSON.stringify(response));
1242
+ }
1243
+ };
1244
+
1245
+ //#endregion
1246
+ export { createCatchAllEmailResolver as a, getCurrentAgent as c, unstable_callable as d, genericObservability as f, createAddressBasedEmailResolver as i, routeAgentEmail as l, StreamingResponse as n, createHeaderBasedEmailResolver as o, callable as r, getAgentByName as s, Agent as t, routeAgentRequest as u };
1247
+ //# sourceMappingURL=src-C1WWpbRo.js.map