agents 0.2.9 → 0.2.11

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