agents 0.0.0-c5e3a32 → 0.0.0-c6d9bf1

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 (72) hide show
  1. package/README.md +234 -6
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +13 -9
  5. package/dist/ai-chat-agent.js +444 -60
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.d.ts +152 -0
  8. package/dist/ai-chat-v5-migration.js +20 -0
  9. package/dist/ai-chat-v5-migration.js.map +1 -0
  10. package/dist/ai-react.d.ts +69 -71
  11. package/dist/ai-react.js +252 -99
  12. package/dist/ai-react.js.map +1 -1
  13. package/dist/ai-types.d.ts +37 -19
  14. package/dist/ai-types.js +7 -0
  15. package/dist/ccip-CMBYN64O.js +15 -0
  16. package/dist/ccip-CMBYN64O.js.map +1 -0
  17. package/dist/{chunk-EDUDXISR.js → chunk-254F4GDT.js} +321 -126
  18. package/dist/chunk-254F4GDT.js.map +1 -0
  19. package/dist/chunk-3OT2NNEW.js +941 -0
  20. package/dist/chunk-3OT2NNEW.js.map +1 -0
  21. package/dist/chunk-5Y6BEZDY.js +276 -0
  22. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  23. package/dist/chunk-BER7KXUJ.js +18 -0
  24. package/dist/chunk-BER7KXUJ.js.map +1 -0
  25. package/dist/chunk-JJBFIGUC.js +5202 -0
  26. package/dist/chunk-JJBFIGUC.js.map +1 -0
  27. package/dist/chunk-PR4QN5HX.js +43 -0
  28. package/dist/chunk-PR4QN5HX.js.map +1 -0
  29. package/dist/{chunk-KUH345EY.js → chunk-QEVM4BVL.js} +5 -5
  30. package/dist/chunk-QEVM4BVL.js.map +1 -0
  31. package/dist/chunk-TYAY6AU6.js +159 -0
  32. package/dist/chunk-TYAY6AU6.js.map +1 -0
  33. package/dist/chunk-UJVEAURM.js +150 -0
  34. package/dist/chunk-UJVEAURM.js.map +1 -0
  35. package/dist/{chunk-PVQZBKN7.js → chunk-Z44WASMA.js} +11 -3
  36. package/dist/chunk-Z44WASMA.js.map +1 -0
  37. package/dist/client-DVoPb3-C.d.ts +5120 -0
  38. package/dist/client.js +3 -1
  39. package/dist/codemode/ai.d.ts +25 -0
  40. package/dist/codemode/ai.js +5112 -0
  41. package/dist/codemode/ai.js.map +1 -0
  42. package/dist/index.d.ts +550 -31
  43. package/dist/index.js +8 -4
  44. package/dist/mcp/client.d.ts +10 -1053
  45. package/dist/mcp/client.js +2 -1
  46. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  47. package/dist/mcp/do-oauth-client-provider.js +2 -1
  48. package/dist/mcp/index.d.ts +58 -63
  49. package/dist/mcp/index.js +954 -638
  50. package/dist/mcp/index.js.map +1 -1
  51. package/dist/mcp/x402.d.ts +39 -0
  52. package/dist/mcp/x402.js +3195 -0
  53. package/dist/mcp/x402.js.map +1 -0
  54. package/dist/mcp-BH1fJeiU.d.ts +58 -0
  55. package/dist/observability/index.d.ts +34 -12
  56. package/dist/observability/index.js +6 -4
  57. package/dist/react.d.ts +16 -8
  58. package/dist/react.js +107 -7
  59. package/dist/react.js.map +1 -1
  60. package/dist/schedule.d.ts +83 -9
  61. package/dist/schedule.js +17 -2
  62. package/dist/schedule.js.map +1 -1
  63. package/dist/secp256k1-M22GZP2U.js +2193 -0
  64. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  65. package/package.json +32 -9
  66. package/src/index.ts +453 -154
  67. package/dist/chunk-EDUDXISR.js.map +0 -1
  68. package/dist/chunk-KUH345EY.js.map +0 -1
  69. package/dist/chunk-MW5BQ2FW.js +0 -469
  70. package/dist/chunk-MW5BQ2FW.js.map +0 -1
  71. package/dist/chunk-PVQZBKN7.js.map +0 -1
  72. package/dist/index-DukU3sIa.d.ts +0 -571
@@ -1,12 +1,13 @@
1
1
  import {
2
+ DisposableStore,
2
3
  MCPClientManager
3
- } from "./chunk-MW5BQ2FW.js";
4
+ } from "./chunk-3OT2NNEW.js";
4
5
  import {
5
6
  DurableObjectOAuthClientProvider
6
- } from "./chunk-PVQZBKN7.js";
7
+ } from "./chunk-Z44WASMA.js";
7
8
  import {
8
9
  camelCaseToKebabCase
9
- } from "./chunk-KUH345EY.js";
10
+ } from "./chunk-QEVM4BVL.js";
10
11
 
11
12
  // src/index.ts
12
13
  import { AsyncLocalStorage } from "async_hooks";
@@ -19,13 +20,13 @@ import {
19
20
  routePartykitRequest
20
21
  } from "partyserver";
21
22
  function isRPCRequest(msg) {
22
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
23
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" /* RPC */ && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
23
24
  }
24
25
  function isStateUpdateMessage(msg) {
25
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
26
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" /* CF_AGENT_STATE */ && "state" in msg;
26
27
  }
27
28
  var callableMetadata = /* @__PURE__ */ new Map();
28
- function unstable_callable(metadata = {}) {
29
+ function callable(metadata = {}) {
29
30
  return function callableDecorator(target, context) {
30
31
  if (!callableMetadata.has(target)) {
31
32
  callableMetadata.set(target, metadata);
@@ -33,6 +34,16 @@ function unstable_callable(metadata = {}) {
33
34
  return target;
34
35
  };
35
36
  }
37
+ var didWarnAboutUnstableCallable = false;
38
+ var unstable_callable = (metadata = {}) => {
39
+ if (!didWarnAboutUnstableCallable) {
40
+ didWarnAboutUnstableCallable = true;
41
+ console.warn(
42
+ "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
43
+ );
44
+ }
45
+ callable(metadata);
46
+ };
36
47
  function getNextCronTime(cron) {
37
48
  const interval = parseCronExpression(cron);
38
49
  return interval.getNextDate();
@@ -55,7 +66,10 @@ function getCurrentAgent() {
55
66
  }
56
67
  function withAgentContext(method) {
57
68
  return function(...args) {
58
- const { connection, request, email } = getCurrentAgent();
69
+ const { connection, request, email, agent } = getCurrentAgent();
70
+ if (agent === this) {
71
+ return method.apply(this, args);
72
+ }
59
73
  return agentContext.run({ agent: this, connection, request, email }, () => {
60
74
  return method.apply(this, args);
61
75
  });
@@ -65,8 +79,12 @@ var _Agent = class _Agent extends Server {
65
79
  constructor(ctx, env) {
66
80
  super(ctx, env);
67
81
  this._state = DEFAULT_STATE;
82
+ this._disposables = new DisposableStore();
68
83
  this._ParentClass = Object.getPrototypeOf(this).constructor;
69
- this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
84
+ this.mcp = new MCPClientManager(
85
+ this._ParentClass.name,
86
+ "0.0.1"
87
+ );
70
88
  /**
71
89
  * Initial state for the Agent
72
90
  * Override to provide default state values
@@ -76,6 +94,7 @@ var _Agent = class _Agent extends Server {
76
94
  * The observability implementation to use for the Agent
77
95
  */
78
96
  this.observability = genericObservability;
97
+ this._flushingQueue = false;
79
98
  /**
80
99
  * Method called when an alarm fires.
81
100
  * Executes any scheduled tasks that are due.
@@ -109,7 +128,10 @@ var _Agent = class _Agent extends Server {
109
128
  {
110
129
  displayMessage: `Schedule ${row.id} executed`,
111
130
  id: nanoid(),
112
- payload: row,
131
+ payload: {
132
+ callback: row.callback,
133
+ id: row.id
134
+ },
113
135
  timestamp: Date.now(),
114
136
  type: "schedule:execute"
115
137
  },
@@ -136,13 +158,34 @@ var _Agent = class _Agent extends Server {
136
158
  }
137
159
  await this._scheduleNextAlarm();
138
160
  };
161
+ if (!wrappedClasses.has(this.constructor)) {
162
+ this._autoWrapCustomMethods();
163
+ wrappedClasses.add(this.constructor);
164
+ }
165
+ this._disposables.add(
166
+ this.mcp.onConnected(async () => {
167
+ this.broadcastMcpServers();
168
+ })
169
+ );
170
+ this._disposables.add(
171
+ this.mcp.onObservabilityEvent((event) => {
172
+ this.observability?.emit(event);
173
+ })
174
+ );
139
175
  this.sql`
140
176
  CREATE TABLE IF NOT EXISTS cf_agents_state (
141
177
  id TEXT PRIMARY KEY NOT NULL,
142
178
  state TEXT
143
179
  )
144
180
  `;
145
- this._autoWrapCustomMethods();
181
+ this.sql`
182
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
183
+ id TEXT PRIMARY KEY NOT NULL,
184
+ payload TEXT,
185
+ callback TEXT,
186
+ created_at INTEGER DEFAULT (unixepoch())
187
+ )
188
+ `;
146
189
  void this.ctx.blockConcurrencyWhile(async () => {
147
190
  return this._tryCatch(async () => {
148
191
  this.sql`
@@ -177,17 +220,16 @@ var _Agent = class _Agent extends Server {
177
220
  { agent: this, connection: void 0, request, email: void 0 },
178
221
  async () => {
179
222
  if (this.mcp.isCallbackRequest(request)) {
180
- await this.mcp.handleCallbackRequest(request);
181
- this.broadcast(
182
- JSON.stringify({
183
- mcp: this.getMcpServers(),
184
- type: "cf_agent_mcp_servers"
185
- })
186
- );
187
- return new Response("<script>window.close();</script>", {
188
- headers: { "content-type": "text/html" },
189
- status: 200
190
- });
223
+ const result = await this.mcp.handleCallbackRequest(request);
224
+ this.broadcastMcpServers();
225
+ if (result.authSuccess) {
226
+ this.mcp.establishConnection(result.serverId).catch((error) => {
227
+ console.error("Background connection failed:", error);
228
+ }).finally(() => {
229
+ this.broadcastMcpServers();
230
+ });
231
+ }
232
+ return this.handleOAuthCallbackResponse(result, request);
191
233
  }
192
234
  return this._tryCatch(() => _onRequest(request));
193
235
  }
@@ -233,10 +275,8 @@ var _Agent = class _Agent extends Server {
233
275
  displayMessage: `RPC call to ${method}`,
234
276
  id: nanoid(),
235
277
  payload: {
236
- args,
237
278
  method,
238
- streaming: metadata?.streaming,
239
- success: true
279
+ streaming: metadata?.streaming
240
280
  },
241
281
  timestamp: Date.now(),
242
282
  type: "rpc"
@@ -248,7 +288,7 @@ var _Agent = class _Agent extends Server {
248
288
  id,
249
289
  result,
250
290
  success: true,
251
- type: "rpc"
291
+ type: "rpc" /* RPC */
252
292
  };
253
293
  connection.send(JSON.stringify(response));
254
294
  } catch (e) {
@@ -256,7 +296,7 @@ var _Agent = class _Agent extends Server {
256
296
  error: e instanceof Error ? e.message : "Unknown error occurred",
257
297
  id: parsed.id,
258
298
  success: false,
259
- type: "rpc"
299
+ type: "rpc" /* RPC */
260
300
  };
261
301
  connection.send(JSON.stringify(response));
262
302
  console.error("RPC error:", e);
@@ -271,41 +311,39 @@ var _Agent = class _Agent extends Server {
271
311
  this.onConnect = (connection, ctx2) => {
272
312
  return agentContext.run(
273
313
  { agent: this, connection, request: ctx2.request, email: void 0 },
274
- async () => {
275
- setTimeout(() => {
276
- if (this.state) {
277
- connection.send(
278
- JSON.stringify({
279
- state: this.state,
280
- type: "cf_agent_state"
281
- })
282
- );
283
- }
314
+ () => {
315
+ if (this.state) {
284
316
  connection.send(
285
317
  JSON.stringify({
286
- mcp: this.getMcpServers(),
287
- type: "cf_agent_mcp_servers"
318
+ state: this.state,
319
+ type: "cf_agent_state" /* CF_AGENT_STATE */
288
320
  })
289
321
  );
290
- this.observability?.emit(
291
- {
292
- displayMessage: "Connection established",
293
- id: nanoid(),
294
- payload: {
295
- connectionId: connection.id
296
- },
297
- timestamp: Date.now(),
298
- type: "connect"
322
+ }
323
+ connection.send(
324
+ JSON.stringify({
325
+ mcp: this.getMcpServers(),
326
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
327
+ })
328
+ );
329
+ this.observability?.emit(
330
+ {
331
+ displayMessage: "Connection established",
332
+ id: nanoid(),
333
+ payload: {
334
+ connectionId: connection.id
299
335
  },
300
- this.ctx
301
- );
302
- return this._tryCatch(() => _onConnect(connection, ctx2));
303
- }, 20);
336
+ timestamp: Date.now(),
337
+ type: "connect"
338
+ },
339
+ this.ctx
340
+ );
341
+ return this._tryCatch(() => _onConnect(connection, ctx2));
304
342
  }
305
343
  );
306
344
  };
307
345
  const _onStart = this.onStart.bind(this);
308
- this.onStart = async () => {
346
+ this.onStart = async (props) => {
309
347
  return agentContext.run(
310
348
  {
311
349
  agent: this,
@@ -314,13 +352,21 @@ var _Agent = class _Agent extends Server {
314
352
  email: void 0
315
353
  },
316
354
  async () => {
317
- const servers = this.sql`
355
+ await this._tryCatch(() => {
356
+ const servers = this.sql`
318
357
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
319
358
  `;
320
- if (servers && Array.isArray(servers) && servers.length > 0) {
321
- Promise.allSettled(
322
- servers.map((server) => {
323
- return this._connectToMcpServerInternal(
359
+ this.broadcastMcpServers();
360
+ if (servers && Array.isArray(servers) && servers.length > 0) {
361
+ servers.forEach((server) => {
362
+ if (server.callback_url) {
363
+ this.mcp.registerCallbackUrl(
364
+ `${server.callback_url}/${server.id}`
365
+ );
366
+ }
367
+ });
368
+ servers.forEach((server) => {
369
+ this._connectToMcpServerInternal(
324
370
  server.name,
325
371
  server.server_url,
326
372
  server.callback_url,
@@ -329,18 +375,19 @@ var _Agent = class _Agent extends Server {
329
375
  id: server.id,
330
376
  oauthClientId: server.client_id ?? void 0
331
377
  }
332
- );
333
- })
334
- ).then((_results) => {
335
- this.broadcast(
336
- JSON.stringify({
337
- mcp: this.getMcpServers(),
338
- type: "cf_agent_mcp_servers"
339
- })
340
- );
341
- });
342
- }
343
- await this._tryCatch(() => _onStart());
378
+ ).then(() => {
379
+ this.broadcastMcpServers();
380
+ }).catch((error) => {
381
+ console.error(
382
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
383
+ error
384
+ );
385
+ this.broadcastMcpServers();
386
+ });
387
+ });
388
+ }
389
+ return _onStart(props);
390
+ });
344
391
  }
345
392
  );
346
393
  };
@@ -391,7 +438,6 @@ var _Agent = class _Agent extends Server {
391
438
  }
392
439
  }
393
440
  _setStateInternal(state, source = "server") {
394
- const previousState = this._state;
395
441
  this._state = state;
396
442
  this.sql`
397
443
  INSERT OR REPLACE INTO cf_agents_state (id, state)
@@ -404,7 +450,7 @@ var _Agent = class _Agent extends Server {
404
450
  this.broadcast(
405
451
  JSON.stringify({
406
452
  state,
407
- type: "cf_agent_state"
453
+ type: "cf_agent_state" /* CF_AGENT_STATE */
408
454
  }),
409
455
  source !== "server" ? [source.id] : []
410
456
  );
@@ -417,10 +463,7 @@ var _Agent = class _Agent extends Server {
417
463
  {
418
464
  displayMessage: "State updated",
419
465
  id: nanoid(),
420
- payload: {
421
- previousState,
422
- state
423
- },
466
+ payload: {},
424
467
  timestamp: Date.now(),
425
468
  type: "state:update"
426
469
  },
@@ -537,28 +580,22 @@ var _Agent = class _Agent extends Server {
537
580
  while (proto && proto !== Object.prototype && depth < 10) {
538
581
  const methodNames = Object.getOwnPropertyNames(proto);
539
582
  for (const methodName of methodNames) {
540
- if (baseMethods.has(methodName) || methodName.startsWith("_") || typeof this[methodName] !== "function") {
583
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
584
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") {
541
585
  continue;
542
586
  }
543
- if (!baseMethods.has(methodName)) {
544
- const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
545
- if (descriptor && typeof descriptor.value === "function") {
546
- const wrappedFunction = withAgentContext(
547
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
548
- this[methodName]
549
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
550
- );
551
- if (this._isCallable(methodName)) {
552
- callableMetadata.set(
553
- wrappedFunction,
554
- callableMetadata.get(
555
- this[methodName]
556
- )
557
- );
558
- }
559
- this.constructor.prototype[methodName] = wrappedFunction;
560
- }
587
+ const wrappedFunction = withAgentContext(
588
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
589
+ this[methodName]
590
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
591
+ );
592
+ if (this._isCallable(methodName)) {
593
+ callableMetadata.set(
594
+ wrappedFunction,
595
+ callableMetadata.get(this[methodName])
596
+ );
561
597
  }
598
+ this.constructor.prototype[methodName] = wrappedFunction;
562
599
  }
563
600
  proto = Object.getPrototypeOf(proto);
564
601
  depth++;
@@ -589,6 +626,108 @@ var _Agent = class _Agent extends Server {
589
626
  render() {
590
627
  throw new Error("Not implemented");
591
628
  }
629
+ /**
630
+ * Queue a task to be executed in the future
631
+ * @param payload Payload to pass to the callback
632
+ * @param callback Name of the method to call
633
+ * @returns The ID of the queued task
634
+ */
635
+ async queue(callback, payload) {
636
+ const id = nanoid(9);
637
+ if (typeof callback !== "string") {
638
+ throw new Error("Callback must be a string");
639
+ }
640
+ if (typeof this[callback] !== "function") {
641
+ throw new Error(`this.${callback} is not a function`);
642
+ }
643
+ this.sql`
644
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
645
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
646
+ `;
647
+ void this._flushQueue().catch((e) => {
648
+ console.error("Error flushing queue:", e);
649
+ });
650
+ return id;
651
+ }
652
+ async _flushQueue() {
653
+ if (this._flushingQueue) {
654
+ return;
655
+ }
656
+ this._flushingQueue = true;
657
+ while (true) {
658
+ const result = this.sql`
659
+ SELECT * FROM cf_agents_queues
660
+ ORDER BY created_at ASC
661
+ `;
662
+ if (!result || result.length === 0) {
663
+ break;
664
+ }
665
+ for (const row of result || []) {
666
+ const callback = this[row.callback];
667
+ if (!callback) {
668
+ console.error(`callback ${row.callback} not found`);
669
+ continue;
670
+ }
671
+ const { connection, request, email } = agentContext.getStore() || {};
672
+ await agentContext.run(
673
+ {
674
+ agent: this,
675
+ connection,
676
+ request,
677
+ email
678
+ },
679
+ async () => {
680
+ await callback.bind(this)(JSON.parse(row.payload), row);
681
+ await this.dequeue(row.id);
682
+ }
683
+ );
684
+ }
685
+ }
686
+ this._flushingQueue = false;
687
+ }
688
+ /**
689
+ * Dequeue a task by ID
690
+ * @param id ID of the task to dequeue
691
+ */
692
+ async dequeue(id) {
693
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
694
+ }
695
+ /**
696
+ * Dequeue all tasks
697
+ */
698
+ async dequeueAll() {
699
+ this.sql`DELETE FROM cf_agents_queues`;
700
+ }
701
+ /**
702
+ * Dequeue all tasks by callback
703
+ * @param callback Name of the callback to dequeue
704
+ */
705
+ async dequeueAllByCallback(callback) {
706
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
707
+ }
708
+ /**
709
+ * Get a queued task by ID
710
+ * @param id ID of the task to get
711
+ * @returns The task or undefined if not found
712
+ */
713
+ async getQueue(id) {
714
+ const result = this.sql`
715
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
716
+ `;
717
+ return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
718
+ }
719
+ /**
720
+ * Get all queues by key and value
721
+ * @param key Key to filter by
722
+ * @param value Value to filter by
723
+ * @returns Array of matching QueueItem objects
724
+ */
725
+ async getQueues(key, value) {
726
+ const result = this.sql`
727
+ SELECT * FROM cf_agents_queues
728
+ `;
729
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
730
+ }
592
731
  /**
593
732
  * Schedule a task to be executed in the future
594
733
  * @template T Type of the payload data
@@ -603,7 +742,10 @@ var _Agent = class _Agent extends Server {
603
742
  {
604
743
  displayMessage: `Schedule ${schedule.id} created`,
605
744
  id: nanoid(),
606
- payload: schedule,
745
+ payload: {
746
+ callback,
747
+ id
748
+ },
607
749
  timestamp: Date.now(),
608
750
  type: "schedule:create"
609
751
  },
@@ -738,7 +880,10 @@ var _Agent = class _Agent extends Server {
738
880
  {
739
881
  displayMessage: `Schedule ${id} cancelled`,
740
882
  id: nanoid(),
741
- payload: schedule,
883
+ payload: {
884
+ callback: schedule.callback,
885
+ id: schedule.id
886
+ },
742
887
  timestamp: Date.now(),
743
888
  type: "schedule:cancel"
744
889
  },
@@ -751,9 +896,9 @@ var _Agent = class _Agent extends Server {
751
896
  }
752
897
  async _scheduleNextAlarm() {
753
898
  const result = this.sql`
754
- SELECT time FROM cf_agents_schedules
899
+ SELECT time FROM cf_agents_schedules
755
900
  WHERE time > ${Math.floor(Date.now() / 1e3)}
756
- ORDER BY time ASC
901
+ ORDER BY time ASC
757
902
  LIMIT 1
758
903
  `;
759
904
  if (!result) return;
@@ -769,8 +914,11 @@ var _Agent = class _Agent extends Server {
769
914
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
770
915
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
771
916
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
917
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
772
918
  await this.ctx.storage.deleteAlarm();
773
919
  await this.ctx.storage.deleteAll();
920
+ this._disposables.dispose();
921
+ await this.mcp.dispose?.();
774
922
  this.ctx.abort("destroyed");
775
923
  this.observability?.emit(
776
924
  {
@@ -793,14 +941,26 @@ var _Agent = class _Agent extends Server {
793
941
  /**
794
942
  * Connect to a new MCP Server
795
943
  *
944
+ * @param serverName Name of the MCP server
796
945
  * @param url MCP Server SSE URL
797
- * @param callbackHost Base host for the agent, used for the redirect URI.
946
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
798
947
  * @param agentsPrefix agents routing prefix if not using `agents`
799
- * @param options MCP client and transport (header) options
948
+ * @param options MCP client and transport options
800
949
  * @returns authUrl
801
950
  */
802
951
  async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
803
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
952
+ let resolvedCallbackHost = callbackHost;
953
+ if (!resolvedCallbackHost) {
954
+ const { request } = getCurrentAgent();
955
+ if (!request) {
956
+ throw new Error(
957
+ "callbackHost is required when not called within a request context"
958
+ );
959
+ }
960
+ const requestUrl = new URL(request.url);
961
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
962
+ }
963
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
804
964
  const result = await this._connectToMcpServerInternal(
805
965
  serverName,
806
966
  url,
@@ -820,12 +980,7 @@ var _Agent = class _Agent extends Server {
820
980
  ${options ? JSON.stringify(options) : null}
821
981
  );
822
982
  `;
823
- this.broadcast(
824
- JSON.stringify({
825
- mcp: this.getMcpServers(),
826
- type: "cf_agent_mcp_servers"
827
- })
828
- );
983
+ this.broadcastMcpServers();
829
984
  return result;
830
985
  }
831
986
  async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
@@ -840,6 +995,7 @@ var _Agent = class _Agent extends Server {
840
995
  authProvider.clientId = reconnect.oauthClientId;
841
996
  }
842
997
  }
998
+ const transportType = options?.transport?.type ?? "auto";
843
999
  let headerTransportOpts = {};
844
1000
  if (options?.transport?.headers) {
845
1001
  headerTransportOpts = {
@@ -859,7 +1015,8 @@ var _Agent = class _Agent extends Server {
859
1015
  reconnect,
860
1016
  transport: {
861
1017
  ...headerTransportOpts,
862
- authProvider
1018
+ authProvider,
1019
+ type: transportType
863
1020
  }
864
1021
  });
865
1022
  return {
@@ -870,15 +1027,11 @@ var _Agent = class _Agent extends Server {
870
1027
  }
871
1028
  async removeMcpServer(id) {
872
1029
  this.mcp.closeConnection(id);
1030
+ this.mcp.unregisterCallbackUrl(id);
873
1031
  this.sql`
874
1032
  DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
875
1033
  `;
876
- this.broadcast(
877
- JSON.stringify({
878
- mcp: this.getMcpServers(),
879
- type: "cf_agent_mcp_servers"
880
- })
881
- );
1034
+ this.broadcastMcpServers();
882
1035
  }
883
1036
  getMcpServers() {
884
1037
  const mcpState = {
@@ -906,6 +1059,36 @@ var _Agent = class _Agent extends Server {
906
1059
  }
907
1060
  return mcpState;
908
1061
  }
1062
+ broadcastMcpServers() {
1063
+ this.broadcast(
1064
+ JSON.stringify({
1065
+ mcp: this.getMcpServers(),
1066
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
1067
+ })
1068
+ );
1069
+ }
1070
+ /**
1071
+ * Handle OAuth callback response using MCPClientManager configuration
1072
+ * @param result OAuth callback result
1073
+ * @param request The original request (needed for base URL)
1074
+ * @returns Response for the OAuth callback
1075
+ */
1076
+ handleOAuthCallbackResponse(result, request) {
1077
+ const config = this.mcp.getOAuthCallbackConfig();
1078
+ if (config?.customHandler) {
1079
+ return config.customHandler(result);
1080
+ }
1081
+ if (config?.successRedirect && result.authSuccess) {
1082
+ return Response.redirect(config.successRedirect);
1083
+ }
1084
+ if (config?.errorRedirect && !result.authSuccess) {
1085
+ return Response.redirect(
1086
+ `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`
1087
+ );
1088
+ }
1089
+ const baseUrl = new URL(request.url).origin;
1090
+ return Response.redirect(baseUrl);
1091
+ }
909
1092
  };
910
1093
  /**
911
1094
  * Agent configuration options
@@ -916,6 +1099,7 @@ _Agent.options = {
916
1099
  // default to hibernate
917
1100
  };
918
1101
  var Agent = _Agent;
1102
+ var wrappedClasses = /* @__PURE__ */ new Set();
919
1103
  async function routeAgentRequest(request, env, options) {
920
1104
  const corsHeaders = options?.cors === true ? {
921
1105
  "Access-Control-Allow-Credentials": "true",
@@ -1004,25 +1188,35 @@ function createAddressBasedEmailResolver(defaultAgentName) {
1004
1188
  function createCatchAllEmailResolver(agentName, agentId) {
1005
1189
  return async () => ({ agentName, agentId });
1006
1190
  }
1191
+ var agentMapCache = /* @__PURE__ */ new WeakMap();
1007
1192
  async function routeAgentEmail(email, env, options) {
1008
1193
  const routingInfo = await options.resolver(email, env);
1009
1194
  if (!routingInfo) {
1010
1195
  console.warn("No routing information found for email, dropping message");
1011
1196
  return;
1012
1197
  }
1013
- const namespaceBinding = env[routingInfo.agentName];
1014
- if (!namespaceBinding) {
1015
- throw new Error(
1016
- `Agent namespace '${routingInfo.agentName}' not found in environment`
1017
- );
1198
+ if (!agentMapCache.has(env)) {
1199
+ const map = {};
1200
+ for (const [key, value] of Object.entries(env)) {
1201
+ if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1202
+ map[key] = value;
1203
+ map[camelCaseToKebabCase(key)] = value;
1204
+ }
1205
+ }
1206
+ agentMapCache.set(env, map);
1018
1207
  }
1019
- if (typeof namespaceBinding !== "object" || !("idFromName" in namespaceBinding) || typeof namespaceBinding.idFromName !== "function") {
1208
+ const agentMap = agentMapCache.get(env);
1209
+ const namespace = agentMap[routingInfo.agentName];
1210
+ if (!namespace) {
1211
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1020
1212
  throw new Error(
1021
- `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1213
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1022
1214
  );
1023
1215
  }
1024
- const namespace = namespaceBinding;
1025
- const agent = await getAgentByName(namespace, routingInfo.agentId);
1216
+ const agent = await getAgentByName(
1217
+ namespace,
1218
+ routingInfo.agentId
1219
+ );
1026
1220
  const serialisableEmail = {
1027
1221
  getRaw: async () => {
1028
1222
  const reader = email.raw.getReader();
@@ -1084,7 +1278,7 @@ var StreamingResponse = class {
1084
1278
  id: this._id,
1085
1279
  result: chunk,
1086
1280
  success: true,
1087
- type: "rpc"
1281
+ type: "rpc" /* RPC */
1088
1282
  };
1089
1283
  this._connection.send(JSON.stringify(response));
1090
1284
  }
@@ -1102,7 +1296,7 @@ var StreamingResponse = class {
1102
1296
  id: this._id,
1103
1297
  result: finalChunk,
1104
1298
  success: true,
1105
- type: "rpc"
1299
+ type: "rpc" /* RPC */
1106
1300
  };
1107
1301
  this._connection.send(JSON.stringify(response));
1108
1302
  }
@@ -1134,6 +1328,7 @@ function isLocalMode() {
1134
1328
 
1135
1329
  export {
1136
1330
  genericObservability,
1331
+ callable,
1137
1332
  unstable_callable,
1138
1333
  getCurrentAgent,
1139
1334
  Agent,
@@ -1145,4 +1340,4 @@ export {
1145
1340
  getAgentByName,
1146
1341
  StreamingResponse
1147
1342
  };
1148
- //# sourceMappingURL=chunk-EDUDXISR.js.map
1343
+ //# sourceMappingURL=chunk-254F4GDT.js.map