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