agents 0.0.0-143ec31 → 0.0.0-14616d3

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