@osfactory/otel-hook 0.13.2 → 0.14.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 (37) hide show
  1. package/README.md +43 -0
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +427 -37
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +30 -4
  6. package/dist/config.js +161 -9
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C4sSKjDO.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-BjRXDots.d.ts → export-destinations-DvoH4QOe.d.ts} +101 -9
  10. package/dist/{hook-CKLpgrYP.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +424 -36
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/integration.d.ts +7 -7
  16. package/dist/integration.js +376 -34
  17. package/dist/integration.js.map +1 -1
  18. package/dist/lifecycle.js +1 -1
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{payload-DLK7QaBB.d.ts → payload-D4r71EL-.d.ts} +1 -1
  21. package/dist/privacy.d.ts +2 -2
  22. package/dist/privacy.js +42 -1
  23. package/dist/privacy.js.map +1 -1
  24. package/dist/providers.d.ts +8 -8
  25. package/dist/{registry-DM-4YvIA.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  26. package/dist/runtime.d.ts +5 -5
  27. package/dist/runtime.js +128 -2
  28. package/dist/runtime.js.map +1 -1
  29. package/dist/{schema-CD61uW99.d.ts → schema-oRsbo7WO.d.ts} +45 -0
  30. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  31. package/dist/telemetry.d.ts +5 -4
  32. package/dist/telemetry.js +285 -15
  33. package/dist/telemetry.js.map +1 -1
  34. package/dist/testing.d.ts +5 -5
  35. package/dist/testing.js +128 -2
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1653,6 +1653,62 @@ import { z as z8 } from "zod";
1653
1653
 
1654
1654
  // src/config/destinations.ts
1655
1655
  import { z as z6 } from "zod";
1656
+
1657
+ // src/config/repository-key.ts
1658
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
1659
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
1660
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
1661
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
1662
+ var trimTrailingSlashes = (value) => {
1663
+ let end = value.length;
1664
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1665
+ return value.slice(0, end);
1666
+ };
1667
+ var keyOf = (host, pathname) => {
1668
+ const withoutSlashes = trimTrailingSlashes(pathname);
1669
+ const cleanedPath = trimTrailingSlashes(
1670
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
1671
+ );
1672
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
1673
+ return void 0;
1674
+ }
1675
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
1676
+ return `${host}${withSlash}`.toLowerCase();
1677
+ };
1678
+ var normalizeRepositoryKey = (reference) => {
1679
+ const trimmed = reference.trim();
1680
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
1681
+ return void 0;
1682
+ }
1683
+ if (SCHEME_PATTERN.test(trimmed)) {
1684
+ let url;
1685
+ try {
1686
+ url = new URL(trimmed);
1687
+ } catch {
1688
+ return void 0;
1689
+ }
1690
+ if (url.protocol === "file:") {
1691
+ return void 0;
1692
+ }
1693
+ return keyOf(url.hostname, url.pathname);
1694
+ }
1695
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
1696
+ return void 0;
1697
+ }
1698
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
1699
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
1700
+ const [, host, pathPart] = scp;
1701
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
1702
+ }
1703
+ try {
1704
+ const url = new URL(`https://${trimmed}`);
1705
+ return keyOf(url.hostname, url.pathname);
1706
+ } catch {
1707
+ return void 0;
1708
+ }
1709
+ };
1710
+
1711
+ // src/config/destinations.ts
1656
1712
  var DEFAULT_DESTINATION_NAME = "default";
1657
1713
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1658
1714
  var MAX_EXPORT_DESTINATIONS = 16;
@@ -1670,6 +1726,30 @@ var headerValueSchema = z6.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1670
1726
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1671
1727
  );
1672
1728
  var endpointSchema = z6.string().url().max(2048);
1729
+ var MAX_DESTINATION_SCOPES = 64;
1730
+ var MAX_SCOPE_REPOSITORIES = 256;
1731
+ var ALL_REPOSITORIES = "*";
1732
+ var repositoryReferenceSchema = z6.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
1733
+ (value) => normalizeRepositoryKey(value) !== void 0,
1734
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
1735
+ );
1736
+ var destinationScopeSchema = z6.strictObject({
1737
+ /**
1738
+ * Repository URLs (any spelling of the remote; compared by host and path,
1739
+ * case-insensitively, without `.git`), or `"*"` for every record that names
1740
+ * a repository. A record that names none never matches a scope.
1741
+ */
1742
+ repositories: z6.union([
1743
+ z6.literal(ALL_REPOSITORIES),
1744
+ z6.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
1745
+ ]),
1746
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
1747
+ signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1748
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
1749
+ contentMode: contentModeSchema.optional(),
1750
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
1751
+ includeSessionId: z6.boolean().optional()
1752
+ });
1673
1753
  var exportDestinationSchema = z6.strictObject({
1674
1754
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1675
1755
  name: z6.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -1703,7 +1783,15 @@ var exportDestinationSchema = z6.strictObject({
1703
1783
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
1704
1784
  * default: a destination receives hook-derived metrics only when it lists them.
1705
1785
  */
1706
- signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional()
1786
+ signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1787
+ /**
1788
+ * Per-repository filter. Absent: every record goes to this destination, as
1789
+ * before scopes existed. Present: a record goes only when its repository
1790
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
1791
+ * decides its signals, content mode, and session id — and a record that
1792
+ * names no repository is not sent here at all.
1793
+ */
1794
+ scopes: z6.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
1707
1795
  }).refine(
1708
1796
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1709
1797
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -1747,6 +1835,32 @@ var effectiveSpoolPolicy = (exporter) => ({
1747
1835
  maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1748
1836
  maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1749
1837
  });
1838
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
1839
+ const listed = scope.signals ?? exportSignalSchema.options;
1840
+ return {
1841
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
1842
+ scope.repositories.flatMap((reference) => {
1843
+ const key = normalizeRepositoryKey(reference);
1844
+ return key === void 0 ? [] : [key];
1845
+ })
1846
+ ),
1847
+ signals: {
1848
+ traces: destinationSignals.traces && listed.includes("traces"),
1849
+ logs: destinationSignals.logs && listed.includes("logs"),
1850
+ metrics: destinationSignals.metrics && listed.includes("metrics")
1851
+ },
1852
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
1853
+ includeSessionId: scope.includeSessionId ?? true
1854
+ };
1855
+ });
1856
+ var matchDestinationScope = (scopes, repositoryKey) => {
1857
+ if (repositoryKey === void 0) {
1858
+ return void 0;
1859
+ }
1860
+ return scopes.find(
1861
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
1862
+ );
1863
+ };
1750
1864
  var legacyDestination = (exporter) => ({
1751
1865
  name: DEFAULT_DESTINATION_NAME,
1752
1866
  source: "exporter",
@@ -1771,6 +1885,11 @@ var resolveExportDestinations = (exporter) => {
1771
1885
  continue;
1772
1886
  }
1773
1887
  const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
1888
+ const flags = {
1889
+ traces: signals.includes("traces"),
1890
+ logs: exporter.logs.enabled && signals.includes("logs"),
1891
+ metrics: signals.includes("metrics")
1892
+ };
1774
1893
  resolved.push({
1775
1894
  name: destination.name,
1776
1895
  source: "destinations",
@@ -1779,12 +1898,9 @@ var resolveExportDestinations = (exporter) => {
1779
1898
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1780
1899
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1781
1900
  ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1782
- signals: {
1783
- traces: signals.includes("traces"),
1784
- logs: exporter.logs.enabled && signals.includes("logs"),
1785
- metrics: signals.includes("metrics")
1786
- },
1787
- headers: { ...destination.headers ?? {} }
1901
+ signals: flags,
1902
+ headers: { ...destination.headers ?? {} },
1903
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
1788
1904
  });
1789
1905
  }
1790
1906
  return resolved;
@@ -1808,6 +1924,12 @@ var resolveDestinationHeaders = (headers, environment) => {
1808
1924
  }
1809
1925
  return { values, missingVariables: [...new Set(missing)].sort() };
1810
1926
  };
1927
+ var describeScope = (scope) => ({
1928
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : [...scope.repositories].sort(),
1929
+ signals: exportSignalSchema.options.filter((signal) => scope.signals[signal]),
1930
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
1931
+ includeSessionId: scope.includeSessionId
1932
+ });
1811
1933
  var endpointOrigin = (endpoint) => {
1812
1934
  if (endpoint === void 0) {
1813
1935
  return void 0;
@@ -1837,7 +1959,8 @@ var describeExportDestinations = (exporter) => {
1837
1959
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1838
1960
  ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
1839
1961
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1840
- headerVariables: [...new Set(variables)].sort()
1962
+ headerVariables: [...new Set(variables)].sort(),
1963
+ ...destination.scopes === void 0 ? {} : { scopes: destination.scopes.map(describeScope) }
1841
1964
  };
1842
1965
  };
1843
1966
  const enabled = resolveExportDestinations(exporter).map(
@@ -1851,7 +1974,14 @@ var describeExportDestinations = (exporter) => {
1851
1974
  protocol: destination.protocol ?? exporter.protocol,
1852
1975
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1853
1976
  signals: { traces: false, logs: false, metrics: false },
1854
- headers: { ...destination.headers ?? {} }
1977
+ headers: { ...destination.headers ?? {} },
1978
+ ...destination.scopes === void 0 ? {} : {
1979
+ scopes: resolveDestinationScopes(destination.scopes, {
1980
+ traces: true,
1981
+ logs: true,
1982
+ metrics: true
1983
+ })
1984
+ }
1855
1985
  },
1856
1986
  false
1857
1987
  )
@@ -2159,6 +2289,18 @@ var resolveConfig = (layers = []) => {
2159
2289
  );
2160
2290
  }
2161
2291
  }
2292
+ const rank = { omit: 0, mask: 1, redact: 2, raw: 3 };
2293
+ const effectiveMode = parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent ? "omit" : parsed.data.privacy.contentMode;
2294
+ const widening = enabled.filter(
2295
+ (destination) => (destination.scopes ?? []).some(
2296
+ (scope) => scope.contentMode !== void 0 && rank[scope.contentMode] > rank[effectiveMode]
2297
+ )
2298
+ ).map((destination) => destination.name);
2299
+ if (widening.length > 0) {
2300
+ notes.push(
2301
+ `destination(s) ${widening.join(", ")} have a scope contentMode above privacy.contentMode=${effectiveMode}; a scope can only lower disclosure, so ${effectiveMode} applies`
2302
+ );
2303
+ }
2162
2304
  }
2163
2305
  if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2164
2306
  notes.push(
@@ -2206,6 +2348,9 @@ var describeDestinationAttributes = (config) => {
2206
2348
  }
2207
2349
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2208
2350
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2351
+ if (destination.scopes !== void 0) {
2352
+ attributes[`${prefix}.scope_count`] = destination.scopes.length;
2353
+ }
2209
2354
  }
2210
2355
  return attributes;
2211
2356
  };
@@ -3309,6 +3454,23 @@ var summarizeHealth = (snapshots) => ({
3309
3454
 
3310
3455
  // src/privacy/service.ts
3311
3456
  import { createHash } from "crypto";
3457
+ var DISCLOSURE_RANK = Object.freeze({
3458
+ omitted: 0,
3459
+ masked: 1,
3460
+ redacted: 2,
3461
+ raw: 3
3462
+ });
3463
+ var WHITESPACE = /\s/u;
3464
+ var withoutTrailingToken = (text) => {
3465
+ let end = text.length;
3466
+ while (end > 0) {
3467
+ const low = text.charCodeAt(end - 1);
3468
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
3469
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
3470
+ end -= width;
3471
+ }
3472
+ return text.slice(0, end);
3473
+ };
3312
3474
  var compilePatterns = (sources, flags) => {
3313
3475
  const compiled = [];
3314
3476
  for (const source of sources) {
@@ -3646,7 +3808,31 @@ var createPrivacyService = (policyInput) => {
3646
3808
  flattenToAttributes,
3647
3809
  sanitizeAttributes,
3648
3810
  sanitizeExtensions,
3649
- boundString
3811
+ boundString,
3812
+ restrictContent: (fact, mode) => {
3813
+ const target = CONTENT_MODE_DISCLOSURE[mode];
3814
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
3815
+ return fact;
3816
+ }
3817
+ const { text, ...rest } = fact;
3818
+ switch (target) {
3819
+ case "omitted":
3820
+ return { ...rest, disclosure: "omitted", truncated: false };
3821
+ case "masked":
3822
+ return { ...rest, disclosure: "masked", text: maskText(text) };
3823
+ case "redacted": {
3824
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
3825
+ return {
3826
+ ...rest,
3827
+ disclosure: "redacted",
3828
+ text: redacted.text,
3829
+ secretsRedacted: fact.secretsRedacted + redacted.count
3830
+ };
3831
+ }
3832
+ case "raw":
3833
+ return fact;
3834
+ }
3835
+ }
3650
3836
  };
3651
3837
  };
3652
3838
 
@@ -9149,7 +9335,7 @@ import {
9149
9335
  } from "@opentelemetry/semantic-conventions/incubating";
9150
9336
 
9151
9337
  // src/version.ts
9152
- var VERSION = "0.13.2";
9338
+ var VERSION = "0.14.0";
9153
9339
 
9154
9340
  // src/telemetry/semconv.ts
9155
9341
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -9632,6 +9818,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
9632
9818
  };
9633
9819
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9634
9820
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9821
+ var spanEndEdgesOf = (events) => {
9822
+ const layout = layoutBatch(events);
9823
+ const ends = /* @__PURE__ */ new Map();
9824
+ for (const [eventId, groupKey] of layout.groupOf) {
9825
+ const end = layout.groups.get(groupKey)?.end;
9826
+ if (end !== void 0) {
9827
+ ends.set(eventId, end);
9828
+ }
9829
+ }
9830
+ return ends;
9831
+ };
9635
9832
  var canonicalEventTraceIdentities = (events, options = {}) => {
9636
9833
  const layout = layoutBatch(events);
9637
9834
  const correlations = indexCorrelations(options.correlations);
@@ -11173,6 +11370,101 @@ var createOtlpMetricSink = (options) => {
11173
11370
  };
11174
11371
  };
11175
11372
 
11373
+ // src/telemetry/destination-scope.ts
11374
+ var DISCLOSURE_RANK2 = Object.freeze({
11375
+ omitted: 0,
11376
+ masked: 1,
11377
+ redacted: 2,
11378
+ raw: 3
11379
+ });
11380
+ var omitRestrictedContent = (fact, mode) => {
11381
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
11382
+ return fact;
11383
+ }
11384
+ const { text, ...rest } = fact;
11385
+ void text;
11386
+ return { ...rest, disclosure: "omitted", truncated: false };
11387
+ };
11388
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
11389
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
11390
+ var eventRepositoryKey = (event3, fallbackKey) => {
11391
+ const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
11392
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
11393
+ };
11394
+ var pointRepositoryKey = (point, fallbackKey) => {
11395
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
11396
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
11397
+ };
11398
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
11399
+ var restrictEventContent = (event3, mode, restrict) => {
11400
+ switch (event3.type) {
11401
+ case "prompt.submitted":
11402
+ return event3.content === void 0 ? event3 : { ...event3, content: restrict(event3.content, mode) };
11403
+ case "generation.start": {
11404
+ const inputContent = restrictFacts(event3.inputContent, mode, restrict);
11405
+ return inputContent === void 0 ? event3 : { ...event3, inputContent };
11406
+ }
11407
+ case "generation.end": {
11408
+ const outputContent = restrictFacts(event3.outputContent, mode, restrict);
11409
+ return outputContent === void 0 ? event3 : { ...event3, outputContent };
11410
+ }
11411
+ case "tool.start":
11412
+ return event3.input === void 0 ? event3 : { ...event3, input: restrict(event3.input, mode) };
11413
+ case "tool.end":
11414
+ return event3.output === void 0 ? event3 : { ...event3, output: restrict(event3.output, mode) };
11415
+ case "error.raised":
11416
+ return event3.message === void 0 ? event3 : { ...event3, message: restrict(event3.message, mode) };
11417
+ default:
11418
+ return event3;
11419
+ }
11420
+ };
11421
+ var routeEventsToScopes = (events, scopes, options) => {
11422
+ const ends = spanEndEdgesOf(events);
11423
+ const traces = [];
11424
+ const logs = [];
11425
+ let unchanged = true;
11426
+ for (const event3 of events) {
11427
+ const anchor = ends.get(event3.eventId) ?? event3;
11428
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
11429
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
11430
+ unchanged = false;
11431
+ }
11432
+ if (scope === void 0) {
11433
+ continue;
11434
+ }
11435
+ const restricted = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
11436
+ if (restricted !== event3) {
11437
+ unchanged = false;
11438
+ }
11439
+ if (scope.signals.traces) {
11440
+ traces.push(restricted);
11441
+ }
11442
+ if (scope.signals.logs) {
11443
+ logs.push(restricted);
11444
+ }
11445
+ }
11446
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
11447
+ };
11448
+ var routePointsToScopes = (scopes, pointsFor, options) => {
11449
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
11450
+ const kept = [];
11451
+ for (const variant of [true, false]) {
11452
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
11453
+ continue;
11454
+ }
11455
+ for (const point of pointsFor(variant) ?? []) {
11456
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
11457
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
11458
+ kept.push(point);
11459
+ }
11460
+ }
11461
+ }
11462
+ return kept;
11463
+ };
11464
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
11465
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
11466
+ );
11467
+
11176
11468
  // src/telemetry/signal-fanout.ts
11177
11469
  var createSignalFanout = (options) => {
11178
11470
  const emit = async (events) => {
@@ -11205,14 +11497,20 @@ var createSignalFanout = (options) => {
11205
11497
  };
11206
11498
  var shareCorrelationPerBatch = (correlate) => {
11207
11499
  let pending;
11208
- return (events) => {
11209
- if (pending?.events === events) {
11500
+ const resolve8 = (events) => {
11501
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
11210
11502
  return pending.result;
11211
11503
  }
11212
11504
  const result = correlate(events);
11213
- pending = { events, result };
11505
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
11214
11506
  return result;
11215
11507
  };
11508
+ const alias = (subset, batch) => {
11509
+ if (pending?.events === batch && subset !== batch) {
11510
+ pending.aliases.add(subset);
11511
+ }
11512
+ };
11513
+ return Object.assign(resolve8, { alias });
11216
11514
  };
11217
11515
 
11218
11516
  // src/telemetry/export-destinations.ts
@@ -11281,6 +11579,8 @@ var createExportDestinationSinks = (options) => {
11281
11579
  ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
11282
11580
  probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
11283
11581
  });
11582
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
11583
+ const restrict = options.restrictContent ?? omitRestrictedContent;
11284
11584
  for (const destination of resolveExportDestinations(options.exporter)) {
11285
11585
  let headers;
11286
11586
  let logHeaders;
@@ -11370,17 +11670,51 @@ var createExportDestinationSinks = (options) => {
11370
11670
  metrics,
11371
11671
  ...spool === void 0 ? {} : { spool },
11372
11672
  ...logSpool === void 0 ? {} : { logSpool },
11373
- ...metricSpool === void 0 ? {} : { metricSpool }
11673
+ ...metricSpool === void 0 ? {} : { metricSpool },
11674
+ ...destination.scopes === void 0 ? {} : {
11675
+ scopes: destination.scopes,
11676
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
11677
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
11678
+ restrict
11679
+ })
11680
+ }
11374
11681
  });
11375
11682
  }
11376
11683
  return { destinations, skipped };
11377
11684
  };
11378
- var createDestinationFanout = (destinations) => {
11685
+ var createScopedFanout = (destination, correlate) => {
11686
+ const route = destination.route;
11687
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
11688
+ if (route === void 0) {
11689
+ return unscoped;
11690
+ }
11691
+ const none2 = { accepted: 0, rejected: 0, errors: [] };
11692
+ return {
11693
+ ...unscoped,
11694
+ emit: async (events) => {
11695
+ const batch = route(events);
11696
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
11697
+ await correlate(events);
11698
+ correlate.alias(batch.traces, events);
11699
+ correlate.alias(batch.logs, events);
11700
+ }
11701
+ const traces = batch.traces.length === 0 ? none2 : await destination.traces.emit(batch.traces);
11702
+ const logs = batch.logs.length === 0 ? none2 : await destination.logs.emit(batch.logs);
11703
+ return {
11704
+ accepted: traces.accepted + logs.accepted,
11705
+ rejected: traces.rejected + logs.rejected,
11706
+ errors: [...traces.errors, ...logs.errors]
11707
+ };
11708
+ }
11709
+ };
11710
+ };
11711
+ var createDestinationFanout = (destinations, options = {}) => {
11379
11712
  const fanouts = destinations.map((destination) => ({
11380
11713
  name: destination.name,
11381
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
11714
+ sink: createScopedFanout(destination, options.correlate)
11382
11715
  }));
11383
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
11716
+ const scoped = destinations.some((destination) => destination.route !== void 0);
11717
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
11384
11718
  if (only !== void 0) {
11385
11719
  return only.sink;
11386
11720
  }
@@ -11610,8 +11944,25 @@ var describeDestinationLine = (destination) => {
11610
11944
  );
11611
11945
  }
11612
11946
  }
11613
- return `${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`;
11947
+ if (destination.scopes === void 0) {
11948
+ if (destination.enabled) {
11949
+ parts.push("all repositories");
11950
+ }
11951
+ } else {
11952
+ parts.push(`scoped (${String(destination.scopes.length)} scope(s); records without a repository are not sent)`);
11953
+ }
11954
+ const lines = [`${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`];
11955
+ for (const [index, scope] of (destination.scopes ?? []).entries()) {
11956
+ lines.push(` scope ${String(index + 1)}: ${describeScopeLine(scope)}`);
11957
+ }
11958
+ return lines.join("\n");
11614
11959
  };
11960
+ var describeScopeLine = (scope) => [
11961
+ scope.repositories === "*" ? "every repository" : scope.repositories.join(", "),
11962
+ scope.signals.length === 0 ? "no signals" : scope.signals.join("+"),
11963
+ `content ${scope.contentMode ?? "as configured"}`,
11964
+ scope.includeSessionId ? "session.id on metrics" : "no session.id on metrics"
11965
+ ].join("; ");
11615
11966
  var sumSpoolStats = (all) => {
11616
11967
  const oldest = all.map((stats) => stats.oldestEnqueuedAt).filter((value) => value !== void 0);
11617
11968
  const lastDropped = all.map((stats) => stats.dropped.lastDroppedAt).filter((value) => value !== void 0);
@@ -16286,7 +16637,8 @@ var createHookRuntime = (options) => {
16286
16637
  // has always been governed by.
16287
16638
  allowRawContent: privacy.policy.allowRawContent
16288
16639
  },
16289
- correlate
16640
+ correlate,
16641
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
16290
16642
  });
16291
16643
  const primary = exportDestinations.destinations[0];
16292
16644
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -16303,7 +16655,7 @@ var createHookRuntime = (options) => {
16303
16655
  });
16304
16656
  const spool = primary?.spool;
16305
16657
  const logSpool = primary?.logSpool;
16306
- const sink = createDestinationFanout(exportDestinations.destinations);
16658
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
16307
16659
  const hookDeps = {
16308
16660
  stateStore,
16309
16661
  config: options.config,
@@ -16344,6 +16696,8 @@ var createHookRuntime = (options) => {
16344
16696
  (destination) => destination.metrics.enabled
16345
16697
  );
16346
16698
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
16699
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
16700
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
16347
16701
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
16348
16702
  if (deliveryRetentionMillis < staleClaimMillis) {
16349
16703
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -16409,28 +16763,63 @@ var createHookRuntime = (options) => {
16409
16763
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
16410
16764
  }
16411
16765
  }
16412
- const observations = deriveMetricObservations({
16413
- events: ingest.events,
16414
- usage: ingest.usageObservations,
16415
- resource: metricResource,
16416
- includeSessionId: metricsPolicy.includeSessionId,
16417
- ...generationStarts === void 0 ? {} : { generationStarts },
16418
- turnStart: (sessionId) => turnStarts.get(sessionId)
16419
- });
16420
- if (observations.length === 0) {
16766
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
16767
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
16768
+ const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
16769
+ (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
16770
+ ...event3,
16771
+ contextAttributes: {
16772
+ ...event3.contextAttributes,
16773
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
16774
+ }
16775
+ } : event3
16776
+ );
16777
+ const pointsByVariant = /* @__PURE__ */ new Map();
16778
+ const variants = new Set(
16779
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
16780
+ );
16781
+ for (const destination of scopedMetricDestinations) {
16782
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
16783
+ variants.add(variant);
16784
+ }
16785
+ }
16786
+ for (const includeSessionId of variants) {
16787
+ const observations = deriveMetricObservations({
16788
+ events: metricEvents,
16789
+ usage: ingest.usageObservations,
16790
+ resource: metricResource,
16791
+ includeSessionId,
16792
+ ...generationStarts === void 0 ? {} : { generationStarts },
16793
+ turnStart: (sessionId) => turnStarts.get(sessionId)
16794
+ });
16795
+ if (observations.length === 0) {
16796
+ continue;
16797
+ }
16798
+ pointsByVariant.set(
16799
+ includeSessionId,
16800
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
16801
+ perSession: includeSessionId,
16802
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
16803
+ })
16804
+ );
16805
+ }
16806
+ if (pointsByVariant.size === 0) {
16421
16807
  return void 0;
16422
16808
  }
16423
- const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
16424
- perSession: metricsPolicy.includeSessionId,
16425
- ...deliveryToken === void 0 ? {} : { deliveryToken }
16426
- });
16427
16809
  const context = agreedContextAttributes(ingest.events);
16428
16810
  const results = await Promise.all(
16429
16811
  metricDestinations.map(async (destination) => {
16430
- const result = await destination.metrics.exportPoints(points, context).catch(
16812
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
16813
+ fallbackKey: scopedRepositoryFallback,
16814
+ includeSessionId: metricsPolicy.includeSessionId
16815
+ });
16816
+ if (points2.length === 0) {
16817
+ return { name: destination.name, accepted: 0, rejected: 0 };
16818
+ }
16819
+ const result = await destination.metrics.exportPoints(points2, context).catch(
16431
16820
  (thrown) => ({
16432
16821
  accepted: 0,
16433
- rejected: points.length,
16822
+ rejected: points2.length,
16434
16823
  errors: [
16435
16824
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
16436
16825
  ]
@@ -16440,7 +16829,8 @@ var createHookRuntime = (options) => {
16440
16829
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
16441
16830
  })
16442
16831
  );
16443
- return { points: points.length, destinations: results };
16832
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
16833
+ return { points, destinations: results };
16444
16834
  } catch (thrown) {
16445
16835
  diagnostics.push(stateDiagnostic(thrown));
16446
16836
  logger.warn("hook-derived metrics could not be recorded for this callback", {});