agents 0.0.0-eb6827a → 0.0.0-ecbd795

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