@copilotkit/shared 1.70.1 → 1.70.3

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 (70) hide show
  1. package/dist/attachments/types.d.cts +10 -0
  2. package/dist/attachments/types.d.cts.map +1 -1
  3. package/dist/attachments/types.d.mts +10 -0
  4. package/dist/attachments/types.d.mts.map +1 -1
  5. package/dist/index.cjs +8 -5
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +5 -3
  8. package/dist/index.d.cts.map +1 -1
  9. package/dist/index.d.mts +5 -4
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +5 -4
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/index.umd.js +226 -197
  14. package/dist/index.umd.js.map +1 -1
  15. package/dist/package.cjs +1 -1
  16. package/dist/package.mjs +1 -1
  17. package/dist/telemetry/index.cjs +15 -0
  18. package/dist/telemetry/index.d.cts +5 -0
  19. package/dist/telemetry/index.d.mts +4 -2
  20. package/dist/telemetry/index.mjs +6 -0
  21. package/dist/telemetry/telemetry-client.cjs +4 -13
  22. package/dist/telemetry/telemetry-client.cjs.map +1 -1
  23. package/dist/telemetry/telemetry-client.d.cts +2 -8
  24. package/dist/telemetry/telemetry-client.d.cts.map +1 -1
  25. package/dist/telemetry/telemetry-client.d.mts +2 -8
  26. package/dist/telemetry/telemetry-client.d.mts.map +1 -1
  27. package/dist/telemetry/telemetry-client.mjs +4 -12
  28. package/dist/telemetry/telemetry-client.mjs.map +1 -1
  29. package/dist/telemetry/telemetry-disabled.cjs +20 -0
  30. package/dist/telemetry/telemetry-disabled.cjs.map +1 -0
  31. package/dist/telemetry/telemetry-disabled.d.cts +16 -0
  32. package/dist/telemetry/telemetry-disabled.d.cts.map +1 -0
  33. package/dist/telemetry/telemetry-disabled.d.mts +16 -0
  34. package/dist/telemetry/telemetry-disabled.d.mts.map +1 -0
  35. package/dist/telemetry/telemetry-disabled.mjs +19 -0
  36. package/dist/telemetry/telemetry-disabled.mjs.map +1 -0
  37. package/dist/utils/index.cjs +1 -0
  38. package/dist/utils/index.cjs.map +1 -1
  39. package/dist/utils/index.d.cts +2 -1
  40. package/dist/utils/index.d.cts.map +1 -1
  41. package/dist/utils/index.d.mts +2 -1
  42. package/dist/utils/index.d.mts.map +1 -1
  43. package/dist/utils/index.mjs +1 -0
  44. package/dist/utils/index.mjs.map +1 -1
  45. package/dist/utils/inspector-learning.cjs +185 -0
  46. package/dist/utils/inspector-learning.cjs.map +1 -0
  47. package/dist/utils/inspector-learning.d.cts +91 -0
  48. package/dist/utils/inspector-learning.d.cts.map +1 -0
  49. package/dist/utils/inspector-learning.d.mts +91 -0
  50. package/dist/utils/inspector-learning.d.mts.map +1 -0
  51. package/dist/utils/inspector-learning.mjs +182 -0
  52. package/dist/utils/inspector-learning.mjs.map +1 -0
  53. package/dist/utils/types.cjs.map +1 -1
  54. package/dist/utils/types.d.cts +13 -2
  55. package/dist/utils/types.d.cts.map +1 -1
  56. package/dist/utils/types.d.mts +13 -2
  57. package/dist/utils/types.d.mts.map +1 -1
  58. package/dist/utils/types.mjs.map +1 -1
  59. package/package.json +12 -1
  60. package/src/__tests__/license-context.test.ts +22 -1
  61. package/src/__tests__/root-entry-browser-safety.test.ts +85 -0
  62. package/src/attachments/types.ts +10 -0
  63. package/src/index.ts +27 -2
  64. package/src/telemetry/telemetry-client.ts +2 -17
  65. package/src/telemetry/telemetry-disabled.ts +22 -0
  66. package/src/utils/index.ts +1 -0
  67. package/src/utils/inspector-learning.test.ts +213 -0
  68. package/src/utils/inspector-learning.ts +423 -0
  69. package/src/utils/types.ts +16 -1
  70. package/tsdown.config.ts +4 -1
package/dist/package.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  //#region package.json
3
- var version = "1.70.1";
3
+ var version = "1.70.3";
4
4
 
5
5
  //#endregion
6
6
  Object.defineProperty(exports, 'version', {
package/dist/package.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.70.1";
2
+ var version = "1.70.3";
3
3
 
4
4
  //#endregion
5
5
  export { version };
@@ -0,0 +1,15 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_telemetry_disabled = require('./telemetry-disabled.cjs');
3
+ const require_sampling = require('./sampling.cjs');
4
+ const require_lambda_client = require('./lambda-client.cjs');
5
+ const require_telemetry_client = require('./telemetry-client.cjs');
6
+
7
+ exports.TELEMETRY_EMITTER_V1 = require_sampling.TELEMETRY_EMITTER_V1;
8
+ exports.TELEMETRY_EMITTER_V2 = require_sampling.TELEMETRY_EMITTER_V2;
9
+ exports.TelemetryClient = require_telemetry_client.TelemetryClient;
10
+ exports.computeSamplingMeta = require_sampling.computeSamplingMeta;
11
+ exports.firstNonBlankTelemetryId = require_lambda_client.firstNonBlankTelemetryId;
12
+ exports.isTelemetryDisabled = require_telemetry_disabled.isTelemetryDisabled;
13
+ exports.lambdaClient = require_lambda_client.lambdaClient;
14
+ exports.parseAndWarnTelemetryId = require_lambda_client.parseAndWarnTelemetryId;
15
+ exports.parseTelemetryIdFromLicense = require_lambda_client.parseTelemetryIdFromLicense;
@@ -0,0 +1,5 @@
1
+ import { isTelemetryDisabled } from "./telemetry-disabled.cjs";
2
+ import { SamplingMeta, TELEMETRY_EMITTER_V1, TELEMETRY_EMITTER_V2, TelemetryEmitter, TelemetryTransport, computeSamplingMeta } from "./sampling.cjs";
3
+ import { LambdaSendOptions, firstNonBlankTelemetryId, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense } from "./lambda-client.cjs";
4
+ import { TelemetryCapture, TelemetryClient, TelemetryIdentity } from "./telemetry-client.cjs";
5
+ export { type LambdaSendOptions, SamplingMeta, TELEMETRY_EMITTER_V1, TELEMETRY_EMITTER_V2, TelemetryCapture, TelemetryClient, TelemetryEmitter, TelemetryIdentity, TelemetryTransport, computeSamplingMeta, firstNonBlankTelemetryId, isTelemetryDisabled, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense };
@@ -1,3 +1,5 @@
1
- import { TelemetryCapture, TelemetryClient, TelemetryIdentity, isTelemetryDisabled } from "./telemetry-client.mjs";
1
+ import { isTelemetryDisabled } from "./telemetry-disabled.mjs";
2
2
  import { SamplingMeta, TELEMETRY_EMITTER_V1, TELEMETRY_EMITTER_V2, TelemetryEmitter, TelemetryTransport, computeSamplingMeta } from "./sampling.mjs";
3
- import { LambdaSendOptions, firstNonBlankTelemetryId, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense } from "./lambda-client.mjs";
3
+ import { LambdaSendOptions, firstNonBlankTelemetryId, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense } from "./lambda-client.mjs";
4
+ import { TelemetryCapture, TelemetryClient, TelemetryIdentity } from "./telemetry-client.mjs";
5
+ export { type LambdaSendOptions, SamplingMeta, TELEMETRY_EMITTER_V1, TELEMETRY_EMITTER_V2, TelemetryCapture, TelemetryClient, TelemetryEmitter, TelemetryIdentity, TelemetryTransport, computeSamplingMeta, firstNonBlankTelemetryId, isTelemetryDisabled, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense };
@@ -0,0 +1,6 @@
1
+ import { isTelemetryDisabled } from "./telemetry-disabled.mjs";
2
+ import { TELEMETRY_EMITTER_V1, TELEMETRY_EMITTER_V2, computeSamplingMeta } from "./sampling.mjs";
3
+ import { firstNonBlankTelemetryId, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense } from "./lambda-client.mjs";
4
+ import { TelemetryClient } from "./telemetry-client.mjs";
5
+
6
+ export { TELEMETRY_EMITTER_V1, TELEMETRY_EMITTER_V2, TelemetryClient, computeSamplingMeta, firstNonBlankTelemetryId, isTelemetryDisabled, lambdaClient, parseAndWarnTelemetryId, parseTelemetryIdFromLicense };
@@ -1,20 +1,12 @@
1
1
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
- const require_utils = require('./utils.cjs');
3
- const require_lambda_client = require('./lambda-client.cjs');
2
+ const require_telemetry_disabled = require('./telemetry-disabled.cjs');
4
3
  const require_sampling = require('./sampling.cjs');
4
+ const require_lambda_client = require('./lambda-client.cjs');
5
+ const require_utils = require('./utils.cjs');
5
6
  let uuid = require("uuid");
6
7
  let _segment_analytics_node = require("@segment/analytics-node");
7
8
 
8
9
  //#region src/telemetry/telemetry-client.ts
9
- /**
10
- * Checks if telemetry is disabled via environment variables.
11
- * Users can opt out by setting:
12
- * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
13
- * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
14
- */
15
- function isTelemetryDisabled() {
16
- return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
17
- }
18
10
  var TelemetryClient = class {
19
11
  constructor({ packageName, packageVersion, telemetryDisabled, telemetryBaseUrl, sampleRate }) {
20
12
  this.globalProperties = {};
@@ -27,7 +19,7 @@ var TelemetryClient = class {
27
19
  this.anonymousId = `anon_${(0, uuid.v4)()}`;
28
20
  this.packageName = packageName;
29
21
  this.packageVersion = packageVersion;
30
- this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();
22
+ this.telemetryDisabled = telemetryDisabled || require_telemetry_disabled.isTelemetryDisabled();
31
23
  if (this.telemetryDisabled) return;
32
24
  this.setSampleRate(sampleRate);
33
25
  this.segment = new _segment_analytics_node.Analytics({ writeKey: process.env.COPILOTKIT_SEGMENT_WRITE_KEY || "n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja" });
@@ -163,5 +155,4 @@ var TelemetryClient = class {
163
155
 
164
156
  //#endregion
165
157
  exports.TelemetryClient = TelemetryClient;
166
- exports.isTelemetryDisabled = isTelemetryDisabled;
167
158
  //# sourceMappingURL=telemetry-client.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-client.cjs","names":["Analytics","computeSamplingMeta","TELEMETRY_EMITTER_V1","flattenObject","lambdaClient","firstNonBlankTelemetryId","parseAndWarnTelemetryId"],"sources":["../../src/telemetry/telemetry-client.ts"],"sourcesContent":["import { Analytics } from \"@segment/analytics-node\";\nimport type { AnalyticsEvents } from \"./events\";\nimport { flattenObject } from \"./utils\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseAndWarnTelemetryId,\n} from \"./lambda-client\";\nimport { computeSamplingMeta, TELEMETRY_EMITTER_V1 } from \"./sampling\";\n\n/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK ===\n \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n\n/** Transport identity and sampling authority resolved for one runtime. */\nexport interface TelemetryIdentity {\n telemetryId?: string;\n licenseToken?: string;\n}\n\n/** Capture-only telemetry client bound to one runtime identity. */\nexport interface TelemetryCapture {\n capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void>;\n}\n\ninterface ResolvedTelemetryIdentity {\n telemetryId: string | null;\n licenseToken: string | null;\n licenseTelemetryId: string | null;\n}\n\nexport class TelemetryClient {\n segment: Analytics | undefined;\n globalProperties: Record<string, any> = {};\n cloudConfiguration: { publicApiKey: string; baseUrl: string } | null = null;\n // EIP / Intelligence license token (Ed25519-signed JWT). The lambda\n // client decodes its payload to extract telemetry_id. Customer API\n // keys are NOT used here — they flow only into Segment.\n private licenseToken: string | null = null;\n // Standalone analytics identity. This stays separate from the effective\n // identity so legacy callers continue sending only their license token to\n // the Lambda transport.\n private telemetryId: string | null = null;\n // License-derived identity used only as sampling authority. A standalone\n // telemetry id remains a transport claim and does not bypass sampleRate.\n private licenseTelemetryId: string | null = null;\n packageName: string;\n packageVersion: string;\n private telemetryDisabled: boolean = false;\n // Client-side sampling rate for anonymous events. Identified events\n // (those whose license token yielded a telemetry_id) bypass the gate\n // entirely. Applied uniformly to both the lambda sink and Segment —\n // one dice roll per capture, both sinks see the same decision.\n private sampleRate: number = 0.05;\n private anonymousId = `anon_${uuidv4()}`;\n\n constructor({\n packageName,\n packageVersion,\n telemetryDisabled,\n telemetryBaseUrl,\n sampleRate,\n }: {\n packageName: string;\n packageVersion: string;\n telemetryDisabled?: boolean;\n telemetryBaseUrl?: string;\n sampleRate?: number;\n }) {\n this.packageName = packageName;\n this.packageVersion = packageVersion;\n this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();\n\n if (this.telemetryDisabled) {\n return;\n }\n\n this.setSampleRate(sampleRate);\n\n // eslint-disable-next-line\n const writeKey =\n process.env.COPILOTKIT_SEGMENT_WRITE_KEY ||\n \"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja\";\n\n this.segment = new Analytics({\n writeKey,\n });\n\n this.setGlobalProperties({\n \"copilotkit.package.name\": packageName,\n \"copilotkit.package.version\": packageVersion,\n });\n }\n\n private shouldSendEvent() {\n const randomNumber = Math.random();\n return randomNumber < this.sampleRate;\n }\n\n async capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void> {\n return this.captureWithIdentity(event, properties, {\n telemetryId: this.telemetryId,\n licenseToken: this.licenseToken,\n licenseTelemetryId: this.licenseTelemetryId,\n });\n }\n\n private async captureWithIdentity<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n identity: ResolvedTelemetryIdentity,\n ): Promise<void> {\n if (this.telemetryDisabled) {\n return;\n }\n\n // Callers without license-derived sampling authority are gated by\n // sampleRate. Legacy license tokens with telemetry_id always send —\n // the volume is bounded by paying-customer count and full fidelity\n // per identified customer is worth the marginal cost.\n if (!identity.licenseTelemetryId && !this.shouldSendEvent()) {\n return;\n }\n\n // Sampling metadata is computed in ./sampling so this client and the\n // v2 runtime client can't drift apart again — see the note there.\n const samplingMeta = computeSamplingMeta({\n telemetryId: identity.licenseTelemetryId,\n sampleRate: this.sampleRate,\n });\n\n // Everything below travels identically on both copies of this event.\n // The event id is what makes the dual-write dedupable downstream:\n // one capture() produces one id, stamped on the lambda copy and the\n // Segment copy alike, so consumers no longer have to infer the\n // duplication from $lib or from which fields happen to be present\n // (OSS-1019).\n const eventMeta = {\n ...samplingMeta,\n telemetry_emitter: TELEMETRY_EMITTER_V1,\n telemetry_event_id: uuidv4(),\n };\n\n const flattenedProperties = flattenObject(properties);\n const propertiesWithGlobal: Record<string, any> = {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"segment\",\n ...flattenedProperties,\n };\n const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal)\n .sort()\n .reduce(\n (obj, key) => {\n obj[key] = propertiesWithGlobal[key];\n return obj;\n },\n {} as Record<string, any>,\n );\n\n await lambdaClient.send({\n event,\n properties: flattenedProperties,\n globalProperties: {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"lambda\",\n },\n packageName: this.packageName,\n packageVersion: this.packageVersion,\n telemetryId: identity.telemetryId ?? undefined,\n licenseToken: identity.licenseToken ?? undefined,\n });\n\n if (this.segment) {\n this.segment.track({\n anonymousId: this.anonymousId,\n event,\n properties: { ...orderedPropertiesWithGlobal },\n });\n }\n }\n\n setGlobalProperties(properties: Record<string, any>) {\n const flattenedProperties = flattenObject(properties);\n this.globalProperties = {\n ...this.globalProperties,\n ...flattenedProperties,\n };\n }\n\n setCloudConfiguration(properties: { publicApiKey: string; baseUrl: string }) {\n this.cloudConfiguration = properties;\n\n this.setGlobalProperties({\n cloud: {\n publicApiKey: properties.publicApiKey,\n baseUrl: properties.baseUrl,\n },\n });\n }\n\n /**\n * Atomically configure standalone, legacy, or anonymous telemetry identity.\n *\n * A standalone id takes transport precedence over a supplied legacy license\n * token, but only a license-derived id grants sampling authority. Neither\n * value is added to event properties.\n *\n * @param identity - One standalone id, one legacy license token, or neither.\n */\n setTelemetryIdentity(identity: {\n telemetryId?: string;\n licenseToken?: string;\n }): void {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n this.telemetryId = resolvedIdentity.telemetryId;\n this.licenseToken = resolvedIdentity.licenseToken;\n this.licenseTelemetryId = resolvedIdentity.licenseTelemetryId;\n }\n\n /**\n * Configure legacy license-derived telemetry identity.\n *\n * @param licenseToken - License token whose telemetry claim identifies sends.\n */\n setLicenseToken(licenseToken: string) {\n this.setTelemetryIdentity({ licenseToken });\n }\n\n /**\n * Create an immutable capture scope for one runtime.\n *\n * The scope shares this client's sinks, process-wide opt-out, global\n * properties, and sampling settings, but snapshots transport identity and\n * license-derived sampling authority. Constructing another runtime cannot\n * rewrite an existing scope.\n *\n * @param identity - The runtime's construction-time telemetry identity.\n * @returns A capture-only client bound to that identity.\n */\n createScope(identity: TelemetryIdentity): TelemetryCapture {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n\n return {\n capture: <K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ) => this.captureWithIdentity(event, properties, resolvedIdentity),\n };\n }\n\n private resolveTelemetryIdentity(\n identity: TelemetryIdentity,\n ): ResolvedTelemetryIdentity {\n const telemetryId = firstNonBlankTelemetryId(identity.telemetryId);\n if (telemetryId !== undefined) {\n return {\n telemetryId,\n licenseToken: null,\n licenseTelemetryId: null,\n };\n }\n\n return {\n telemetryId: null,\n licenseToken: identity.licenseToken ?? null,\n licenseTelemetryId: identity.licenseToken\n ? parseAndWarnTelemetryId(identity.licenseToken)\n : null,\n };\n }\n\n private setSampleRate(sampleRate: number | undefined) {\n let _sampleRate: number;\n\n _sampleRate = sampleRate ?? 0.05;\n\n // eslint-disable-next-line\n if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) {\n // eslint-disable-next-line\n _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);\n }\n\n // Number.isNaN guards against parseFloat(\"nonsense\") slipping past the\n // range check (all NaN comparisons are false), which would silently\n // drop every anonymous event with no signal — especially important\n // since the default is now 0.05, making env-var overrides more common.\n if (Number.isNaN(_sampleRate) || _sampleRate < 0 || _sampleRate > 1) {\n throw new Error(\"Sample rate must be between 0 and 1\");\n }\n\n this.sampleRate = _sampleRate;\n // Per-event sampling metadata (sampleRate/sampleRateAdjustmentFactor/\n // sampleWeight) is computed per capture() in ./sampling. Only license-\n // authorized events get effectiveSampleRate=1; standalone transport\n // identity stays in the sampled population.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,SAAgB,sBAA+B;AAC7C,QACG,QAAQ,IACN,kCAAkC,UACpC,QAAQ,IACN,kCAAkC,OACpC,QAAQ,IAA2C,iBAClD,UACD,QAAQ,IAA2C,iBAAiB;;AAwBzE,IAAa,kBAAb,MAA6B;CAyB3B,YAAY,EACV,aACA,gBACA,mBACA,kBACA,cAOC;0BAnCqC,EAAE;4BAC6B;sBAIjC;qBAID;4BAGO;2BAGP;oBAKR;qBACP,sBAAgB;AAepC,OAAK,cAAc;AACnB,OAAK,iBAAiB;AACtB,OAAK,oBAAoB,qBAAqB,qBAAqB;AAEnE,MAAI,KAAK,kBACP;AAGF,OAAK,cAAc,WAAW;AAO9B,OAAK,UAAU,IAAIA,kCAAU,EAC3B,UAJA,QAAQ,IAAI,gCACZ,oCAID,CAAC;AAEF,OAAK,oBAAoB;GACvB,2BAA2B;GAC3B,8BAA8B;GAC/B,CAAC;;CAGJ,AAAQ,kBAAkB;AAExB,SADqB,KAAK,QAAQ,GACZ,KAAK;;CAG7B,MAAM,QACJ,OACA,YACe;AACf,SAAO,KAAK,oBAAoB,OA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C,OAAK,eAAe,iBAAiB;AACrC,OAAK,qBAAqB,iBAAiB;;;;;;;CAQ7C,gBAAgB,cAAsB;AACpC,OAAK,qBAAqB,EAAE,cAAc,CAAC;;;;;;;;;;;;;CAc7C,YAAY,UAA+C;EACzD,MAAM,mBAAmB,KAAK,yBAAyB,SAAS;AAEhE,SAAO,EACL,UACE,OACA,eACG,KAAK,oBAAoB,OAAO,YAAY,iBAAiB,EACnE;;CAGH,AAAQ,yBACN,UAC2B;EAC3B,MAAM,cAAcE,+CAAyB,SAAS,YAAY;AAClE,MAAI,gBAAgB,OAClB,QAAO;GACL;GACA,cAAc;GACd,oBAAoB;GACrB;AAGH,SAAO;GACL,aAAa;GACb,cAAc,SAAS,gBAAgB;GACvC,oBAAoB,SAAS,eACzBC,8CAAwB,SAAS,aAAa,GAC9C;GACL;;CAGH,AAAQ,cAAc,YAAgC;EACpD,IAAI;AAEJ,gBAAc,cAAc;AAG5B,MAAI,QAAQ,IAAI,iCAEd,eAAc,WAAW,QAAQ,IAAI,iCAAiC;AAOxE,MAAI,OAAO,MAAM,YAAY,IAAI,cAAc,KAAK,cAAc,EAChE,OAAM,IAAI,MAAM,sCAAsC;AAGxD,OAAK,aAAa"}
1
+ {"version":3,"file":"telemetry-client.cjs","names":["isTelemetryDisabled","Analytics","computeSamplingMeta","TELEMETRY_EMITTER_V1","flattenObject","lambdaClient","firstNonBlankTelemetryId","parseAndWarnTelemetryId"],"sources":["../../src/telemetry/telemetry-client.ts"],"sourcesContent":["import { Analytics } from \"@segment/analytics-node\";\nimport type { AnalyticsEvents } from \"./events\";\nimport { flattenObject } from \"./utils\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseAndWarnTelemetryId,\n} from \"./lambda-client\";\nimport { computeSamplingMeta, TELEMETRY_EMITTER_V1 } from \"./sampling\";\nimport { isTelemetryDisabled } from \"./telemetry-disabled\";\n\nexport { isTelemetryDisabled };\n\n/** Transport identity and sampling authority resolved for one runtime. */\nexport interface TelemetryIdentity {\n telemetryId?: string;\n licenseToken?: string;\n}\n\n/** Capture-only telemetry client bound to one runtime identity. */\nexport interface TelemetryCapture {\n capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void>;\n}\n\ninterface ResolvedTelemetryIdentity {\n telemetryId: string | null;\n licenseToken: string | null;\n licenseTelemetryId: string | null;\n}\n\nexport class TelemetryClient {\n segment: Analytics | undefined;\n globalProperties: Record<string, any> = {};\n cloudConfiguration: { publicApiKey: string; baseUrl: string } | null = null;\n // EIP / Intelligence license token (Ed25519-signed JWT). The lambda\n // client decodes its payload to extract telemetry_id. Customer API\n // keys are NOT used here — they flow only into Segment.\n private licenseToken: string | null = null;\n // Standalone analytics identity. This stays separate from the effective\n // identity so legacy callers continue sending only their license token to\n // the Lambda transport.\n private telemetryId: string | null = null;\n // License-derived identity used only as sampling authority. A standalone\n // telemetry id remains a transport claim and does not bypass sampleRate.\n private licenseTelemetryId: string | null = null;\n packageName: string;\n packageVersion: string;\n private telemetryDisabled: boolean = false;\n // Client-side sampling rate for anonymous events. Identified events\n // (those whose license token yielded a telemetry_id) bypass the gate\n // entirely. Applied uniformly to both the lambda sink and Segment —\n // one dice roll per capture, both sinks see the same decision.\n private sampleRate: number = 0.05;\n private anonymousId = `anon_${uuidv4()}`;\n\n constructor({\n packageName,\n packageVersion,\n telemetryDisabled,\n telemetryBaseUrl,\n sampleRate,\n }: {\n packageName: string;\n packageVersion: string;\n telemetryDisabled?: boolean;\n telemetryBaseUrl?: string;\n sampleRate?: number;\n }) {\n this.packageName = packageName;\n this.packageVersion = packageVersion;\n this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();\n\n if (this.telemetryDisabled) {\n return;\n }\n\n this.setSampleRate(sampleRate);\n\n // eslint-disable-next-line\n const writeKey =\n process.env.COPILOTKIT_SEGMENT_WRITE_KEY ||\n \"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja\";\n\n this.segment = new Analytics({\n writeKey,\n });\n\n this.setGlobalProperties({\n \"copilotkit.package.name\": packageName,\n \"copilotkit.package.version\": packageVersion,\n });\n }\n\n private shouldSendEvent() {\n const randomNumber = Math.random();\n return randomNumber < this.sampleRate;\n }\n\n async capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void> {\n return this.captureWithIdentity(event, properties, {\n telemetryId: this.telemetryId,\n licenseToken: this.licenseToken,\n licenseTelemetryId: this.licenseTelemetryId,\n });\n }\n\n private async captureWithIdentity<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n identity: ResolvedTelemetryIdentity,\n ): Promise<void> {\n if (this.telemetryDisabled) {\n return;\n }\n\n // Callers without license-derived sampling authority are gated by\n // sampleRate. Legacy license tokens with telemetry_id always send —\n // the volume is bounded by paying-customer count and full fidelity\n // per identified customer is worth the marginal cost.\n if (!identity.licenseTelemetryId && !this.shouldSendEvent()) {\n return;\n }\n\n // Sampling metadata is computed in ./sampling so this client and the\n // v2 runtime client can't drift apart again — see the note there.\n const samplingMeta = computeSamplingMeta({\n telemetryId: identity.licenseTelemetryId,\n sampleRate: this.sampleRate,\n });\n\n // Everything below travels identically on both copies of this event.\n // The event id is what makes the dual-write dedupable downstream:\n // one capture() produces one id, stamped on the lambda copy and the\n // Segment copy alike, so consumers no longer have to infer the\n // duplication from $lib or from which fields happen to be present\n // (OSS-1019).\n const eventMeta = {\n ...samplingMeta,\n telemetry_emitter: TELEMETRY_EMITTER_V1,\n telemetry_event_id: uuidv4(),\n };\n\n const flattenedProperties = flattenObject(properties);\n const propertiesWithGlobal: Record<string, any> = {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"segment\",\n ...flattenedProperties,\n };\n const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal)\n .sort()\n .reduce(\n (obj, key) => {\n obj[key] = propertiesWithGlobal[key];\n return obj;\n },\n {} as Record<string, any>,\n );\n\n await lambdaClient.send({\n event,\n properties: flattenedProperties,\n globalProperties: {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"lambda\",\n },\n packageName: this.packageName,\n packageVersion: this.packageVersion,\n telemetryId: identity.telemetryId ?? undefined,\n licenseToken: identity.licenseToken ?? undefined,\n });\n\n if (this.segment) {\n this.segment.track({\n anonymousId: this.anonymousId,\n event,\n properties: { ...orderedPropertiesWithGlobal },\n });\n }\n }\n\n setGlobalProperties(properties: Record<string, any>) {\n const flattenedProperties = flattenObject(properties);\n this.globalProperties = {\n ...this.globalProperties,\n ...flattenedProperties,\n };\n }\n\n setCloudConfiguration(properties: { publicApiKey: string; baseUrl: string }) {\n this.cloudConfiguration = properties;\n\n this.setGlobalProperties({\n cloud: {\n publicApiKey: properties.publicApiKey,\n baseUrl: properties.baseUrl,\n },\n });\n }\n\n /**\n * Atomically configure standalone, legacy, or anonymous telemetry identity.\n *\n * A standalone id takes transport precedence over a supplied legacy license\n * token, but only a license-derived id grants sampling authority. Neither\n * value is added to event properties.\n *\n * @param identity - One standalone id, one legacy license token, or neither.\n */\n setTelemetryIdentity(identity: {\n telemetryId?: string;\n licenseToken?: string;\n }): void {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n this.telemetryId = resolvedIdentity.telemetryId;\n this.licenseToken = resolvedIdentity.licenseToken;\n this.licenseTelemetryId = resolvedIdentity.licenseTelemetryId;\n }\n\n /**\n * Configure legacy license-derived telemetry identity.\n *\n * @param licenseToken - License token whose telemetry claim identifies sends.\n */\n setLicenseToken(licenseToken: string) {\n this.setTelemetryIdentity({ licenseToken });\n }\n\n /**\n * Create an immutable capture scope for one runtime.\n *\n * The scope shares this client's sinks, process-wide opt-out, global\n * properties, and sampling settings, but snapshots transport identity and\n * license-derived sampling authority. Constructing another runtime cannot\n * rewrite an existing scope.\n *\n * @param identity - The runtime's construction-time telemetry identity.\n * @returns A capture-only client bound to that identity.\n */\n createScope(identity: TelemetryIdentity): TelemetryCapture {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n\n return {\n capture: <K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ) => this.captureWithIdentity(event, properties, resolvedIdentity),\n };\n }\n\n private resolveTelemetryIdentity(\n identity: TelemetryIdentity,\n ): ResolvedTelemetryIdentity {\n const telemetryId = firstNonBlankTelemetryId(identity.telemetryId);\n if (telemetryId !== undefined) {\n return {\n telemetryId,\n licenseToken: null,\n licenseTelemetryId: null,\n };\n }\n\n return {\n telemetryId: null,\n licenseToken: identity.licenseToken ?? null,\n licenseTelemetryId: identity.licenseToken\n ? parseAndWarnTelemetryId(identity.licenseToken)\n : null,\n };\n }\n\n private setSampleRate(sampleRate: number | undefined) {\n let _sampleRate: number;\n\n _sampleRate = sampleRate ?? 0.05;\n\n // eslint-disable-next-line\n if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) {\n // eslint-disable-next-line\n _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);\n }\n\n // Number.isNaN guards against parseFloat(\"nonsense\") slipping past the\n // range check (all NaN comparisons are false), which would silently\n // drop every anonymous event with no signal — especially important\n // since the default is now 0.05, making env-var overrides more common.\n if (Number.isNaN(_sampleRate) || _sampleRate < 0 || _sampleRate > 1) {\n throw new Error(\"Sample rate must be between 0 and 1\");\n }\n\n this.sampleRate = _sampleRate;\n // Per-event sampling metadata (sampleRate/sampleRateAdjustmentFactor/\n // sampleWeight) is computed per capture() in ./sampling. Only license-\n // authorized events get effectiveSampleRate=1; standalone transport\n // identity stays in the sampled population.\n }\n}\n"],"mappings":";;;;;;;;;AAkCA,IAAa,kBAAb,MAA6B;CAyB3B,YAAY,EACV,aACA,gBACA,mBACA,kBACA,cAOC;0BAnCqC,EAAE;4BAC6B;sBAIjC;qBAID;4BAGO;2BAGP;oBAKR;qBACP,sBAAgB;AAepC,OAAK,cAAc;AACnB,OAAK,iBAAiB;AACtB,OAAK,oBAAoB,qBAAqBA,gDAAqB;AAEn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BD,4BAAc,WAAW;AACrD,OAAK,mBAAmB;GACtB,GAAG,KAAK;GACR,GAAG;GACJ;;CAGH,sBAAsB,YAAuD;AAC3E,OAAK,qBAAqB;AAE1B,OAAK,oBAAoB,EACvB,OAAO;GACL,cAAc,WAAW;GACzB,SAAS,WAAW;GACrB,EACF,CAAC;;;;;;;;;;;CAYJ,qBAAqB,UAGZ;EACP,MAAM,mBAAmB,KAAK,yBAAyB,SAAS;AAChE,OAAK,cAAc,iBAAiB;AACpC,OAAK,eAAe,iBAAiB;AACrC,OAAK,qBAAqB,iBAAiB;;;;;;;CAQ7C,gBAAgB,cAAsB;AACpC,OAAK,qBAAqB,EAAE,cAAc,CAAC;;;;;;;;;;;;;CAc7C,YAAY,UAA+C;EACzD,MAAM,mBAAmB,KAAK,yBAAyB,SAAS;AAEhE,SAAO,EACL,UACE,OACA,eACG,KAAK,oBAAoB,OAAO,YAAY,iBAAiB,EACnE;;CAGH,AAAQ,yBACN,UAC2B;EAC3B,MAAM,cAAcE,+CAAyB,SAAS,YAAY;AAClE,MAAI,gBAAgB,OAClB,QAAO;GACL;GACA,cAAc;GACd,oBAAoB;GACrB;AAGH,SAAO;GACL,aAAa;GACb,cAAc,SAAS,gBAAgB;GACvC,oBAAoB,SAAS,eACzBC,8CAAwB,SAAS,aAAa,GAC9C;GACL;;CAGH,AAAQ,cAAc,YAAgC;EACpD,IAAI;AAEJ,gBAAc,cAAc;AAG5B,MAAI,QAAQ,IAAI,iCAEd,eAAc,WAAW,QAAQ,IAAI,iCAAiC;AAOxE,MAAI,OAAO,MAAM,YAAY,IAAI,cAAc,KAAK,cAAc,EAChE,OAAM,IAAI,MAAM,sCAAsC;AAGxD,OAAK,aAAa"}
@@ -1,14 +1,8 @@
1
+ import { isTelemetryDisabled } from "./telemetry-disabled.cjs";
1
2
  import { AnalyticsEvents } from "./events.cjs";
2
3
  import { Analytics } from "@segment/analytics-node";
3
4
 
4
5
  //#region src/telemetry/telemetry-client.d.ts
5
- /**
6
- * Checks if telemetry is disabled via environment variables.
7
- * Users can opt out by setting:
8
- * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
9
- * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
10
- */
11
- declare function isTelemetryDisabled(): boolean;
12
6
  /** Transport identity and sampling authority resolved for one runtime. */
13
7
  interface TelemetryIdentity {
14
8
  telemetryId?: string;
@@ -89,5 +83,5 @@ declare class TelemetryClient {
89
83
  private setSampleRate;
90
84
  }
91
85
  //#endregion
92
- export { TelemetryCapture, TelemetryClient, TelemetryIdentity, isTelemetryDisabled };
86
+ export { TelemetryCapture, TelemetryClient, TelemetryIdentity };
93
87
  //# sourceMappingURL=telemetry-client.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-client.d.cts","names":[],"sources":["../../src/telemetry/telemetry-client.ts"],"mappings":";;;;;;AAiBA;;;;iBAAgB,mBAAA,CAAA;AAahB;AAAA,UAAiB,iBAAA;EACf,WAAA;EACA,YAAA;AAAA;AAIF;AAAA,UAAiB,gBAAA;EACf,OAAA,iBAAwB,eAAA,EACtB,KAAA,EAAO,CAAA,EACP,UAAA,EAAY,eAAA,CAAgB,CAAA,IAC3B,OAAA;AAAA;AAAA,cASQ,eAAA;EACX,OAAA,EAAS,SAAA;EACT,gBAAA,EAAkB,MAAA;EAClB,kBAAA;IAAsB,YAAA;IAAsB,OAAA;EAAA;EAAA,QAIpC,YAAA;EAAA,QAIA,WAAA;EAAA,QAGA,kBAAA;EACR,WAAA;EACA,cAAA;EAAA,QACQ,iBAAA;EAAA,QAKA,UAAA;EAAA,QACA,WAAA;;IAGN,WAAA;IACA,cAAA;IACA,iBAAA;IACA,gBAAA;IACA;EAAA;IAEA,WAAA;IACA,cAAA;IACA,iBAAA;IACA,gBAAA;IACA,UAAA;EAAA;EAAA,QA2BM,eAAA;EAKF,OAAA,iBAAwB,eAAA,CAAA,CAC5B,KAAA,EAAO,CAAA,EACP,UAAA,EAAY,eA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EAAA;EA7F5C;;;;;;;;;EAiHd,oBAAA,CAAqB,QAAA;IACnB,WAAA;IACA,YAAA;EAAA;EAtLoB;;;;;EAmMtB,eAAA,CAAgB,YAAA;EAtLhB;;;;;;;;;;;EAqMA,WAAA,CAAY,QAAA,EAAU,iBAAA,GAAoB,gBAAA;EAAA,QAWlC,wBAAA;EAAA,QAqBA,aAAA;AAAA"}
@@ -1,14 +1,8 @@
1
+ import { isTelemetryDisabled } from "./telemetry-disabled.mjs";
1
2
  import { AnalyticsEvents } from "./events.mjs";
2
3
  import { Analytics } from "@segment/analytics-node";
3
4
 
4
5
  //#region src/telemetry/telemetry-client.d.ts
5
- /**
6
- * Checks if telemetry is disabled via environment variables.
7
- * Users can opt out by setting:
8
- * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
9
- * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
10
- */
11
- declare function isTelemetryDisabled(): boolean;
12
6
  /** Transport identity and sampling authority resolved for one runtime. */
13
7
  interface TelemetryIdentity {
14
8
  telemetryId?: string;
@@ -89,5 +83,5 @@ declare class TelemetryClient {
89
83
  private setSampleRate;
90
84
  }
91
85
  //#endregion
92
- export { TelemetryCapture, TelemetryClient, TelemetryIdentity, isTelemetryDisabled };
86
+ export { TelemetryCapture, TelemetryClient, TelemetryIdentity };
93
87
  //# sourceMappingURL=telemetry-client.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-client.d.mts","names":[],"sources":["../../src/telemetry/telemetry-client.ts"],"mappings":";;;;;;AAiBA;;;;iBAAgB,mBAAA,CAAA;AAahB;AAAA,UAAiB,iBAAA;EACf,WAAA;EACA,YAAA;AAAA;AAIF;AAAA,UAAiB,gBAAA;EACf,OAAA,iBAAwB,eAAA,EACtB,KAAA,EAAO,CAAA,EACP,UAAA,EAAY,eAAA,CAAgB,CAAA,IAC3B,OAAA;AAAA;AAAA,cASQ,eAAA;EACX,OAAA,EAAS,SAAA;EACT,g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EAAA,QACQ,iBAAA;EAAA,QAKA,UAAA;EAAA,QACA,WAAA;;IAGN,WAAA;IACA,cAAA;IACA,iBAAA;IACA,gBAAA;IACA;EAAA;IAEA,WAAA;IACA,cAAA;IACA,iBAAA;IACA,gBAAA;IACA,UAAA;EAAA;EAAA,QA2BM,eAAA;EAKF,OAAA,iBAAwB,eAAA,CAAA,CAC5B,KAAA,EAAO,CAAA,EACP,UAAA,EAAY,eAAA,CAAgB,CAAA,IAC3B,OAAA;EAAA,QAQW,mBAAA;EA4Ed,mBAAA,CAAoB,UAAA,EAAY,MAAA;EAQhC,qBAAA,CAAsB,UAAA;IAAc,YAAA;IAAsB,OAAA;EAAA;EA7F5C;;;;;;;;;EAiHd,oBAAA,CAAqB,QAAA;IACnB,WAAA;IACA,YAAA;EAAA;EAtLoB;;;;;EAmMtB,eAAA,CAAgB,YAAA;EAtLhB;;;;;;;;;;;EAqMA,WAAA,CAAY,QAAA,EAAU,iBAAA,GAAoB,gBAAA;EAAA,QAWlC,wBAAA;EAAA,QAqBA,aAAA;AAAA"}
@@ -1,19 +1,11 @@
1
- import { flattenObject } from "./utils.mjs";
2
- import { firstNonBlankTelemetryId, lambdaClient, parseAndWarnTelemetryId } from "./lambda-client.mjs";
1
+ import { isTelemetryDisabled } from "./telemetry-disabled.mjs";
3
2
  import { TELEMETRY_EMITTER_V1, computeSamplingMeta } from "./sampling.mjs";
3
+ import { firstNonBlankTelemetryId, lambdaClient, parseAndWarnTelemetryId } from "./lambda-client.mjs";
4
+ import { flattenObject } from "./utils.mjs";
4
5
  import { v4 } from "uuid";
5
6
  import { Analytics } from "@segment/analytics-node";
6
7
 
7
8
  //#region src/telemetry/telemetry-client.ts
8
- /**
9
- * Checks if telemetry is disabled via environment variables.
10
- * Users can opt out by setting:
11
- * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
12
- * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
13
- */
14
- function isTelemetryDisabled() {
15
- return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
16
- }
17
9
  var TelemetryClient = class {
18
10
  constructor({ packageName, packageVersion, telemetryDisabled, telemetryBaseUrl, sampleRate }) {
19
11
  this.globalProperties = {};
@@ -161,5 +153,5 @@ var TelemetryClient = class {
161
153
  };
162
154
 
163
155
  //#endregion
164
- export { TelemetryClient, isTelemetryDisabled };
156
+ export { TelemetryClient };
165
157
  //# sourceMappingURL=telemetry-client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-client.mjs","names":["uuidv4"],"sources":["../../src/telemetry/telemetry-client.ts"],"sourcesContent":["import { Analytics } from \"@segment/analytics-node\";\nimport type { AnalyticsEvents } from \"./events\";\nimport { flattenObject } from \"./utils\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseAndWarnTelemetryId,\n} from \"./lambda-client\";\nimport { computeSamplingMeta, TELEMETRY_EMITTER_V1 } from \"./sampling\";\n\n/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK ===\n \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n\n/** Transport identity and sampling authority resolved for one runtime. */\nexport interface TelemetryIdentity {\n telemetryId?: string;\n licenseToken?: string;\n}\n\n/** Capture-only telemetry client bound to one runtime identity. */\nexport interface TelemetryCapture {\n capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void>;\n}\n\ninterface ResolvedTelemetryIdentity {\n telemetryId: string | null;\n licenseToken: string | null;\n licenseTelemetryId: string | null;\n}\n\nexport class TelemetryClient {\n segment: Analytics | undefined;\n globalProperties: Record<string, any> = {};\n cloudConfiguration: { publicApiKey: string; baseUrl: string } | null = null;\n // EIP / Intelligence license token (Ed25519-signed JWT). The lambda\n // client decodes its payload to extract telemetry_id. Customer API\n // keys are NOT used here — they flow only into Segment.\n private licenseToken: string | null = null;\n // Standalone analytics identity. This stays separate from the effective\n // identity so legacy callers continue sending only their license token to\n // the Lambda transport.\n private telemetryId: string | null = null;\n // License-derived identity used only as sampling authority. A standalone\n // telemetry id remains a transport claim and does not bypass sampleRate.\n private licenseTelemetryId: string | null = null;\n packageName: string;\n packageVersion: string;\n private telemetryDisabled: boolean = false;\n // Client-side sampling rate for anonymous events. Identified events\n // (those whose license token yielded a telemetry_id) bypass the gate\n // entirely. Applied uniformly to both the lambda sink and Segment —\n // one dice roll per capture, both sinks see the same decision.\n private sampleRate: number = 0.05;\n private anonymousId = `anon_${uuidv4()}`;\n\n constructor({\n packageName,\n packageVersion,\n telemetryDisabled,\n telemetryBaseUrl,\n sampleRate,\n }: {\n packageName: string;\n packageVersion: string;\n telemetryDisabled?: boolean;\n telemetryBaseUrl?: string;\n sampleRate?: number;\n }) {\n this.packageName = packageName;\n this.packageVersion = packageVersion;\n this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();\n\n if (this.telemetryDisabled) {\n return;\n }\n\n this.setSampleRate(sampleRate);\n\n // eslint-disable-next-line\n const writeKey =\n process.env.COPILOTKIT_SEGMENT_WRITE_KEY ||\n \"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja\";\n\n this.segment = new Analytics({\n writeKey,\n });\n\n this.setGlobalProperties({\n \"copilotkit.package.name\": packageName,\n \"copilotkit.package.version\": packageVersion,\n });\n }\n\n private shouldSendEvent() {\n const randomNumber = Math.random();\n return randomNumber < this.sampleRate;\n }\n\n async capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void> {\n return this.captureWithIdentity(event, properties, {\n telemetryId: this.telemetryId,\n licenseToken: this.licenseToken,\n licenseTelemetryId: this.licenseTelemetryId,\n });\n }\n\n private async captureWithIdentity<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n identity: ResolvedTelemetryIdentity,\n ): Promise<void> {\n if (this.telemetryDisabled) {\n return;\n }\n\n // Callers without license-derived sampling authority are gated by\n // sampleRate. Legacy license tokens with telemetry_id always send —\n // the volume is bounded by paying-customer count and full fidelity\n // per identified customer is worth the marginal cost.\n if (!identity.licenseTelemetryId && !this.shouldSendEvent()) {\n return;\n }\n\n // Sampling metadata is computed in ./sampling so this client and the\n // v2 runtime client can't drift apart again — see the note there.\n const samplingMeta = computeSamplingMeta({\n telemetryId: identity.licenseTelemetryId,\n sampleRate: this.sampleRate,\n });\n\n // Everything below travels identically on both copies of this event.\n // The event id is what makes the dual-write dedupable downstream:\n // one capture() produces one id, stamped on the lambda copy and the\n // Segment copy alike, so consumers no longer have to infer the\n // duplication from $lib or from which fields happen to be present\n // (OSS-1019).\n const eventMeta = {\n ...samplingMeta,\n telemetry_emitter: TELEMETRY_EMITTER_V1,\n telemetry_event_id: uuidv4(),\n };\n\n const flattenedProperties = flattenObject(properties);\n const propertiesWithGlobal: Record<string, any> = {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"segment\",\n ...flattenedProperties,\n };\n const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal)\n .sort()\n .reduce(\n (obj, key) => {\n obj[key] = propertiesWithGlobal[key];\n return obj;\n },\n {} as Record<string, any>,\n );\n\n await lambdaClient.send({\n event,\n properties: flattenedProperties,\n globalProperties: {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"lambda\",\n },\n packageName: this.packageName,\n packageVersion: this.packageVersion,\n telemetryId: identity.telemetryId ?? undefined,\n licenseToken: identity.licenseToken ?? undefined,\n });\n\n if (this.segment) {\n this.segment.track({\n anonymousId: this.anonymousId,\n event,\n properties: { ...orderedPropertiesWithGlobal },\n });\n }\n }\n\n setGlobalProperties(properties: Record<string, any>) {\n const flattenedProperties = flattenObject(properties);\n this.globalProperties = {\n ...this.globalProperties,\n ...flattenedProperties,\n };\n }\n\n setCloudConfiguration(properties: { publicApiKey: string; baseUrl: string }) {\n this.cloudConfiguration = properties;\n\n this.setGlobalProperties({\n cloud: {\n publicApiKey: properties.publicApiKey,\n baseUrl: properties.baseUrl,\n },\n });\n }\n\n /**\n * Atomically configure standalone, legacy, or anonymous telemetry identity.\n *\n * A standalone id takes transport precedence over a supplied legacy license\n * token, but only a license-derived id grants sampling authority. Neither\n * value is added to event properties.\n *\n * @param identity - One standalone id, one legacy license token, or neither.\n */\n setTelemetryIdentity(identity: {\n telemetryId?: string;\n licenseToken?: string;\n }): void {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n this.telemetryId = resolvedIdentity.telemetryId;\n this.licenseToken = resolvedIdentity.licenseToken;\n this.licenseTelemetryId = resolvedIdentity.licenseTelemetryId;\n }\n\n /**\n * Configure legacy license-derived telemetry identity.\n *\n * @param licenseToken - License token whose telemetry claim identifies sends.\n */\n setLicenseToken(licenseToken: string) {\n this.setTelemetryIdentity({ licenseToken });\n }\n\n /**\n * Create an immutable capture scope for one runtime.\n *\n * The scope shares this client's sinks, process-wide opt-out, global\n * properties, and sampling settings, but snapshots transport identity and\n * license-derived sampling authority. Constructing another runtime cannot\n * rewrite an existing scope.\n *\n * @param identity - The runtime's construction-time telemetry identity.\n * @returns A capture-only client bound to that identity.\n */\n createScope(identity: TelemetryIdentity): TelemetryCapture {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n\n return {\n capture: <K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ) => this.captureWithIdentity(event, properties, resolvedIdentity),\n };\n }\n\n private resolveTelemetryIdentity(\n identity: TelemetryIdentity,\n ): ResolvedTelemetryIdentity {\n const telemetryId = firstNonBlankTelemetryId(identity.telemetryId);\n if (telemetryId !== undefined) {\n return {\n telemetryId,\n licenseToken: null,\n licenseTelemetryId: null,\n };\n }\n\n return {\n telemetryId: null,\n licenseToken: identity.licenseToken ?? null,\n licenseTelemetryId: identity.licenseToken\n ? parseAndWarnTelemetryId(identity.licenseToken)\n : null,\n };\n }\n\n private setSampleRate(sampleRate: number | undefined) {\n let _sampleRate: number;\n\n _sampleRate = sampleRate ?? 0.05;\n\n // eslint-disable-next-line\n if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) {\n // eslint-disable-next-line\n _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);\n }\n\n // Number.isNaN guards against parseFloat(\"nonsense\") slipping past the\n // range check (all NaN comparisons are false), which would silently\n // drop every anonymous event with no signal — especially important\n // since the default is now 0.05, making env-var overrides more common.\n if (Number.isNaN(_sampleRate) || _sampleRate < 0 || _sampleRate > 1) {\n throw new Error(\"Sample rate must be between 0 and 1\");\n }\n\n this.sampleRate = _sampleRate;\n // Per-event sampling metadata (sampleRate/sampleRateAdjustmentFactor/\n // sampleWeight) is computed per capture() in ./sampling. Only license-\n // authorized events get effectiveSampleRate=1; standalone transport\n // identity stays in the sampled population.\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,SAAgB,sBAA+B;AAC7C,QACG,QAAQ,IACN,kCAAkC,UACpC,QAAQ,IACN,kCAAkC,OACpC,QAAQ,IAA2C,iBAClD,UACD,QAAQ,IAA2C,iBAAiB;;AAwBzE,IAAa,kBAAb,MAA6B;CAyB3B,YAAY,EACV,aACA,gBACA,mBACA,kBACA,cAOC;0BAnCqC,EAAE;4BAC6B;sBAIjC;qBAID;4BAGO;2BAGP;oBAKR;qBACP,QAAQA,IAAQ;AAepC,OAAK,cAAc;AACnB,OAAK,iBA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AAC;;CAIN,oBAAoB,YAAiC;EACnD,MAAM,sBAAsB,cAAc,WAAW;AACrD,OAAK,mBAAmB;GACtB,GAAG,KAAK;GACR,GAAG;GACJ;;CAGH,sBAAsB,YAAuD;AAC3E,OAAK,qBAAqB;AAE1B,OAAK,oBAAoB,EACvB,OAAO;GACL,cAAc,WAAW;GACzB,SAAS,WAAW;GACrB,EACF,CAAC;;;;;;;;;;;CAYJ,qBAAqB,UAGZ;EACP,MAAM,mBAAmB,KAAK,yBAAyB,SAAS;AAChE,OAAK,cAAc,iBAAiB;AACpC,OAAK,eAAe,iBAAiB;AACrC,OAAK,qBAAqB,iBAAiB;;;;;;;CAQ7C,gBAAgB,cAAsB;AACpC,OAAK,qBAAqB,EAAE,cAAc,CAAC;;;;;;;;;;;;;CAc7C,YAAY,UAA+C;EACzD,MAAM,mBAAmB,KAAK,yBAAyB,SAAS;AAEhE,SAAO,EACL,UACE,OACA,eACG,KAAK,oBAAoB,OAAO,YAAY,iBAAiB,EACnE;;CAGH,AAAQ,yBACN,UAC2B;EAC3B,MAAM,cAAc,yBAAyB,SAAS,YAAY;AAClE,MAAI,gBAAgB,OAClB,QAAO;GACL;GACA,cAAc;GACd,oBAAoB;GACrB;AAGH,SAAO;GACL,aAAa;GACb,cAAc,SAAS,gBAAgB;GACvC,oBAAoB,SAAS,eACzB,wBAAwB,SAAS,aAAa,GAC9C;GACL;;CAGH,AAAQ,cAAc,YAAgC;EACpD,IAAI;AAEJ,gBAAc,cAAc;AAG5B,MAAI,QAAQ,IAAI,iCAEd,eAAc,WAAW,QAAQ,IAAI,iCAAiC;AAOxE,MAAI,OAAO,MAAM,YAAY,IAAI,cAAc,KAAK,cAAc,EAChE,OAAM,IAAI,MAAM,sCAAsC;AAGxD,OAAK,aAAa"}
1
+ {"version":3,"file":"telemetry-client.mjs","names":["uuidv4"],"sources":["../../src/telemetry/telemetry-client.ts"],"sourcesContent":["import { Analytics } from \"@segment/analytics-node\";\nimport type { AnalyticsEvents } from \"./events\";\nimport { flattenObject } from \"./utils\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseAndWarnTelemetryId,\n} from \"./lambda-client\";\nimport { computeSamplingMeta, TELEMETRY_EMITTER_V1 } from \"./sampling\";\nimport { isTelemetryDisabled } from \"./telemetry-disabled\";\n\nexport { isTelemetryDisabled };\n\n/** Transport identity and sampling authority resolved for one runtime. */\nexport interface TelemetryIdentity {\n telemetryId?: string;\n licenseToken?: string;\n}\n\n/** Capture-only telemetry client bound to one runtime identity. */\nexport interface TelemetryCapture {\n capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void>;\n}\n\ninterface ResolvedTelemetryIdentity {\n telemetryId: string | null;\n licenseToken: string | null;\n licenseTelemetryId: string | null;\n}\n\nexport class TelemetryClient {\n segment: Analytics | undefined;\n globalProperties: Record<string, any> = {};\n cloudConfiguration: { publicApiKey: string; baseUrl: string } | null = null;\n // EIP / Intelligence license token (Ed25519-signed JWT). The lambda\n // client decodes its payload to extract telemetry_id. Customer API\n // keys are NOT used here — they flow only into Segment.\n private licenseToken: string | null = null;\n // Standalone analytics identity. This stays separate from the effective\n // identity so legacy callers continue sending only their license token to\n // the Lambda transport.\n private telemetryId: string | null = null;\n // License-derived identity used only as sampling authority. A standalone\n // telemetry id remains a transport claim and does not bypass sampleRate.\n private licenseTelemetryId: string | null = null;\n packageName: string;\n packageVersion: string;\n private telemetryDisabled: boolean = false;\n // Client-side sampling rate for anonymous events. Identified events\n // (those whose license token yielded a telemetry_id) bypass the gate\n // entirely. Applied uniformly to both the lambda sink and Segment —\n // one dice roll per capture, both sinks see the same decision.\n private sampleRate: number = 0.05;\n private anonymousId = `anon_${uuidv4()}`;\n\n constructor({\n packageName,\n packageVersion,\n telemetryDisabled,\n telemetryBaseUrl,\n sampleRate,\n }: {\n packageName: string;\n packageVersion: string;\n telemetryDisabled?: boolean;\n telemetryBaseUrl?: string;\n sampleRate?: number;\n }) {\n this.packageName = packageName;\n this.packageVersion = packageVersion;\n this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();\n\n if (this.telemetryDisabled) {\n return;\n }\n\n this.setSampleRate(sampleRate);\n\n // eslint-disable-next-line\n const writeKey =\n process.env.COPILOTKIT_SEGMENT_WRITE_KEY ||\n \"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja\";\n\n this.segment = new Analytics({\n writeKey,\n });\n\n this.setGlobalProperties({\n \"copilotkit.package.name\": packageName,\n \"copilotkit.package.version\": packageVersion,\n });\n }\n\n private shouldSendEvent() {\n const randomNumber = Math.random();\n return randomNumber < this.sampleRate;\n }\n\n async capture<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ): Promise<void> {\n return this.captureWithIdentity(event, properties, {\n telemetryId: this.telemetryId,\n licenseToken: this.licenseToken,\n licenseTelemetryId: this.licenseTelemetryId,\n });\n }\n\n private async captureWithIdentity<K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n identity: ResolvedTelemetryIdentity,\n ): Promise<void> {\n if (this.telemetryDisabled) {\n return;\n }\n\n // Callers without license-derived sampling authority are gated by\n // sampleRate. Legacy license tokens with telemetry_id always send —\n // the volume is bounded by paying-customer count and full fidelity\n // per identified customer is worth the marginal cost.\n if (!identity.licenseTelemetryId && !this.shouldSendEvent()) {\n return;\n }\n\n // Sampling metadata is computed in ./sampling so this client and the\n // v2 runtime client can't drift apart again — see the note there.\n const samplingMeta = computeSamplingMeta({\n telemetryId: identity.licenseTelemetryId,\n sampleRate: this.sampleRate,\n });\n\n // Everything below travels identically on both copies of this event.\n // The event id is what makes the dual-write dedupable downstream:\n // one capture() produces one id, stamped on the lambda copy and the\n // Segment copy alike, so consumers no longer have to infer the\n // duplication from $lib or from which fields happen to be present\n // (OSS-1019).\n const eventMeta = {\n ...samplingMeta,\n telemetry_emitter: TELEMETRY_EMITTER_V1,\n telemetry_event_id: uuidv4(),\n };\n\n const flattenedProperties = flattenObject(properties);\n const propertiesWithGlobal: Record<string, any> = {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"segment\",\n ...flattenedProperties,\n };\n const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal)\n .sort()\n .reduce(\n (obj, key) => {\n obj[key] = propertiesWithGlobal[key];\n return obj;\n },\n {} as Record<string, any>,\n );\n\n await lambdaClient.send({\n event,\n properties: flattenedProperties,\n globalProperties: {\n ...this.globalProperties,\n ...eventMeta,\n telemetry_transport: \"lambda\",\n },\n packageName: this.packageName,\n packageVersion: this.packageVersion,\n telemetryId: identity.telemetryId ?? undefined,\n licenseToken: identity.licenseToken ?? undefined,\n });\n\n if (this.segment) {\n this.segment.track({\n anonymousId: this.anonymousId,\n event,\n properties: { ...orderedPropertiesWithGlobal },\n });\n }\n }\n\n setGlobalProperties(properties: Record<string, any>) {\n const flattenedProperties = flattenObject(properties);\n this.globalProperties = {\n ...this.globalProperties,\n ...flattenedProperties,\n };\n }\n\n setCloudConfiguration(properties: { publicApiKey: string; baseUrl: string }) {\n this.cloudConfiguration = properties;\n\n this.setGlobalProperties({\n cloud: {\n publicApiKey: properties.publicApiKey,\n baseUrl: properties.baseUrl,\n },\n });\n }\n\n /**\n * Atomically configure standalone, legacy, or anonymous telemetry identity.\n *\n * A standalone id takes transport precedence over a supplied legacy license\n * token, but only a license-derived id grants sampling authority. Neither\n * value is added to event properties.\n *\n * @param identity - One standalone id, one legacy license token, or neither.\n */\n setTelemetryIdentity(identity: {\n telemetryId?: string;\n licenseToken?: string;\n }): void {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n this.telemetryId = resolvedIdentity.telemetryId;\n this.licenseToken = resolvedIdentity.licenseToken;\n this.licenseTelemetryId = resolvedIdentity.licenseTelemetryId;\n }\n\n /**\n * Configure legacy license-derived telemetry identity.\n *\n * @param licenseToken - License token whose telemetry claim identifies sends.\n */\n setLicenseToken(licenseToken: string) {\n this.setTelemetryIdentity({ licenseToken });\n }\n\n /**\n * Create an immutable capture scope for one runtime.\n *\n * The scope shares this client's sinks, process-wide opt-out, global\n * properties, and sampling settings, but snapshots transport identity and\n * license-derived sampling authority. Constructing another runtime cannot\n * rewrite an existing scope.\n *\n * @param identity - The runtime's construction-time telemetry identity.\n * @returns A capture-only client bound to that identity.\n */\n createScope(identity: TelemetryIdentity): TelemetryCapture {\n const resolvedIdentity = this.resolveTelemetryIdentity(identity);\n\n return {\n capture: <K extends keyof AnalyticsEvents>(\n event: K,\n properties: AnalyticsEvents[K],\n ) => this.captureWithIdentity(event, properties, resolvedIdentity),\n };\n }\n\n private resolveTelemetryIdentity(\n identity: TelemetryIdentity,\n ): ResolvedTelemetryIdentity {\n const telemetryId = firstNonBlankTelemetryId(identity.telemetryId);\n if (telemetryId !== undefined) {\n return {\n telemetryId,\n licenseToken: null,\n licenseTelemetryId: null,\n };\n }\n\n return {\n telemetryId: null,\n licenseToken: identity.licenseToken ?? null,\n licenseTelemetryId: identity.licenseToken\n ? parseAndWarnTelemetryId(identity.licenseToken)\n : null,\n };\n }\n\n private setSampleRate(sampleRate: number | undefined) {\n let _sampleRate: number;\n\n _sampleRate = sampleRate ?? 0.05;\n\n // eslint-disable-next-line\n if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) {\n // eslint-disable-next-line\n _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);\n }\n\n // Number.isNaN guards against parseFloat(\"nonsense\") slipping past the\n // range check (all NaN comparisons are false), which would silently\n // drop every anonymous event with no signal — especially important\n // since the default is now 0.05, making env-var overrides more common.\n if (Number.isNaN(_sampleRate) || _sampleRate < 0 || _sampleRate > 1) {\n throw new Error(\"Sample rate must be between 0 and 1\");\n }\n\n this.sampleRate = _sampleRate;\n // Per-event sampling metadata (sampleRate/sampleRateAdjustmentFactor/\n // sampleWeight) is computed per capture() in ./sampling. Only license-\n // authorized events get effectiveSampleRate=1; standalone transport\n // identity stays in the sampled population.\n }\n}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IAAI,cAAc,KAAK,cAAc,EAChE,OAAM,IAAI,MAAM,sCAAsC;AAGxD,OAAK,aAAa"}
@@ -0,0 +1,20 @@
1
+
2
+ //#region src/telemetry/telemetry-disabled.ts
3
+ /**
4
+ * Checks if telemetry is disabled via environment variables.
5
+ * Users can opt out by setting:
6
+ * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
7
+ * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
8
+ *
9
+ * Lives in its own module so that the browser-facing root entry can
10
+ * re-export it without pulling in `telemetry-client.ts`, whose
11
+ * `@segment/analytics-node` import drags Node built-ins into browser
12
+ * bundler module graphs. See the note in `../index.ts`.
13
+ */
14
+ function isTelemetryDisabled() {
15
+ return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
16
+ }
17
+
18
+ //#endregion
19
+ exports.isTelemetryDisabled = isTelemetryDisabled;
20
+ //# sourceMappingURL=telemetry-disabled.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-disabled.cjs","names":[],"sources":["../../src/telemetry/telemetry-disabled.ts"],"sourcesContent":["/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n *\n * Lives in its own module so that the browser-facing root entry can\n * re-export it without pulling in `telemetry-client.ts`, whose\n * `@segment/analytics-node` import drags Node built-ins into browser\n * bundler module graphs. See the note in `../index.ts`.\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK ===\n \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAgB,sBAA+B;AAC7C,QACG,QAAQ,IACN,kCAAkC,UACpC,QAAQ,IACN,kCAAkC,OACpC,QAAQ,IAA2C,iBAClD,UACD,QAAQ,IAA2C,iBAAiB"}
@@ -0,0 +1,16 @@
1
+ //#region src/telemetry/telemetry-disabled.d.ts
2
+ /**
3
+ * Checks if telemetry is disabled via environment variables.
4
+ * Users can opt out by setting:
5
+ * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
6
+ * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
7
+ *
8
+ * Lives in its own module so that the browser-facing root entry can
9
+ * re-export it without pulling in `telemetry-client.ts`, whose
10
+ * `@segment/analytics-node` import drags Node built-ins into browser
11
+ * bundler module graphs. See the note in `../index.ts`.
12
+ */
13
+ declare function isTelemetryDisabled(): boolean;
14
+ //#endregion
15
+ export { isTelemetryDisabled };
16
+ //# sourceMappingURL=telemetry-disabled.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-disabled.d.cts","names":[],"sources":["../../src/telemetry/telemetry-disabled.ts"],"mappings":";;AAWA;;;;;;;;;;iBAAgB,mBAAA,CAAA"}
@@ -0,0 +1,16 @@
1
+ //#region src/telemetry/telemetry-disabled.d.ts
2
+ /**
3
+ * Checks if telemetry is disabled via environment variables.
4
+ * Users can opt out by setting:
5
+ * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
6
+ * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
7
+ *
8
+ * Lives in its own module so that the browser-facing root entry can
9
+ * re-export it without pulling in `telemetry-client.ts`, whose
10
+ * `@segment/analytics-node` import drags Node built-ins into browser
11
+ * bundler module graphs. See the note in `../index.ts`.
12
+ */
13
+ declare function isTelemetryDisabled(): boolean;
14
+ //#endregion
15
+ export { isTelemetryDisabled };
16
+ //# sourceMappingURL=telemetry-disabled.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-disabled.d.mts","names":[],"sources":["../../src/telemetry/telemetry-disabled.ts"],"mappings":";;AAWA;;;;;;;;;;iBAAgB,mBAAA,CAAA"}
@@ -0,0 +1,19 @@
1
+ //#region src/telemetry/telemetry-disabled.ts
2
+ /**
3
+ * Checks if telemetry is disabled via environment variables.
4
+ * Users can opt out by setting:
5
+ * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
6
+ * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
7
+ *
8
+ * Lives in its own module so that the browser-facing root entry can
9
+ * re-export it without pulling in `telemetry-client.ts`, whose
10
+ * `@segment/analytics-node` import drags Node built-ins into browser
11
+ * bundler module graphs. See the note in `../index.ts`.
12
+ */
13
+ function isTelemetryDisabled() {
14
+ return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
15
+ }
16
+
17
+ //#endregion
18
+ export { isTelemetryDisabled };
19
+ //# sourceMappingURL=telemetry-disabled.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry-disabled.mjs","names":[],"sources":["../../src/telemetry/telemetry-disabled.ts"],"sourcesContent":["/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n *\n * Lives in its own module so that the browser-facing root entry can\n * re-export it without pulling in `telemetry-client.ts`, whose\n * `@segment/analytics-node` import drags Node built-ins into browser\n * bundler module graphs. See the note in `../index.ts`.\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK ===\n \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,sBAA+B;AAC7C,QACG,QAAQ,IACN,kCAAkC,UACpC,QAAQ,IACN,kCAAkC,OACpC,QAAQ,IAA2C,iBAClD,UACD,QAAQ,IAA2C,iBAAiB"}
@@ -5,6 +5,7 @@ const require_console_styling = require('./console-styling.cjs');
5
5
  const require_errors = require('./errors.cjs');
6
6
  const require_json_schema = require('./json-schema.cjs');
7
7
  const require_inspector_metadata = require('./inspector-metadata.cjs');
8
+ const require_inspector_learning = require('./inspector-learning.cjs');
8
9
  const require_inspector_visibility = require('./inspector-visibility.cjs');
9
10
  const require_types = require('./types.cjs');
10
11
  const require_random_id = require('./random-id.cjs');
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["PartialJSON"],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\nexport * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;;;;;AAQzC,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAASA,aAAY,MAAM,KAAK;AACtC,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
1
+ {"version":3,"file":"index.cjs","names":["PartialJSON"],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\nexport * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-learning\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;;;;;AAQzC,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAASA,aAAY,MAAM,KAAK;AACtC,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
@@ -4,8 +4,9 @@ import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled,
4
4
  import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.cjs";
5
5
  import { JSONSchema, JSONSchemaArray, JSONSchemaBoolean, JSONSchemaNumber, JSONSchemaObject, JSONSchemaString, actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.cjs";
6
6
  import { InspectorMetadataV1, parseInspectorMetadataV1 } from "./inspector-metadata.cjs";
7
+ import { InspectorLearningEvidence, InspectorLearningInsight, InspectorLearningPage, InspectorLearningRequestV1, InspectorLearningSkill, InspectorLearningSnapshotV1, parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.cjs";
7
8
  import { InspectorVisibilityOptions, shouldEnableInspector } from "./inspector-visibility.cjs";
8
- import { A2UIRuntimeInfo, AgentDescription, IntelligenceRuntimeInfo, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeMode, ThreadEndpointRuntimeInfo } from "./types.cjs";
9
+ import { A2UIRuntimeInfo, AgentDescription, IntelligenceRuntimeInfo, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeMode, SingleRouteRuntimeInfo, ThreadEndpointRuntimeInfo } from "./types.cjs";
9
10
  import { dataToUUID, isValidUUID, randomId, randomUUID } from "./random-id.cjs";
10
11
  import { readBody } from "./requests.cjs";
11
12
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;AAmBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAYxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;;AAoBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAYxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
@@ -4,8 +4,9 @@ import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled,
4
4
  import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.mjs";
5
5
  import { JSONSchema, JSONSchemaArray, JSONSchemaBoolean, JSONSchemaNumber, JSONSchemaObject, JSONSchemaString, actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.mjs";
6
6
  import { InspectorMetadataV1, parseInspectorMetadataV1 } from "./inspector-metadata.mjs";
7
+ import { InspectorLearningEvidence, InspectorLearningInsight, InspectorLearningPage, InspectorLearningRequestV1, InspectorLearningSkill, InspectorLearningSnapshotV1, parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.mjs";
7
8
  import { InspectorVisibilityOptions, shouldEnableInspector } from "./inspector-visibility.mjs";
8
- import { A2UIRuntimeInfo, AgentDescription, IntelligenceRuntimeInfo, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeMode, ThreadEndpointRuntimeInfo } from "./types.mjs";
9
+ import { A2UIRuntimeInfo, AgentDescription, IntelligenceRuntimeInfo, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeMode, SingleRouteRuntimeInfo, ThreadEndpointRuntimeInfo } from "./types.mjs";
9
10
  import { dataToUUID, isValidUUID, randomId, randomUUID } from "./random-id.mjs";
10
11
  import { readBody } from "./requests.mjs";
11
12
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;AAmBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAYxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;;AAoBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAYxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
@@ -4,6 +4,7 @@ import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled,
4
4
  import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.mjs";
5
5
  import { actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.mjs";
6
6
  import { parseInspectorMetadataV1 } from "./inspector-metadata.mjs";
7
+ import { parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.mjs";
7
8
  import { shouldEnableInspector } from "./inspector-visibility.mjs";
8
9
  import { RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE } from "./types.mjs";
9
10
  import { dataToUUID, isValidUUID, randomId, randomUUID } from "./random-id.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\nexport * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;;;;;AAQzC,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAAS,YAAY,MAAM,KAAK;AACtC,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\nexport * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-learning\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;;;;;AAQzC,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAAS,YAAY,MAAM,KAAK;AACtC,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}