agents 0.0.0-eeb70e2 → 0.0.0-f0c6dce

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