agents 0.0.0-fb503ba → 0.0.0-fb62d22

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