agents 0.17.4 → 0.18.0

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 (46) hide show
  1. package/dist/{agent-tool-types-OhWqAbCp.d.ts → agent-tool-types-BNUGGBzQ.d.ts} +30 -11
  2. package/dist/agent-tool-types.d.ts +1 -1
  3. package/dist/{agent-tools-LdNKGZT9.d.ts → agent-tools-BFbzVLFc.d.ts} +2 -2
  4. package/dist/agent-tools.d.ts +1 -1
  5. package/dist/chat/index.d.ts +29 -9
  6. package/dist/chat/index.js +31 -41
  7. package/dist/chat/index.js.map +1 -1
  8. package/dist/chat/react.d.ts +25 -1
  9. package/dist/chat/react.js +249 -93
  10. package/dist/chat/react.js.map +1 -1
  11. package/dist/chat-sdk/index.d.ts +1 -1
  12. package/dist/{client-C7F0MaVz.js → client-CcjiFpTf.js} +176 -42
  13. package/dist/client-CcjiFpTf.js.map +1 -0
  14. package/dist/client.d.ts +1 -1
  15. package/dist/cloudflare-BldFV0Pa.js +117 -0
  16. package/dist/cloudflare-BldFV0Pa.js.map +1 -0
  17. package/dist/index.d.ts +5 -3
  18. package/dist/index.js +118 -43
  19. package/dist/index.js.map +1 -1
  20. package/dist/mcp/client.d.ts +1 -1
  21. package/dist/mcp/client.js +1 -1
  22. package/dist/mcp/index.d.ts +1 -1
  23. package/dist/mcp/index.js +1 -1
  24. package/dist/observability/ai/index.d.ts +155 -0
  25. package/dist/observability/ai/index.js +1845 -0
  26. package/dist/observability/ai/index.js.map +1 -0
  27. package/dist/react.d.ts +1 -1
  28. package/dist/{retries-CvHJwSuh.d.ts → retries-CAvxtG9d.d.ts} +16 -7
  29. package/dist/retries.d.ts +8 -6
  30. package/dist/retries.js +20 -2
  31. package/dist/retries.js.map +1 -1
  32. package/dist/serializable.d.ts +1 -1
  33. package/dist/sub-routing.d.ts +1 -1
  34. package/dist/vite.d.ts +4 -4
  35. package/dist/vite.js +4 -2
  36. package/dist/vite.js.map +1 -1
  37. package/dist/{wire-types-nflOzNuU.js → wire-types-CU9rLoeS.js} +33 -2
  38. package/dist/wire-types-CU9rLoeS.js.map +1 -0
  39. package/dist/workflows.d.ts +1 -1
  40. package/docs/agent-class.md +9 -1
  41. package/docs/configuration.md +20 -0
  42. package/docs/mcp-client.md +13 -4
  43. package/docs/observability.md +282 -0
  44. package/package.json +7 -2
  45. package/dist/client-C7F0MaVz.js.map +0 -1
  46. package/dist/wire-types-nflOzNuU.js.map +0 -1
package/dist/index.js CHANGED
@@ -5,10 +5,11 @@ import { camelCaseToKebabCase, isInternalJsStubProp } from "./utils.js";
5
5
  import { createHeaderBasedEmailResolver, signAgentHeaders } from "./email.js";
6
6
  import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
7
7
  import { SUB_PREFIX, getSubAgentByName, parseSubAgentPath, routeSubAgentRequest } from "./sub-routing.js";
8
- import { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isErrorRetryable, isPlatformTransientError, tryN, validateRetryOptions } from "./retries.js";
9
- import { a as MCPConnectionState, c as RPC_DO_PREFIX, i as normalizeServerId, l as DisposableStore, n as MCP_SERVER_ID_MAX_LENGTH, t as MCPClientManager } from "./client-C7F0MaVz.js";
8
+ import { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isDurableObjectStorageReset, isErrorRetryable, isPlatformTransientError, tryN, validateRetryOptions } from "./retries.js";
9
+ import { a as MCPConnectionState, c as RPC_DO_PREFIX, i as normalizeServerId, l as DisposableStore, n as MCP_SERVER_ID_MAX_LENGTH, t as MCPClientManager } from "./client-CcjiFpTf.js";
10
10
  import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider.js";
11
11
  import { genericObservability } from "./observability/index.js";
12
+ import { n as writeSpanAttributes, t as tracer } from "./cloudflare-BldFV0Pa.js";
12
13
  import { AsyncLocalStorage } from "node:async_hooks";
13
14
  import { parseCronExpression } from "cron-schedule";
14
15
  import { nanoid } from "nanoid";
@@ -481,6 +482,23 @@ var Agent = class Agent extends Server {
481
482
  timestamp: Date.now()
482
483
  });
483
484
  }
485
+ _withAgentSpan(operation, storagePhase, attributes, run) {
486
+ let agentId;
487
+ try {
488
+ agentId = this.name;
489
+ } catch {
490
+ agentId = void 0;
491
+ }
492
+ return tracer.withSpan(operation, {
493
+ "cloudflare.agents.agent.id": agentId,
494
+ "cloudflare.agents.agent.name": this._ParentClass.name,
495
+ "cloudflare.agents.operation.name": operation,
496
+ "cloudflare.agents.storage.grouped": true,
497
+ "cloudflare.agents.storage.system": "durable_object",
498
+ "cloudflare.agents.storage.phase": storagePhase,
499
+ ...attributes
500
+ }, (span) => run((finishAttributes) => writeSpanAttributes(span, finishAttributes)));
501
+ }
484
502
  /**
485
503
  * Execute SQL queries against the Agent's database
486
504
  * @template T Type of the returned rows
@@ -722,6 +740,11 @@ var Agent = class Agent extends Server {
722
740
  VALUES (${SCHEMA_VERSION_ROW_ID}, ${String(CURRENT_SCHEMA_VERSION)})
723
741
  `;
724
742
  }
743
+ this._schemaInitialization = {
744
+ previousVersion: schemaVersion,
745
+ currentVersion: CURRENT_SCHEMA_VERSION,
746
+ migrated: schemaVersion < CURRENT_SCHEMA_VERSION
747
+ };
725
748
  }
726
749
  constructor(ctx, env) {
727
750
  super(ctx, env);
@@ -753,14 +776,25 @@ var Agent = class Agent extends Server {
753
776
  this._flushingQueue = false;
754
777
  this.maxConcurrentAgentTools = Infinity;
755
778
  this._subAgentRegistryReady = false;
756
- if (!wrappedClasses.has(this.constructor)) {
757
- this._autoWrapCustomMethods();
758
- wrappedClasses.add(this.constructor);
759
- }
760
- this._ensureSchema();
761
- this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", {
762
- storage: this.ctx.storage,
763
- createAuthProvider: (callbackUrl) => this.createMcpOAuthProvider(callbackUrl)
779
+ this.mcp = this._withAgentSpan("agent_initialization", "initialization", {}, (update) => {
780
+ if (!wrappedClasses.has(this.constructor)) {
781
+ this._autoWrapCustomMethods();
782
+ wrappedClasses.add(this.constructor);
783
+ }
784
+ this._withAgentSpan("initialize_agent_storage", "initialization", {}, (updateStorage) => {
785
+ this._ensureSchema();
786
+ const schemaAttributes = {
787
+ "cloudflare.agents.schema.version.previous": this._schemaInitialization?.previousVersion,
788
+ "cloudflare.agents.schema.version.current": this._schemaInitialization?.currentVersion,
789
+ "cloudflare.agents.schema.migrated": this._schemaInitialization?.migrated
790
+ };
791
+ updateStorage(schemaAttributes);
792
+ update(schemaAttributes);
793
+ });
794
+ return new MCPClientManager(this._ParentClass.name, "0.0.1", {
795
+ storage: this.ctx.storage,
796
+ createAuthProvider: (callbackUrl) => this.createMcpOAuthProvider(callbackUrl)
797
+ });
764
798
  });
765
799
  this._disposables.add(this.mcp.onServerStateChanged(async () => {
766
800
  this.broadcastMcpServers();
@@ -960,36 +994,46 @@ var Agent = class Agent extends Server {
960
994
  });
961
995
  };
962
996
  const _onStart = this.onStart.bind(this);
963
- this.onStart = async (props) => {
997
+ const startAgent = async (props, update) => {
964
998
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
965
999
  agent: this,
966
1000
  connection: void 0,
967
1001
  request: void 0,
968
1002
  email: void 0
969
1003
  }, async () => {
970
- if (await this.ctx.storage.get("cf_agents_is_facet")) this._isFacet = true;
971
- const storedFacetName = await this.ctx.storage.get("cf_agents_facet_name");
972
- if (typeof storedFacetName === "string") this._facetName = storedFacetName;
973
- const storedParentPath = await this.ctx.storage.get("cf_agents_parent_path");
974
- if (isValidParentPath(storedParentPath)) this._parentPath = storedParentPath;
975
- try {
976
- await this._cf_hydrateSubAgentConnectionsFromRoot();
977
- } catch (error) {
978
- console.warn("[Agent] Unable to hydrate sub-agent WebSocket connections:", error);
979
- }
1004
+ await this._withAgentSpan("restore_agent_state", "startup", {}, async () => {
1005
+ if (await this.ctx.storage.get("cf_agents_is_facet")) this._isFacet = true;
1006
+ const storedFacetName = await this.ctx.storage.get("cf_agents_facet_name");
1007
+ if (typeof storedFacetName === "string") this._facetName = storedFacetName;
1008
+ const storedParentPath = await this.ctx.storage.get("cf_agents_parent_path");
1009
+ if (isValidParentPath(storedParentPath)) this._parentPath = storedParentPath;
1010
+ try {
1011
+ await this._cf_hydrateSubAgentConnectionsFromRoot();
1012
+ } catch (error) {
1013
+ console.warn("[Agent] Unable to hydrate sub-agent WebSocket connections:", error);
1014
+ }
1015
+ });
980
1016
  await this._tryCatch(async () => {
981
- await this.mcp.restoreConnectionsFromStorage(this.name);
982
- await this._restoreRpcMcpServers();
983
- this.broadcastMcpServers();
984
- this._checkOrphanedWorkflows();
985
- await this._checkRunFibers();
986
- const startupAgentToolRunIds = this._agentToolRunRecoveryRunIds();
1017
+ await this._withAgentSpan("restore_mcp_connections", "startup", {}, async () => {
1018
+ await this.mcp.restoreConnectionsFromStorage(this.name);
1019
+ await this._restoreRpcMcpServers();
1020
+ this.broadcastMcpServers();
1021
+ });
1022
+ const startupAgentToolRunIds = await this._withAgentSpan("recover_agent_work", "startup", {}, async () => {
1023
+ this._checkOrphanedWorkflows();
1024
+ await this._checkRunFibers();
1025
+ return this._agentToolRunRecoveryRunIds();
1026
+ });
1027
+ update({
1028
+ "cloudflare.agents.start.facet": this._isFacet,
1029
+ "cloudflare.agents.recovery.agent_tools.count": startupAgentToolRunIds.length
1030
+ });
987
1031
  const chatRecoveryBefore = this.chatRecovery;
988
1032
  this._insideOnStart = true;
989
1033
  this._warnedScheduleInOnStart.clear();
990
1034
  let result;
991
1035
  try {
992
- result = await _onStart(props);
1036
+ result = await this._withAgentSpan("run_user_on_start", "startup", {}, () => _onStart(props));
993
1037
  } finally {
994
1038
  this._insideOnStart = false;
995
1039
  }
@@ -1004,6 +1048,7 @@ var Agent = class Agent extends Server {
1004
1048
  });
1005
1049
  });
1006
1050
  };
1051
+ this.onStart = (props) => this._withAgentSpan("agent_start", "startup", {}, (update) => startAgent(props, update));
1007
1052
  }
1008
1053
  /**
1009
1054
  * Check for workflows referencing unknown bindings and warn with migration suggestion.
@@ -2837,10 +2882,15 @@ var Agent = class Agent extends Server {
2837
2882
  }
2838
2883
  async _runFiberInternal(id, name, fn, options) {
2839
2884
  const signal = options?.signal ?? new AbortController().signal;
2840
- this.sql`
2841
- INSERT INTO cf_agents_runs (id, name, snapshot, created_at)
2842
- VALUES (${id}, ${name}, NULL, ${Date.now()})
2843
- `;
2885
+ this._withAgentSpan("initialize_fiber", "fiber", {
2886
+ "cloudflare.agents.fiber.id": id,
2887
+ "cloudflare.agents.fiber.name": name
2888
+ }, () => {
2889
+ this.sql`
2890
+ INSERT INTO cf_agents_runs (id, name, snapshot, created_at)
2891
+ VALUES (${id}, ${name}, NULL, ${Date.now()})
2892
+ `;
2893
+ });
2844
2894
  const startedAt = Date.now();
2845
2895
  this._emit("fiber:run:started", {
2846
2896
  fiberId: id,
@@ -2850,14 +2900,19 @@ var Agent = class Agent extends Server {
2850
2900
  this._runFiberActiveFibers.add(id);
2851
2901
  const writeSnapshot = (data) => {
2852
2902
  const snapshot = JSON.stringify(data);
2853
- this.sql`
2854
- UPDATE cf_agents_runs SET snapshot = ${snapshot}
2855
- WHERE id = ${id}
2856
- `;
2857
- if (options?.managed) this.sql`
2858
- UPDATE cf_agents_fibers SET snapshot = ${snapshot}
2859
- WHERE fiber_id = ${id}
2860
- `;
2903
+ this._withAgentSpan("persist_fiber_snapshot", "fiber", {
2904
+ "cloudflare.agents.fiber.id": id,
2905
+ "cloudflare.agents.fiber.name": name
2906
+ }, () => {
2907
+ this.sql`
2908
+ UPDATE cf_agents_runs SET snapshot = ${snapshot}
2909
+ WHERE id = ${id}
2910
+ `;
2911
+ if (options?.managed) this.sql`
2912
+ UPDATE cf_agents_fibers SET snapshot = ${snapshot}
2913
+ WHERE fiber_id = ${id}
2914
+ `;
2915
+ });
2861
2916
  };
2862
2917
  let root;
2863
2918
  let registeredFacetRun = false;
@@ -2908,7 +2963,12 @@ var Agent = class Agent extends Server {
2908
2963
  }
2909
2964
  } finally {
2910
2965
  this._runFiberActiveFibers.delete(id);
2911
- this.sql`DELETE FROM cf_agents_runs WHERE id = ${id}`;
2966
+ this._withAgentSpan("finalize_fiber", "fiber", {
2967
+ "cloudflare.agents.fiber.id": id,
2968
+ "cloudflare.agents.fiber.name": name
2969
+ }, () => {
2970
+ this.sql`DELETE FROM cf_agents_runs WHERE id = ${id}`;
2971
+ });
2912
2972
  dispose();
2913
2973
  if (root && registeredFacetRun) try {
2914
2974
  await root._cf_unregisterFacetRun(this.selfPath, id);
@@ -3328,6 +3388,9 @@ var Agent = class Agent extends Server {
3328
3388
  `[0]?.count ?? 0) > 0;
3329
3389
  }
3330
3390
  async _scheduleNextAlarm() {
3391
+ await this._withAgentSpan("schedule_agent_alarm", "alarm", {}, () => this._scheduleNextAlarmBody());
3392
+ }
3393
+ async _scheduleNextAlarmBody() {
3331
3394
  if (await this._hasPendingDestroy()) {
3332
3395
  await this.ctx.storage.setAlarm(Date.now());
3333
3396
  return;
@@ -6717,7 +6780,8 @@ var Agent = class Agent extends Server {
6717
6780
  if (existingServer && this.mcp.mcpConnections[existingServer.id]) {
6718
6781
  const conn = this.mcp.mcpConnections[existingServer.id];
6719
6782
  if (conn.connectionState === MCPConnectionState.AUTHENTICATING) {
6720
- const authUrl = conn.options.transport.authProvider?.authUrl || (this._isAbsoluteHttpUrl(existingServer.auth_url) ? existingServer.auth_url : void 0);
6783
+ const authProvider = conn.options.transport.authProvider;
6784
+ const authUrl = await this._redeemableAuthUrl(existingServer.id, authProvider?.authUrl, authProvider) ?? await this._redeemableAuthUrl(existingServer.id, existingServer.auth_url, authProvider);
6721
6785
  if (authUrl) return {
6722
6786
  id: existingServer.id,
6723
6787
  state: MCPConnectionState.AUTHENTICATING,
@@ -6852,6 +6916,17 @@ var Agent = class Agent extends Server {
6852
6916
  state: MCPConnectionState.READY
6853
6917
  };
6854
6918
  }
6919
+ async _redeemableAuthUrl(serverId, authUrl, authProvider) {
6920
+ if (!this._isAbsoluteHttpUrl(authUrl) || !authProvider) return;
6921
+ const state = new URL(authUrl).searchParams.get("state");
6922
+ if (!state) return authUrl;
6923
+ authProvider.serverId = serverId;
6924
+ try {
6925
+ return (await authProvider.checkState(state)).valid ? authUrl : void 0;
6926
+ } catch {
6927
+ return;
6928
+ }
6929
+ }
6855
6930
  _isAbsoluteHttpUrl(value) {
6856
6931
  if (!value) return false;
6857
6932
  try {
@@ -7147,6 +7222,6 @@ var StreamingResponse = class {
7147
7222
  }
7148
7223
  };
7149
7224
  //#endregion
7150
- export { AGENT_TOOL_MILESTONE_PART, AGENT_TOOL_PROGRESS_PART, Agent, DEFAULT_AGENT_STATIC_OPTIONS, DurableObjectOAuthClientProvider, MCP_SERVER_ID_MAX_LENGTH, MessageType, SUB_PREFIX, SqlError, StreamingResponse, __DO_NOT_USE_WILL_BREAK__agentContext, callable, camelCaseToKebabCase, createHeaderBasedEmailResolver, getAgentByName, getCurrentAgent, getSubAgentByName, isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isPlatformTransientError, normalizeServerId, parseSubAgentPath, routeAgentEmail, routeAgentRequest, routeSubAgentRequest, unstable_callable };
7225
+ export { AGENT_TOOL_MILESTONE_PART, AGENT_TOOL_PROGRESS_PART, Agent, DEFAULT_AGENT_STATIC_OPTIONS, DurableObjectOAuthClientProvider, MCP_SERVER_ID_MAX_LENGTH, MessageType, SUB_PREFIX, SqlError, StreamingResponse, __DO_NOT_USE_WILL_BREAK__agentContext, callable, camelCaseToKebabCase, createHeaderBasedEmailResolver, getAgentByName, getCurrentAgent, getSubAgentByName, isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isDurableObjectStorageReset, isPlatformTransientError, normalizeServerId, parseSubAgentPath, routeAgentEmail, routeAgentRequest, routeSubAgentRequest, unstable_callable };
7151
7226
 
7152
7227
  //# sourceMappingURL=index.js.map