agents 0.0.0-ecf8926 → 0.0.0-ed3f94d

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 (64) hide show
  1. package/README.md +126 -4
  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 +2 -1
  5. package/dist/ai-chat-agent.js +391 -76
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.js +1 -0
  8. package/dist/ai-react.d.ts +8 -1
  9. package/dist/ai-react.js +157 -111
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +1 -0
  12. package/dist/ai-types.js +2 -1
  13. package/dist/ccip-CMBYN64O.js +15 -0
  14. package/dist/ccip-CMBYN64O.js.map +1 -0
  15. package/dist/{chunk-EGCWEPQL.js → chunk-254F4GDT.js} +151 -98
  16. package/dist/chunk-254F4GDT.js.map +1 -0
  17. package/dist/{chunk-DS7BJNPH.js → chunk-3OT2NNEW.js} +411 -68
  18. package/dist/chunk-3OT2NNEW.js.map +1 -0
  19. package/dist/chunk-5Y6BEZDY.js +276 -0
  20. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  21. package/dist/{chunk-AVYJQSLW.js → chunk-BER7KXUJ.js} +2 -1
  22. package/dist/chunk-BER7KXUJ.js.map +1 -0
  23. package/dist/chunk-JJBFIGUC.js +5202 -0
  24. package/dist/chunk-JJBFIGUC.js.map +1 -0
  25. package/dist/chunk-PR4QN5HX.js +43 -0
  26. package/dist/chunk-PR4QN5HX.js.map +1 -0
  27. package/dist/chunk-TYAY6AU6.js +159 -0
  28. package/dist/chunk-TYAY6AU6.js.map +1 -0
  29. package/dist/{chunk-PVQZBKN7.js → chunk-Z44WASMA.js} +11 -3
  30. package/dist/chunk-Z44WASMA.js.map +1 -0
  31. package/dist/{client-BAqDHqAV.d.ts → client-DVoPb3-C.d.ts} +549 -30
  32. package/dist/client.js +2 -1
  33. package/dist/codemode/ai.d.ts +25 -0
  34. package/dist/codemode/ai.js +5112 -0
  35. package/dist/codemode/ai.js.map +1 -0
  36. package/dist/index.d.ts +44 -35
  37. package/dist/index.js +7 -4
  38. package/dist/mcp/client.d.ts +2 -1
  39. package/dist/mcp/client.js +2 -1
  40. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  41. package/dist/mcp/do-oauth-client-provider.js +2 -1
  42. package/dist/mcp/index.d.ts +50 -83
  43. package/dist/mcp/index.js +903 -760
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +39 -0
  46. package/dist/mcp/x402.js +3195 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BH1fJeiU.d.ts +58 -0
  49. package/dist/observability/index.d.ts +12 -24
  50. package/dist/observability/index.js +5 -4
  51. package/dist/react.d.ts +10 -6
  52. package/dist/react.js +101 -3
  53. package/dist/react.js.map +1 -1
  54. package/dist/schedule.d.ts +76 -2
  55. package/dist/schedule.js +17 -2
  56. package/dist/schedule.js.map +1 -1
  57. package/dist/secp256k1-M22GZP2U.js +2193 -0
  58. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  59. package/package.json +22 -7
  60. package/src/index.ts +226 -116
  61. package/dist/chunk-AVYJQSLW.js.map +0 -1
  62. package/dist/chunk-DS7BJNPH.js.map +0 -1
  63. package/dist/chunk-EGCWEPQL.js.map +0 -1
  64. package/dist/chunk-PVQZBKN7.js.map +0 -1
package/dist/ai-types.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  MessageType
3
- } from "./chunk-AVYJQSLW.js";
3
+ } from "./chunk-BER7KXUJ.js";
4
+ import "./chunk-PR4QN5HX.js";
4
5
  export {
5
6
  MessageType
6
7
  };
@@ -0,0 +1,15 @@
1
+ import {
2
+ ccipRequest,
3
+ offchainLookup,
4
+ offchainLookupAbiItem,
5
+ offchainLookupSignature
6
+ } from "./chunk-JJBFIGUC.js";
7
+ import "./chunk-TYAY6AU6.js";
8
+ import "./chunk-PR4QN5HX.js";
9
+ export {
10
+ ccipRequest,
11
+ offchainLookup,
12
+ offchainLookupAbiItem,
13
+ offchainLookupSignature
14
+ };
15
+ //# sourceMappingURL=ccip-CMBYN64O.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,9 +1,10 @@
1
1
  import {
2
+ DisposableStore,
2
3
  MCPClientManager
3
- } from "./chunk-DS7BJNPH.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
10
  } from "./chunk-QEVM4BVL.js";
@@ -25,7 +26,7 @@ function isStateUpdateMessage(msg) {
25
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
@@ -140,7 +158,20 @@ var _Agent = class _Agent extends Server {
140
158
  }
141
159
  await this._scheduleNextAlarm();
142
160
  };
143
- this._autoWrapCustomMethods();
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
+ );
144
175
  this.sql`
145
176
  CREATE TABLE IF NOT EXISTS cf_agents_state (
146
177
  id TEXT PRIMARY KEY NOT NULL,
@@ -189,17 +220,16 @@ var _Agent = class _Agent extends Server {
189
220
  { agent: this, connection: void 0, request, email: void 0 },
190
221
  async () => {
191
222
  if (this.mcp.isCallbackRequest(request)) {
192
- await this.mcp.handleCallbackRequest(request);
193
- this.broadcast(
194
- JSON.stringify({
195
- mcp: this.getMcpServers(),
196
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
197
- })
198
- );
199
- return new Response("<script>window.close();</script>", {
200
- headers: { "content-type": "text/html" },
201
- status: 200
202
- });
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);
203
233
  }
204
234
  return this._tryCatch(() => _onRequest(request));
205
235
  }
@@ -281,41 +311,39 @@ var _Agent = class _Agent extends Server {
281
311
  this.onConnect = (connection, ctx2) => {
282
312
  return agentContext.run(
283
313
  { agent: this, connection, request: ctx2.request, email: void 0 },
284
- async () => {
285
- setTimeout(() => {
286
- if (this.state) {
287
- connection.send(
288
- JSON.stringify({
289
- state: this.state,
290
- type: "cf_agent_state" /* CF_AGENT_STATE */
291
- })
292
- );
293
- }
314
+ () => {
315
+ if (this.state) {
294
316
  connection.send(
295
317
  JSON.stringify({
296
- mcp: this.getMcpServers(),
297
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
318
+ state: this.state,
319
+ type: "cf_agent_state" /* CF_AGENT_STATE */
298
320
  })
299
321
  );
300
- this.observability?.emit(
301
- {
302
- displayMessage: "Connection established",
303
- id: nanoid(),
304
- payload: {
305
- connectionId: connection.id
306
- },
307
- timestamp: Date.now(),
308
- 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
309
335
  },
310
- this.ctx
311
- );
312
- return this._tryCatch(() => _onConnect(connection, ctx2));
313
- }, 20);
336
+ timestamp: Date.now(),
337
+ type: "connect"
338
+ },
339
+ this.ctx
340
+ );
341
+ return this._tryCatch(() => _onConnect(connection, ctx2));
314
342
  }
315
343
  );
316
344
  };
317
345
  const _onStart = this.onStart.bind(this);
318
- this.onStart = async () => {
346
+ this.onStart = async (props) => {
319
347
  return agentContext.run(
320
348
  {
321
349
  agent: this,
@@ -328,13 +356,15 @@ var _Agent = class _Agent extends Server {
328
356
  const servers = this.sql`
329
357
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
330
358
  `;
331
- this.broadcast(
332
- JSON.stringify({
333
- mcp: this.getMcpServers(),
334
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
335
- })
336
- );
359
+ this.broadcastMcpServers();
337
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
+ });
338
368
  servers.forEach((server) => {
339
369
  this._connectToMcpServerInternal(
340
370
  server.name,
@@ -346,27 +376,17 @@ var _Agent = class _Agent extends Server {
346
376
  oauthClientId: server.client_id ?? void 0
347
377
  }
348
378
  ).then(() => {
349
- this.broadcast(
350
- JSON.stringify({
351
- mcp: this.getMcpServers(),
352
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
353
- })
354
- );
379
+ this.broadcastMcpServers();
355
380
  }).catch((error) => {
356
381
  console.error(
357
382
  `Error connecting to MCP server: ${server.name} (${server.server_url})`,
358
383
  error
359
384
  );
360
- this.broadcast(
361
- JSON.stringify({
362
- mcp: this.getMcpServers(),
363
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
364
- })
365
- );
385
+ this.broadcastMcpServers();
366
386
  });
367
387
  });
368
388
  }
369
- return _onStart();
389
+ return _onStart(props);
370
390
  });
371
391
  }
372
392
  );
@@ -560,28 +580,22 @@ var _Agent = class _Agent extends Server {
560
580
  while (proto && proto !== Object.prototype && depth < 10) {
561
581
  const methodNames = Object.getOwnPropertyNames(proto);
562
582
  for (const methodName of methodNames) {
563
- 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") {
564
585
  continue;
565
586
  }
566
- if (!baseMethods.has(methodName)) {
567
- const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
568
- if (descriptor && typeof descriptor.value === "function") {
569
- const wrappedFunction = withAgentContext(
570
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
571
- this[methodName]
572
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
573
- );
574
- if (this._isCallable(methodName)) {
575
- callableMetadata.set(
576
- wrappedFunction,
577
- callableMetadata.get(
578
- this[methodName]
579
- )
580
- );
581
- }
582
- this.constructor.prototype[methodName] = wrappedFunction;
583
- }
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
+ );
584
597
  }
598
+ this.constructor.prototype[methodName] = wrappedFunction;
585
599
  }
586
600
  proto = Object.getPrototypeOf(proto);
587
601
  depth++;
@@ -903,6 +917,8 @@ var _Agent = class _Agent extends Server {
903
917
  this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
904
918
  await this.ctx.storage.deleteAlarm();
905
919
  await this.ctx.storage.deleteAll();
920
+ this._disposables.dispose();
921
+ await this.mcp.dispose?.();
906
922
  this.ctx.abort("destroyed");
907
923
  this.observability?.emit(
908
924
  {
@@ -925,14 +941,26 @@ var _Agent = class _Agent extends Server {
925
941
  /**
926
942
  * Connect to a new MCP Server
927
943
  *
944
+ * @param serverName Name of the MCP server
928
945
  * @param url MCP Server SSE URL
929
- * @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.
930
947
  * @param agentsPrefix agents routing prefix if not using `agents`
931
- * @param options MCP client and transport (header) options
948
+ * @param options MCP client and transport options
932
949
  * @returns authUrl
933
950
  */
934
951
  async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
935
- 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`;
936
964
  const result = await this._connectToMcpServerInternal(
937
965
  serverName,
938
966
  url,
@@ -952,12 +980,7 @@ var _Agent = class _Agent extends Server {
952
980
  ${options ? JSON.stringify(options) : null}
953
981
  );
954
982
  `;
955
- this.broadcast(
956
- JSON.stringify({
957
- mcp: this.getMcpServers(),
958
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
959
- })
960
- );
983
+ this.broadcastMcpServers();
961
984
  return result;
962
985
  }
963
986
  async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
@@ -972,6 +995,7 @@ var _Agent = class _Agent extends Server {
972
995
  authProvider.clientId = reconnect.oauthClientId;
973
996
  }
974
997
  }
998
+ const transportType = options?.transport?.type ?? "auto";
975
999
  let headerTransportOpts = {};
976
1000
  if (options?.transport?.headers) {
977
1001
  headerTransportOpts = {
@@ -991,7 +1015,8 @@ var _Agent = class _Agent extends Server {
991
1015
  reconnect,
992
1016
  transport: {
993
1017
  ...headerTransportOpts,
994
- authProvider
1018
+ authProvider,
1019
+ type: transportType
995
1020
  }
996
1021
  });
997
1022
  return {
@@ -1002,15 +1027,11 @@ var _Agent = class _Agent extends Server {
1002
1027
  }
1003
1028
  async removeMcpServer(id) {
1004
1029
  this.mcp.closeConnection(id);
1030
+ this.mcp.unregisterCallbackUrl(id);
1005
1031
  this.sql`
1006
1032
  DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1007
1033
  `;
1008
- this.broadcast(
1009
- JSON.stringify({
1010
- mcp: this.getMcpServers(),
1011
- type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
1012
- })
1013
- );
1034
+ this.broadcastMcpServers();
1014
1035
  }
1015
1036
  getMcpServers() {
1016
1037
  const mcpState = {
@@ -1038,6 +1059,36 @@ var _Agent = class _Agent extends Server {
1038
1059
  }
1039
1060
  return mcpState;
1040
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
+ }
1041
1092
  };
1042
1093
  /**
1043
1094
  * Agent configuration options
@@ -1048,6 +1099,7 @@ _Agent.options = {
1048
1099
  // default to hibernate
1049
1100
  };
1050
1101
  var Agent = _Agent;
1102
+ var wrappedClasses = /* @__PURE__ */ new Set();
1051
1103
  async function routeAgentRequest(request, env, options) {
1052
1104
  const corsHeaders = options?.cors === true ? {
1053
1105
  "Access-Control-Allow-Credentials": "true",
@@ -1276,6 +1328,7 @@ function isLocalMode() {
1276
1328
 
1277
1329
  export {
1278
1330
  genericObservability,
1331
+ callable,
1279
1332
  unstable_callable,
1280
1333
  getCurrentAgent,
1281
1334
  Agent,
@@ -1287,4 +1340,4 @@ export {
1287
1340
  getAgentByName,
1288
1341
  StreamingResponse
1289
1342
  };
1290
- //# sourceMappingURL=chunk-EGCWEPQL.js.map
1343
+ //# sourceMappingURL=chunk-254F4GDT.js.map