agents 0.0.0-f913299 → 0.0.0-fac1fe8

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 +159 -33
  2. package/dist/ai-chat-agent.d.ts +56 -6
  3. package/dist/ai-chat-agent.js +286 -97
  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 -65
  8. package/dist/ai-react.js +193 -72
  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-MH46VMM4.js +612 -0
  17. package/dist/chunk-MH46VMM4.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-YDUDMOL6.js +1296 -0
  23. package/dist/chunk-YDUDMOL6.js.map +1 -0
  24. package/dist/client-CvaJdLQA.d.ts +5015 -0
  25. package/dist/client.d.ts +16 -2
  26. package/dist/client.js +7 -133
  27. package/dist/client.js.map +1 -1
  28. package/dist/index.d.ts +284 -22
  29. package/dist/index.js +15 -4
  30. package/dist/mcp/client.d.ts +11 -0
  31. package/dist/mcp/client.js +9 -0
  32. package/dist/mcp/client.js.map +1 -0
  33. package/dist/mcp/do-oauth-client-provider.d.ts +42 -0
  34. package/dist/mcp/do-oauth-client-provider.js +7 -0
  35. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  36. package/dist/mcp/index.d.ts +97 -0
  37. package/dist/mcp/index.js +1025 -0
  38. package/dist/mcp/index.js.map +1 -0
  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 +53 -32
  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 +95 -43
  52. package/src/index.ts +1243 -184
  53. package/dist/chunk-HMLY7DHA.js +0 -16
  54. package/dist/chunk-X6BBKLSC.js +0 -568
  55. package/dist/chunk-X6BBKLSC.js.map +0 -1
  56. /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
@@ -0,0 +1,1296 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-MH46VMM4.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 (props) => {
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(props);
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
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
575
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") {
576
+ continue;
577
+ }
578
+ const wrappedFunction = withAgentContext(
579
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
580
+ this[methodName]
581
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
582
+ );
583
+ if (this._isCallable(methodName)) {
584
+ callableMetadata.set(
585
+ wrappedFunction,
586
+ callableMetadata.get(this[methodName])
587
+ );
588
+ }
589
+ this.constructor.prototype[methodName] = wrappedFunction;
590
+ }
591
+ proto = Object.getPrototypeOf(proto);
592
+ depth++;
593
+ }
594
+ }
595
+ onError(connectionOrError, error) {
596
+ let theError;
597
+ if (connectionOrError && error) {
598
+ theError = error;
599
+ console.error(
600
+ "Error on websocket connection:",
601
+ connectionOrError.id,
602
+ theError
603
+ );
604
+ console.error(
605
+ "Override onError(connection, error) to handle websocket connection errors"
606
+ );
607
+ } else {
608
+ theError = connectionOrError;
609
+ console.error("Error on server:", theError);
610
+ console.error("Override onError(error) to handle server errors");
611
+ }
612
+ throw theError;
613
+ }
614
+ /**
615
+ * Render content (not implemented in base class)
616
+ */
617
+ render() {
618
+ throw new Error("Not implemented");
619
+ }
620
+ /**
621
+ * Queue a task to be executed in the future
622
+ * @param payload Payload to pass to the callback
623
+ * @param callback Name of the method to call
624
+ * @returns The ID of the queued task
625
+ */
626
+ async queue(callback, payload) {
627
+ const id = nanoid(9);
628
+ if (typeof callback !== "string") {
629
+ throw new Error("Callback must be a string");
630
+ }
631
+ if (typeof this[callback] !== "function") {
632
+ throw new Error(`this.${callback} is not a function`);
633
+ }
634
+ this.sql`
635
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
636
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
637
+ `;
638
+ void this._flushQueue().catch((e) => {
639
+ console.error("Error flushing queue:", e);
640
+ });
641
+ return id;
642
+ }
643
+ async _flushQueue() {
644
+ if (this._flushingQueue) {
645
+ return;
646
+ }
647
+ this._flushingQueue = true;
648
+ while (true) {
649
+ const result = this.sql`
650
+ SELECT * FROM cf_agents_queues
651
+ ORDER BY created_at ASC
652
+ `;
653
+ if (!result || result.length === 0) {
654
+ break;
655
+ }
656
+ for (const row of result || []) {
657
+ const callback = this[row.callback];
658
+ if (!callback) {
659
+ console.error(`callback ${row.callback} not found`);
660
+ continue;
661
+ }
662
+ const { connection, request, email } = agentContext.getStore() || {};
663
+ await agentContext.run(
664
+ {
665
+ agent: this,
666
+ connection,
667
+ request,
668
+ email
669
+ },
670
+ async () => {
671
+ await callback.bind(this)(JSON.parse(row.payload), row);
672
+ await this.dequeue(row.id);
673
+ }
674
+ );
675
+ }
676
+ }
677
+ this._flushingQueue = false;
678
+ }
679
+ /**
680
+ * Dequeue a task by ID
681
+ * @param id ID of the task to dequeue
682
+ */
683
+ async dequeue(id) {
684
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
685
+ }
686
+ /**
687
+ * Dequeue all tasks
688
+ */
689
+ async dequeueAll() {
690
+ this.sql`DELETE FROM cf_agents_queues`;
691
+ }
692
+ /**
693
+ * Dequeue all tasks by callback
694
+ * @param callback Name of the callback to dequeue
695
+ */
696
+ async dequeueAllByCallback(callback) {
697
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
698
+ }
699
+ /**
700
+ * Get a queued task by ID
701
+ * @param id ID of the task to get
702
+ * @returns The task or undefined if not found
703
+ */
704
+ async getQueue(id) {
705
+ const result = this.sql`
706
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
707
+ `;
708
+ return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
709
+ }
710
+ /**
711
+ * Get all queues by key and value
712
+ * @param key Key to filter by
713
+ * @param value Value to filter by
714
+ * @returns Array of matching QueueItem objects
715
+ */
716
+ async getQueues(key, value) {
717
+ const result = this.sql`
718
+ SELECT * FROM cf_agents_queues
719
+ `;
720
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
721
+ }
722
+ /**
723
+ * Schedule a task to be executed in the future
724
+ * @template T Type of the payload data
725
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
726
+ * @param callback Name of the method to call
727
+ * @param payload Data to pass to the callback
728
+ * @returns Schedule object representing the scheduled task
729
+ */
730
+ async schedule(when, callback, payload) {
731
+ const id = nanoid(9);
732
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
733
+ {
734
+ displayMessage: `Schedule ${schedule.id} created`,
735
+ id: nanoid(),
736
+ payload: {
737
+ callback,
738
+ id
739
+ },
740
+ timestamp: Date.now(),
741
+ type: "schedule:create"
742
+ },
743
+ this.ctx
744
+ );
745
+ if (typeof callback !== "string") {
746
+ throw new Error("Callback must be a string");
747
+ }
748
+ if (typeof this[callback] !== "function") {
749
+ throw new Error(`this.${callback} is not a function`);
750
+ }
751
+ if (when instanceof Date) {
752
+ const timestamp = Math.floor(when.getTime() / 1e3);
753
+ this.sql`
754
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
755
+ VALUES (${id}, ${callback}, ${JSON.stringify(
756
+ payload
757
+ )}, 'scheduled', ${timestamp})
758
+ `;
759
+ await this._scheduleNextAlarm();
760
+ const schedule = {
761
+ callback,
762
+ id,
763
+ payload,
764
+ time: timestamp,
765
+ type: "scheduled"
766
+ };
767
+ emitScheduleCreate(schedule);
768
+ return schedule;
769
+ }
770
+ if (typeof when === "number") {
771
+ const time = new Date(Date.now() + when * 1e3);
772
+ const timestamp = Math.floor(time.getTime() / 1e3);
773
+ this.sql`
774
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
775
+ VALUES (${id}, ${callback}, ${JSON.stringify(
776
+ payload
777
+ )}, 'delayed', ${when}, ${timestamp})
778
+ `;
779
+ await this._scheduleNextAlarm();
780
+ const schedule = {
781
+ callback,
782
+ delayInSeconds: when,
783
+ id,
784
+ payload,
785
+ time: timestamp,
786
+ type: "delayed"
787
+ };
788
+ emitScheduleCreate(schedule);
789
+ return schedule;
790
+ }
791
+ if (typeof when === "string") {
792
+ const nextExecutionTime = getNextCronTime(when);
793
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
794
+ this.sql`
795
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
796
+ VALUES (${id}, ${callback}, ${JSON.stringify(
797
+ payload
798
+ )}, 'cron', ${when}, ${timestamp})
799
+ `;
800
+ await this._scheduleNextAlarm();
801
+ const schedule = {
802
+ callback,
803
+ cron: when,
804
+ id,
805
+ payload,
806
+ time: timestamp,
807
+ type: "cron"
808
+ };
809
+ emitScheduleCreate(schedule);
810
+ return schedule;
811
+ }
812
+ throw new Error("Invalid schedule type");
813
+ }
814
+ /**
815
+ * Get a scheduled task by ID
816
+ * @template T Type of the payload data
817
+ * @param id ID of the scheduled task
818
+ * @returns The Schedule object or undefined if not found
819
+ */
820
+ async getSchedule(id) {
821
+ const result = this.sql`
822
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
823
+ `;
824
+ if (!result) {
825
+ console.error(`schedule ${id} not found`);
826
+ return void 0;
827
+ }
828
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
829
+ }
830
+ /**
831
+ * Get scheduled tasks matching the given criteria
832
+ * @template T Type of the payload data
833
+ * @param criteria Criteria to filter schedules
834
+ * @returns Array of matching Schedule objects
835
+ */
836
+ getSchedules(criteria = {}) {
837
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
838
+ const params = [];
839
+ if (criteria.id) {
840
+ query += " AND id = ?";
841
+ params.push(criteria.id);
842
+ }
843
+ if (criteria.type) {
844
+ query += " AND type = ?";
845
+ params.push(criteria.type);
846
+ }
847
+ if (criteria.timeRange) {
848
+ query += " AND time >= ? AND time <= ?";
849
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
850
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
851
+ params.push(
852
+ Math.floor(start.getTime() / 1e3),
853
+ Math.floor(end.getTime() / 1e3)
854
+ );
855
+ }
856
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
857
+ ...row,
858
+ payload: JSON.parse(row.payload)
859
+ }));
860
+ return result;
861
+ }
862
+ /**
863
+ * Cancel a scheduled task
864
+ * @param id ID of the task to cancel
865
+ * @returns true if the task was cancelled, false otherwise
866
+ */
867
+ async cancelSchedule(id) {
868
+ const schedule = await this.getSchedule(id);
869
+ if (schedule) {
870
+ this.observability?.emit(
871
+ {
872
+ displayMessage: `Schedule ${id} cancelled`,
873
+ id: nanoid(),
874
+ payload: {
875
+ callback: schedule.callback,
876
+ id: schedule.id
877
+ },
878
+ timestamp: Date.now(),
879
+ type: "schedule:cancel"
880
+ },
881
+ this.ctx
882
+ );
883
+ }
884
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
885
+ await this._scheduleNextAlarm();
886
+ return true;
887
+ }
888
+ async _scheduleNextAlarm() {
889
+ const result = this.sql`
890
+ SELECT time FROM cf_agents_schedules
891
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
892
+ ORDER BY time ASC
893
+ LIMIT 1
894
+ `;
895
+ if (!result) return;
896
+ if (result.length > 0 && "time" in result[0]) {
897
+ const nextTime = result[0].time * 1e3;
898
+ await this.ctx.storage.setAlarm(nextTime);
899
+ }
900
+ }
901
+ /**
902
+ * Destroy the Agent, removing all state and scheduled tasks
903
+ */
904
+ async destroy() {
905
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
906
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
907
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
908
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
909
+ await this.ctx.storage.deleteAlarm();
910
+ await this.ctx.storage.deleteAll();
911
+ this.ctx.abort("destroyed");
912
+ this.observability?.emit(
913
+ {
914
+ displayMessage: "Agent destroyed",
915
+ id: nanoid(),
916
+ payload: {},
917
+ timestamp: Date.now(),
918
+ type: "destroy"
919
+ },
920
+ this.ctx
921
+ );
922
+ }
923
+ /**
924
+ * Get all methods marked as callable on this Agent
925
+ * @returns A map of method names to their metadata
926
+ */
927
+ _isCallable(method) {
928
+ return callableMetadata.has(this[method]);
929
+ }
930
+ /**
931
+ * Connect to a new MCP Server
932
+ *
933
+ * @param url MCP Server SSE URL
934
+ * @param callbackHost Base host for the agent, used for the redirect URI.
935
+ * @param agentsPrefix agents routing prefix if not using `agents`
936
+ * @param options MCP client and transport (header) options
937
+ * @returns authUrl
938
+ */
939
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
940
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
941
+ const result = await this._connectToMcpServerInternal(
942
+ serverName,
943
+ url,
944
+ callbackUrl,
945
+ options
946
+ );
947
+ this.sql`
948
+ INSERT
949
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
950
+ VALUES (
951
+ ${result.id},
952
+ ${serverName},
953
+ ${url},
954
+ ${result.clientId ?? null},
955
+ ${result.authUrl ?? null},
956
+ ${callbackUrl},
957
+ ${options ? JSON.stringify(options) : null}
958
+ );
959
+ `;
960
+ this.broadcast(
961
+ JSON.stringify({
962
+ mcp: this.getMcpServers(),
963
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
964
+ })
965
+ );
966
+ return result;
967
+ }
968
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
969
+ const authProvider = new DurableObjectOAuthClientProvider(
970
+ this.ctx.storage,
971
+ this.name,
972
+ callbackUrl
973
+ );
974
+ if (reconnect) {
975
+ authProvider.serverId = reconnect.id;
976
+ if (reconnect.oauthClientId) {
977
+ authProvider.clientId = reconnect.oauthClientId;
978
+ }
979
+ }
980
+ let headerTransportOpts = {};
981
+ if (options?.transport?.headers) {
982
+ headerTransportOpts = {
983
+ eventSourceInit: {
984
+ fetch: (url2, init) => fetch(url2, {
985
+ ...init,
986
+ headers: options?.transport?.headers
987
+ })
988
+ },
989
+ requestInit: {
990
+ headers: options?.transport?.headers
991
+ }
992
+ };
993
+ }
994
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
995
+ client: options?.client,
996
+ reconnect,
997
+ transport: {
998
+ ...headerTransportOpts,
999
+ authProvider
1000
+ }
1001
+ });
1002
+ return {
1003
+ authUrl,
1004
+ clientId,
1005
+ id
1006
+ };
1007
+ }
1008
+ async removeMcpServer(id) {
1009
+ this.mcp.closeConnection(id);
1010
+ this.sql`
1011
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1012
+ `;
1013
+ this.broadcast(
1014
+ JSON.stringify({
1015
+ mcp: this.getMcpServers(),
1016
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
1017
+ })
1018
+ );
1019
+ }
1020
+ getMcpServers() {
1021
+ const mcpState = {
1022
+ prompts: this.mcp.listPrompts(),
1023
+ resources: this.mcp.listResources(),
1024
+ servers: {},
1025
+ tools: this.mcp.listTools()
1026
+ };
1027
+ const servers = this.sql`
1028
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1029
+ `;
1030
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1031
+ for (const server of servers) {
1032
+ const serverConn = this.mcp.mcpConnections[server.id];
1033
+ mcpState.servers[server.id] = {
1034
+ auth_url: server.auth_url,
1035
+ capabilities: serverConn?.serverCapabilities ?? null,
1036
+ instructions: serverConn?.instructions ?? null,
1037
+ name: server.name,
1038
+ server_url: server.server_url,
1039
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1040
+ state: serverConn?.connectionState ?? "authenticating"
1041
+ };
1042
+ }
1043
+ }
1044
+ return mcpState;
1045
+ }
1046
+ };
1047
+ /**
1048
+ * Agent configuration options
1049
+ */
1050
+ _Agent.options = {
1051
+ /** Whether the Agent should hibernate when inactive */
1052
+ hibernate: true
1053
+ // default to hibernate
1054
+ };
1055
+ var Agent = _Agent;
1056
+ async function routeAgentRequest(request, env, options) {
1057
+ const corsHeaders = options?.cors === true ? {
1058
+ "Access-Control-Allow-Credentials": "true",
1059
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1060
+ "Access-Control-Allow-Origin": "*",
1061
+ "Access-Control-Max-Age": "86400"
1062
+ } : options?.cors;
1063
+ if (request.method === "OPTIONS") {
1064
+ if (corsHeaders) {
1065
+ return new Response(null, {
1066
+ headers: corsHeaders
1067
+ });
1068
+ }
1069
+ console.warn(
1070
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1071
+ );
1072
+ }
1073
+ let response = await routePartykitRequest(
1074
+ request,
1075
+ env,
1076
+ {
1077
+ prefix: "agents",
1078
+ ...options
1079
+ }
1080
+ );
1081
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
1082
+ response = new Response(response.body, {
1083
+ headers: {
1084
+ ...response.headers,
1085
+ ...corsHeaders
1086
+ }
1087
+ });
1088
+ }
1089
+ return response;
1090
+ }
1091
+ function createHeaderBasedEmailResolver() {
1092
+ return async (email, _env) => {
1093
+ const messageId = email.headers.get("message-id");
1094
+ if (messageId) {
1095
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1096
+ if (messageIdMatch) {
1097
+ const [, agentId2, domain] = messageIdMatch;
1098
+ const agentName2 = domain.split(".")[0];
1099
+ return { agentName: agentName2, agentId: agentId2 };
1100
+ }
1101
+ }
1102
+ const references = email.headers.get("references");
1103
+ if (references) {
1104
+ const referencesMatch = references.match(
1105
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1106
+ );
1107
+ if (referencesMatch) {
1108
+ const [, base64Id, domain] = referencesMatch;
1109
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
1110
+ const agentName2 = domain.split(".")[0];
1111
+ return { agentName: agentName2, agentId: agentId2 };
1112
+ }
1113
+ }
1114
+ const agentName = email.headers.get("x-agent-name");
1115
+ const agentId = email.headers.get("x-agent-id");
1116
+ if (agentName && agentId) {
1117
+ return { agentName, agentId };
1118
+ }
1119
+ return null;
1120
+ };
1121
+ }
1122
+ function createAddressBasedEmailResolver(defaultAgentName) {
1123
+ return async (email, _env) => {
1124
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1125
+ if (!emailMatch) {
1126
+ return null;
1127
+ }
1128
+ const [, localPart, subAddress] = emailMatch;
1129
+ if (subAddress) {
1130
+ return {
1131
+ agentName: localPart,
1132
+ agentId: subAddress
1133
+ };
1134
+ }
1135
+ return {
1136
+ agentName: defaultAgentName,
1137
+ agentId: localPart
1138
+ };
1139
+ };
1140
+ }
1141
+ function createCatchAllEmailResolver(agentName, agentId) {
1142
+ return async () => ({ agentName, agentId });
1143
+ }
1144
+ var agentMapCache = /* @__PURE__ */ new WeakMap();
1145
+ async function routeAgentEmail(email, env, options) {
1146
+ const routingInfo = await options.resolver(email, env);
1147
+ if (!routingInfo) {
1148
+ console.warn("No routing information found for email, dropping message");
1149
+ return;
1150
+ }
1151
+ if (!agentMapCache.has(env)) {
1152
+ const map = {};
1153
+ for (const [key, value] of Object.entries(env)) {
1154
+ if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1155
+ map[key] = value;
1156
+ map[camelCaseToKebabCase(key)] = value;
1157
+ }
1158
+ }
1159
+ agentMapCache.set(env, map);
1160
+ }
1161
+ const agentMap = agentMapCache.get(env);
1162
+ const namespace = agentMap[routingInfo.agentName];
1163
+ if (!namespace) {
1164
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1165
+ throw new Error(
1166
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1167
+ );
1168
+ }
1169
+ const agent = await getAgentByName(
1170
+ namespace,
1171
+ routingInfo.agentId
1172
+ );
1173
+ const serialisableEmail = {
1174
+ getRaw: async () => {
1175
+ const reader = email.raw.getReader();
1176
+ const chunks = [];
1177
+ let done = false;
1178
+ while (!done) {
1179
+ const { value, done: readerDone } = await reader.read();
1180
+ done = readerDone;
1181
+ if (value) {
1182
+ chunks.push(value);
1183
+ }
1184
+ }
1185
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1186
+ const combined = new Uint8Array(totalLength);
1187
+ let offset = 0;
1188
+ for (const chunk of chunks) {
1189
+ combined.set(chunk, offset);
1190
+ offset += chunk.length;
1191
+ }
1192
+ return combined;
1193
+ },
1194
+ headers: email.headers,
1195
+ rawSize: email.rawSize,
1196
+ setReject: (reason) => {
1197
+ email.setReject(reason);
1198
+ },
1199
+ forward: (rcptTo, headers) => {
1200
+ return email.forward(rcptTo, headers);
1201
+ },
1202
+ reply: (options2) => {
1203
+ return email.reply(
1204
+ new EmailMessage(options2.from, options2.to, options2.raw)
1205
+ );
1206
+ },
1207
+ from: email.from,
1208
+ to: email.to
1209
+ };
1210
+ await agent._onEmail(serialisableEmail);
1211
+ }
1212
+ async function getAgentByName(namespace, name, options) {
1213
+ return getServerByName(namespace, name, options);
1214
+ }
1215
+ var StreamingResponse = class {
1216
+ constructor(connection, id) {
1217
+ this._closed = false;
1218
+ this._connection = connection;
1219
+ this._id = id;
1220
+ }
1221
+ /**
1222
+ * Send a chunk of data to the client
1223
+ * @param chunk The data to send
1224
+ */
1225
+ send(chunk) {
1226
+ if (this._closed) {
1227
+ throw new Error("StreamingResponse is already closed");
1228
+ }
1229
+ const response = {
1230
+ done: false,
1231
+ id: this._id,
1232
+ result: chunk,
1233
+ success: true,
1234
+ type: "rpc" /* RPC */
1235
+ };
1236
+ this._connection.send(JSON.stringify(response));
1237
+ }
1238
+ /**
1239
+ * End the stream and send the final chunk (if any)
1240
+ * @param finalChunk Optional final chunk of data to send
1241
+ */
1242
+ end(finalChunk) {
1243
+ if (this._closed) {
1244
+ throw new Error("StreamingResponse is already closed");
1245
+ }
1246
+ this._closed = true;
1247
+ const response = {
1248
+ done: true,
1249
+ id: this._id,
1250
+ result: finalChunk,
1251
+ success: true,
1252
+ type: "rpc" /* RPC */
1253
+ };
1254
+ this._connection.send(JSON.stringify(response));
1255
+ }
1256
+ };
1257
+
1258
+ // src/observability/index.ts
1259
+ var genericObservability = {
1260
+ emit(event) {
1261
+ if (isLocalMode()) {
1262
+ console.log(event.displayMessage);
1263
+ return;
1264
+ }
1265
+ console.log(event);
1266
+ }
1267
+ };
1268
+ var localMode = false;
1269
+ function isLocalMode() {
1270
+ if (localMode) {
1271
+ return true;
1272
+ }
1273
+ const { request } = getCurrentAgent();
1274
+ if (!request) {
1275
+ return false;
1276
+ }
1277
+ const url = new URL(request.url);
1278
+ localMode = url.hostname === "localhost";
1279
+ return localMode;
1280
+ }
1281
+
1282
+ export {
1283
+ genericObservability,
1284
+ callable,
1285
+ unstable_callable,
1286
+ getCurrentAgent,
1287
+ Agent,
1288
+ routeAgentRequest,
1289
+ createHeaderBasedEmailResolver,
1290
+ createAddressBasedEmailResolver,
1291
+ createCatchAllEmailResolver,
1292
+ routeAgentEmail,
1293
+ getAgentByName,
1294
+ StreamingResponse
1295
+ };
1296
+ //# sourceMappingURL=chunk-YDUDMOL6.js.map