@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/index.js CHANGED
@@ -1143,6 +1143,23 @@ var resolvePrivacyPolicy = (policy) => {
1143
1143
 
1144
1144
  // src/privacy/service.ts
1145
1145
  import { createHash } from "crypto";
1146
+ var DISCLOSURE_RANK = Object.freeze({
1147
+ omitted: 0,
1148
+ masked: 1,
1149
+ redacted: 2,
1150
+ raw: 3
1151
+ });
1152
+ var WHITESPACE = /\s/u;
1153
+ var withoutTrailingToken = (text) => {
1154
+ let end = text.length;
1155
+ while (end > 0) {
1156
+ const low = text.charCodeAt(end - 1);
1157
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
1158
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
1159
+ end -= width;
1160
+ }
1161
+ return text.slice(0, end);
1162
+ };
1146
1163
  var compilePatterns = (sources, flags) => {
1147
1164
  const compiled = [];
1148
1165
  for (const source of sources) {
@@ -1480,7 +1497,31 @@ var createPrivacyService = (policyInput) => {
1480
1497
  flattenToAttributes,
1481
1498
  sanitizeAttributes,
1482
1499
  sanitizeExtensions,
1483
- boundString
1500
+ boundString,
1501
+ restrictContent: (fact, mode) => {
1502
+ const target = CONTENT_MODE_DISCLOSURE[mode];
1503
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
1504
+ return fact;
1505
+ }
1506
+ const { text, ...rest } = fact;
1507
+ switch (target) {
1508
+ case "omitted":
1509
+ return { ...rest, disclosure: "omitted", truncated: false };
1510
+ case "masked":
1511
+ return { ...rest, disclosure: "masked", text: maskText(text) };
1512
+ case "redacted": {
1513
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
1514
+ return {
1515
+ ...rest,
1516
+ disclosure: "redacted",
1517
+ text: redacted.text,
1518
+ secretsRedacted: fact.secretsRedacted + redacted.count
1519
+ };
1520
+ }
1521
+ case "raw":
1522
+ return fact;
1523
+ }
1524
+ }
1484
1525
  };
1485
1526
  };
1486
1527
 
@@ -1820,6 +1861,60 @@ var unionOtlpHeaderNames = (...lists) => {
1820
1861
  };
1821
1862
  var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));
1822
1863
 
1864
+ // src/config/repository-key.ts
1865
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
1866
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
1867
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
1868
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
1869
+ var trimTrailingSlashes = (value) => {
1870
+ let end = value.length;
1871
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1872
+ return value.slice(0, end);
1873
+ };
1874
+ var keyOf = (host, pathname) => {
1875
+ const withoutSlashes = trimTrailingSlashes(pathname);
1876
+ const cleanedPath = trimTrailingSlashes(
1877
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
1878
+ );
1879
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
1880
+ return void 0;
1881
+ }
1882
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
1883
+ return `${host}${withSlash}`.toLowerCase();
1884
+ };
1885
+ var normalizeRepositoryKey = (reference) => {
1886
+ const trimmed = reference.trim();
1887
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
1888
+ return void 0;
1889
+ }
1890
+ if (SCHEME_PATTERN.test(trimmed)) {
1891
+ let url;
1892
+ try {
1893
+ url = new URL(trimmed);
1894
+ } catch {
1895
+ return void 0;
1896
+ }
1897
+ if (url.protocol === "file:") {
1898
+ return void 0;
1899
+ }
1900
+ return keyOf(url.hostname, url.pathname);
1901
+ }
1902
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
1903
+ return void 0;
1904
+ }
1905
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
1906
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
1907
+ const [, host, pathPart] = scp;
1908
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
1909
+ }
1910
+ try {
1911
+ const url = new URL(`https://${trimmed}`);
1912
+ return keyOf(url.hostname, url.pathname);
1913
+ } catch {
1914
+ return void 0;
1915
+ }
1916
+ };
1917
+
1823
1918
  // src/config/destinations.ts
1824
1919
  var DEFAULT_DESTINATION_NAME = "default";
1825
1920
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
@@ -1838,6 +1933,30 @@ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1838
1933
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1839
1934
  );
1840
1935
  var endpointSchema = z13.string().url().max(2048);
1936
+ var MAX_DESTINATION_SCOPES = 64;
1937
+ var MAX_SCOPE_REPOSITORIES = 256;
1938
+ var ALL_REPOSITORIES = "*";
1939
+ var repositoryReferenceSchema = z13.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
1940
+ (value) => normalizeRepositoryKey(value) !== void 0,
1941
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
1942
+ );
1943
+ var destinationScopeSchema = z13.strictObject({
1944
+ /**
1945
+ * Repository URLs (any spelling of the remote; compared by host and path,
1946
+ * case-insensitively, without `.git`), or `"*"` for every record that names
1947
+ * a repository. A record that names none never matches a scope.
1948
+ */
1949
+ repositories: z13.union([
1950
+ z13.literal(ALL_REPOSITORIES),
1951
+ z13.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
1952
+ ]),
1953
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
1954
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1955
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
1956
+ contentMode: contentModeSchema.optional(),
1957
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
1958
+ includeSessionId: z13.boolean().optional()
1959
+ });
1841
1960
  var exportDestinationSchema = z13.strictObject({
1842
1961
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1843
1962
  name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -1871,7 +1990,15 @@ var exportDestinationSchema = z13.strictObject({
1871
1990
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
1872
1991
  * default: a destination receives hook-derived metrics only when it lists them.
1873
1992
  */
1874
- signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1993
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1994
+ /**
1995
+ * Per-repository filter. Absent: every record goes to this destination, as
1996
+ * before scopes existed. Present: a record goes only when its repository
1997
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
1998
+ * decides its signals, content mode, and session id — and a record that
1999
+ * names no repository is not sent here at all.
2000
+ */
2001
+ scopes: z13.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
1875
2002
  }).refine(
1876
2003
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1877
2004
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -1915,6 +2042,32 @@ var effectiveSpoolPolicy = (exporter) => ({
1915
2042
  maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1916
2043
  maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1917
2044
  });
2045
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
2046
+ const listed = scope.signals ?? exportSignalSchema.options;
2047
+ return {
2048
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
2049
+ scope.repositories.flatMap((reference) => {
2050
+ const key = normalizeRepositoryKey(reference);
2051
+ return key === void 0 ? [] : [key];
2052
+ })
2053
+ ),
2054
+ signals: {
2055
+ traces: destinationSignals.traces && listed.includes("traces"),
2056
+ logs: destinationSignals.logs && listed.includes("logs"),
2057
+ metrics: destinationSignals.metrics && listed.includes("metrics")
2058
+ },
2059
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
2060
+ includeSessionId: scope.includeSessionId ?? true
2061
+ };
2062
+ });
2063
+ var matchDestinationScope = (scopes, repositoryKey) => {
2064
+ if (repositoryKey === void 0) {
2065
+ return void 0;
2066
+ }
2067
+ return scopes.find(
2068
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
2069
+ );
2070
+ };
1918
2071
  var legacyDestination = (exporter) => ({
1919
2072
  name: DEFAULT_DESTINATION_NAME,
1920
2073
  source: "exporter",
@@ -1939,6 +2092,11 @@ var resolveExportDestinations = (exporter) => {
1939
2092
  continue;
1940
2093
  }
1941
2094
  const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
2095
+ const flags = {
2096
+ traces: signals.includes("traces"),
2097
+ logs: exporter.logs.enabled && signals.includes("logs"),
2098
+ metrics: signals.includes("metrics")
2099
+ };
1942
2100
  resolved.push({
1943
2101
  name: destination.name,
1944
2102
  source: "destinations",
@@ -1947,12 +2105,9 @@ var resolveExportDestinations = (exporter) => {
1947
2105
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1948
2106
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1949
2107
  ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1950
- signals: {
1951
- traces: signals.includes("traces"),
1952
- logs: exporter.logs.enabled && signals.includes("logs"),
1953
- metrics: signals.includes("metrics")
1954
- },
1955
- headers: { ...destination.headers ?? {} }
2108
+ signals: flags,
2109
+ headers: { ...destination.headers ?? {} },
2110
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
1956
2111
  });
1957
2112
  }
1958
2113
  return resolved;
@@ -1976,6 +2131,12 @@ var resolveDestinationHeaders = (headers, environment) => {
1976
2131
  }
1977
2132
  return { values, missingVariables: [...new Set(missing)].sort() };
1978
2133
  };
2134
+ var describeScope = (scope) => ({
2135
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : [...scope.repositories].sort(),
2136
+ signals: exportSignalSchema.options.filter((signal) => scope.signals[signal]),
2137
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
2138
+ includeSessionId: scope.includeSessionId
2139
+ });
1979
2140
  var endpointOrigin = (endpoint) => {
1980
2141
  if (endpoint === void 0) {
1981
2142
  return void 0;
@@ -2005,7 +2166,8 @@ var describeExportDestinations = (exporter) => {
2005
2166
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
2006
2167
  ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
2007
2168
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
2008
- headerVariables: [...new Set(variables)].sort()
2169
+ headerVariables: [...new Set(variables)].sort(),
2170
+ ...destination.scopes === void 0 ? {} : { scopes: destination.scopes.map(describeScope) }
2009
2171
  };
2010
2172
  };
2011
2173
  const enabled = resolveExportDestinations(exporter).map(
@@ -2019,7 +2181,14 @@ var describeExportDestinations = (exporter) => {
2019
2181
  protocol: destination.protocol ?? exporter.protocol,
2020
2182
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2021
2183
  signals: { traces: false, logs: false, metrics: false },
2022
- headers: { ...destination.headers ?? {} }
2184
+ headers: { ...destination.headers ?? {} },
2185
+ ...destination.scopes === void 0 ? {} : {
2186
+ scopes: resolveDestinationScopes(destination.scopes, {
2187
+ traces: true,
2188
+ logs: true,
2189
+ metrics: true
2190
+ })
2191
+ }
2023
2192
  },
2024
2193
  false
2025
2194
  )
@@ -2326,6 +2495,18 @@ var resolveConfig = (layers = []) => {
2326
2495
  );
2327
2496
  }
2328
2497
  }
2498
+ const rank = { omit: 0, mask: 1, redact: 2, raw: 3 };
2499
+ const effectiveMode = parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent ? "omit" : parsed.data.privacy.contentMode;
2500
+ const widening = enabled.filter(
2501
+ (destination) => (destination.scopes ?? []).some(
2502
+ (scope) => scope.contentMode !== void 0 && rank[scope.contentMode] > rank[effectiveMode]
2503
+ )
2504
+ ).map((destination) => destination.name);
2505
+ if (widening.length > 0) {
2506
+ notes.push(
2507
+ `destination(s) ${widening.join(", ")} have a scope contentMode above privacy.contentMode=${effectiveMode}; a scope can only lower disclosure, so ${effectiveMode} applies`
2508
+ );
2509
+ }
2329
2510
  }
2330
2511
  if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2331
2512
  notes.push(
@@ -2373,6 +2554,9 @@ var describeDestinationAttributes = (config) => {
2373
2554
  }
2374
2555
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2375
2556
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2557
+ if (destination.scopes !== void 0) {
2558
+ attributes[`${prefix}.scope_count`] = destination.scopes.length;
2559
+ }
2376
2560
  }
2377
2561
  return attributes;
2378
2562
  };
@@ -9364,7 +9548,7 @@ import {
9364
9548
  } from "@opentelemetry/semantic-conventions/incubating";
9365
9549
 
9366
9550
  // src/version.ts
9367
- var VERSION = "0.13.2";
9551
+ var VERSION = "0.14.0";
9368
9552
 
9369
9553
  // src/telemetry/export-identity.ts
9370
9554
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9937,6 +10121,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
9937
10121
  };
9938
10122
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9939
10123
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
10124
+ var spanEndEdgesOf = (events) => {
10125
+ const layout = layoutBatch(events);
10126
+ const ends = /* @__PURE__ */ new Map();
10127
+ for (const [eventId, groupKey] of layout.groupOf) {
10128
+ const end = layout.groups.get(groupKey)?.end;
10129
+ if (end !== void 0) {
10130
+ ends.set(eventId, end);
10131
+ }
10132
+ }
10133
+ return ends;
10134
+ };
9940
10135
  var canonicalEventTraceIdentities = (events, options = {}) => {
9941
10136
  const layout = layoutBatch(events);
9942
10137
  const correlations = indexCorrelations(options.correlations);
@@ -13243,14 +13438,20 @@ var createSignalFanout = (options) => {
13243
13438
  };
13244
13439
  var shareCorrelationPerBatch = (correlate) => {
13245
13440
  let pending;
13246
- return (events) => {
13247
- if (pending?.events === events) {
13441
+ const resolve5 = (events) => {
13442
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
13248
13443
  return pending.result;
13249
13444
  }
13250
13445
  const result = correlate(events);
13251
- pending = { events, result };
13446
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
13252
13447
  return result;
13253
13448
  };
13449
+ const alias = (subset, batch) => {
13450
+ if (pending?.events === batch && subset !== batch) {
13451
+ pending.aliases.add(subset);
13452
+ }
13453
+ };
13454
+ return Object.assign(resolve5, { alias });
13254
13455
  };
13255
13456
 
13256
13457
  // src/telemetry/durable-metric-spool.ts
@@ -13603,6 +13804,101 @@ var createOtlpMetricSink = (options) => {
13603
13804
  };
13604
13805
  };
13605
13806
 
13807
+ // src/telemetry/destination-scope.ts
13808
+ var DISCLOSURE_RANK2 = Object.freeze({
13809
+ omitted: 0,
13810
+ masked: 1,
13811
+ redacted: 2,
13812
+ raw: 3
13813
+ });
13814
+ var omitRestrictedContent = (fact, mode) => {
13815
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
13816
+ return fact;
13817
+ }
13818
+ const { text, ...rest } = fact;
13819
+ void text;
13820
+ return { ...rest, disclosure: "omitted", truncated: false };
13821
+ };
13822
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
13823
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
13824
+ var eventRepositoryKey = (event3, fallbackKey) => {
13825
+ const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
13826
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
13827
+ };
13828
+ var pointRepositoryKey = (point, fallbackKey) => {
13829
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
13830
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
13831
+ };
13832
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
13833
+ var restrictEventContent = (event3, mode, restrict) => {
13834
+ switch (event3.type) {
13835
+ case "prompt.submitted":
13836
+ return event3.content === void 0 ? event3 : { ...event3, content: restrict(event3.content, mode) };
13837
+ case "generation.start": {
13838
+ const inputContent = restrictFacts(event3.inputContent, mode, restrict);
13839
+ return inputContent === void 0 ? event3 : { ...event3, inputContent };
13840
+ }
13841
+ case "generation.end": {
13842
+ const outputContent = restrictFacts(event3.outputContent, mode, restrict);
13843
+ return outputContent === void 0 ? event3 : { ...event3, outputContent };
13844
+ }
13845
+ case "tool.start":
13846
+ return event3.input === void 0 ? event3 : { ...event3, input: restrict(event3.input, mode) };
13847
+ case "tool.end":
13848
+ return event3.output === void 0 ? event3 : { ...event3, output: restrict(event3.output, mode) };
13849
+ case "error.raised":
13850
+ return event3.message === void 0 ? event3 : { ...event3, message: restrict(event3.message, mode) };
13851
+ default:
13852
+ return event3;
13853
+ }
13854
+ };
13855
+ var routeEventsToScopes = (events, scopes, options) => {
13856
+ const ends = spanEndEdgesOf(events);
13857
+ const traces = [];
13858
+ const logs = [];
13859
+ let unchanged = true;
13860
+ for (const event3 of events) {
13861
+ const anchor = ends.get(event3.eventId) ?? event3;
13862
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
13863
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
13864
+ unchanged = false;
13865
+ }
13866
+ if (scope === void 0) {
13867
+ continue;
13868
+ }
13869
+ const restricted = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
13870
+ if (restricted !== event3) {
13871
+ unchanged = false;
13872
+ }
13873
+ if (scope.signals.traces) {
13874
+ traces.push(restricted);
13875
+ }
13876
+ if (scope.signals.logs) {
13877
+ logs.push(restricted);
13878
+ }
13879
+ }
13880
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
13881
+ };
13882
+ var routePointsToScopes = (scopes, pointsFor, options) => {
13883
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
13884
+ const kept = [];
13885
+ for (const variant of [true, false]) {
13886
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
13887
+ continue;
13888
+ }
13889
+ for (const point of pointsFor(variant) ?? []) {
13890
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
13891
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
13892
+ kept.push(point);
13893
+ }
13894
+ }
13895
+ }
13896
+ return kept;
13897
+ };
13898
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
13899
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
13900
+ );
13901
+
13606
13902
  // src/telemetry/export-destinations.ts
13607
13903
  var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
13608
13904
  traces: `destinations/${destination}/spool`,
@@ -13669,6 +13965,8 @@ var createExportDestinationSinks = (options) => {
13669
13965
  ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
13670
13966
  probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
13671
13967
  });
13968
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
13969
+ const restrict = options.restrictContent ?? omitRestrictedContent;
13672
13970
  for (const destination of resolveExportDestinations(options.exporter)) {
13673
13971
  let headers;
13674
13972
  let logHeaders;
@@ -13758,17 +14056,51 @@ var createExportDestinationSinks = (options) => {
13758
14056
  metrics,
13759
14057
  ...spool === void 0 ? {} : { spool },
13760
14058
  ...logSpool === void 0 ? {} : { logSpool },
13761
- ...metricSpool === void 0 ? {} : { metricSpool }
14059
+ ...metricSpool === void 0 ? {} : { metricSpool },
14060
+ ...destination.scopes === void 0 ? {} : {
14061
+ scopes: destination.scopes,
14062
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
14063
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
14064
+ restrict
14065
+ })
14066
+ }
13762
14067
  });
13763
14068
  }
13764
14069
  return { destinations, skipped };
13765
14070
  };
13766
- var createDestinationFanout = (destinations) => {
14071
+ var createScopedFanout = (destination, correlate) => {
14072
+ const route = destination.route;
14073
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
14074
+ if (route === void 0) {
14075
+ return unscoped;
14076
+ }
14077
+ const none2 = { accepted: 0, rejected: 0, errors: [] };
14078
+ return {
14079
+ ...unscoped,
14080
+ emit: async (events) => {
14081
+ const batch = route(events);
14082
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
14083
+ await correlate(events);
14084
+ correlate.alias(batch.traces, events);
14085
+ correlate.alias(batch.logs, events);
14086
+ }
14087
+ const traces = batch.traces.length === 0 ? none2 : await destination.traces.emit(batch.traces);
14088
+ const logs = batch.logs.length === 0 ? none2 : await destination.logs.emit(batch.logs);
14089
+ return {
14090
+ accepted: traces.accepted + logs.accepted,
14091
+ rejected: traces.rejected + logs.rejected,
14092
+ errors: [...traces.errors, ...logs.errors]
14093
+ };
14094
+ }
14095
+ };
14096
+ };
14097
+ var createDestinationFanout = (destinations, options = {}) => {
13767
14098
  const fanouts = destinations.map((destination) => ({
13768
14099
  name: destination.name,
13769
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
14100
+ sink: createScopedFanout(destination, options.correlate)
13770
14101
  }));
13771
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
14102
+ const scoped = destinations.some((destination) => destination.route !== void 0);
14103
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
13772
14104
  if (only !== void 0) {
13773
14105
  return only.sink;
13774
14106
  }
@@ -13889,7 +14221,8 @@ var createHookRuntime = (options) => {
13889
14221
  // has always been governed by.
13890
14222
  allowRawContent: privacy.policy.allowRawContent
13891
14223
  },
13892
- correlate
14224
+ correlate,
14225
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
13893
14226
  });
13894
14227
  const primary = exportDestinations.destinations[0];
13895
14228
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -13906,7 +14239,7 @@ var createHookRuntime = (options) => {
13906
14239
  });
13907
14240
  const spool = primary?.spool;
13908
14241
  const logSpool = primary?.logSpool;
13909
- const sink = createDestinationFanout(exportDestinations.destinations);
14242
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
13910
14243
  const hookDeps = {
13911
14244
  stateStore,
13912
14245
  config: options.config,
@@ -13947,6 +14280,8 @@ var createHookRuntime = (options) => {
13947
14280
  (destination) => destination.metrics.enabled
13948
14281
  );
13949
14282
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
14283
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
14284
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
13950
14285
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
13951
14286
  if (deliveryRetentionMillis < staleClaimMillis) {
13952
14287
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -14012,28 +14347,63 @@ var createHookRuntime = (options) => {
14012
14347
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
14013
14348
  }
14014
14349
  }
14015
- const observations = deriveMetricObservations({
14016
- events: ingest.events,
14017
- usage: ingest.usageObservations,
14018
- resource: metricResource,
14019
- includeSessionId: metricsPolicy.includeSessionId,
14020
- ...generationStarts === void 0 ? {} : { generationStarts },
14021
- turnStart: (sessionId) => turnStarts.get(sessionId)
14022
- });
14023
- if (observations.length === 0) {
14350
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
14351
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
14352
+ const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
14353
+ (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
14354
+ ...event3,
14355
+ contextAttributes: {
14356
+ ...event3.contextAttributes,
14357
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
14358
+ }
14359
+ } : event3
14360
+ );
14361
+ const pointsByVariant = /* @__PURE__ */ new Map();
14362
+ const variants = new Set(
14363
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
14364
+ );
14365
+ for (const destination of scopedMetricDestinations) {
14366
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
14367
+ variants.add(variant);
14368
+ }
14369
+ }
14370
+ for (const includeSessionId of variants) {
14371
+ const observations = deriveMetricObservations({
14372
+ events: metricEvents,
14373
+ usage: ingest.usageObservations,
14374
+ resource: metricResource,
14375
+ includeSessionId,
14376
+ ...generationStarts === void 0 ? {} : { generationStarts },
14377
+ turnStart: (sessionId) => turnStarts.get(sessionId)
14378
+ });
14379
+ if (observations.length === 0) {
14380
+ continue;
14381
+ }
14382
+ pointsByVariant.set(
14383
+ includeSessionId,
14384
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
14385
+ perSession: includeSessionId,
14386
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
14387
+ })
14388
+ );
14389
+ }
14390
+ if (pointsByVariant.size === 0) {
14024
14391
  return void 0;
14025
14392
  }
14026
- const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
14027
- perSession: metricsPolicy.includeSessionId,
14028
- ...deliveryToken === void 0 ? {} : { deliveryToken }
14029
- });
14030
14393
  const context = agreedContextAttributes(ingest.events);
14031
14394
  const results = await Promise.all(
14032
14395
  metricDestinations.map(async (destination) => {
14033
- const result = await destination.metrics.exportPoints(points, context).catch(
14396
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
14397
+ fallbackKey: scopedRepositoryFallback,
14398
+ includeSessionId: metricsPolicy.includeSessionId
14399
+ });
14400
+ if (points2.length === 0) {
14401
+ return { name: destination.name, accepted: 0, rejected: 0 };
14402
+ }
14403
+ const result = await destination.metrics.exportPoints(points2, context).catch(
14034
14404
  (thrown) => ({
14035
14405
  accepted: 0,
14036
- rejected: points.length,
14406
+ rejected: points2.length,
14037
14407
  errors: [
14038
14408
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
14039
14409
  ]
@@ -14043,7 +14413,8 @@ var createHookRuntime = (options) => {
14043
14413
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
14044
14414
  })
14045
14415
  );
14046
- return { points: points.length, destinations: results };
14416
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
14417
+ return { points, destinations: results };
14047
14418
  } catch (thrown) {
14048
14419
  diagnostics.push(stateDiagnostic(thrown));
14049
14420
  logger.warn("hook-derived metrics could not be recorded for this callback", {});
@@ -15806,11 +16177,13 @@ var planProviderRegistration = (input) => {
15806
16177
  };
15807
16178
  };
15808
16179
  export {
16180
+ ALL_REPOSITORIES,
15809
16181
  ANTIGRAVITY_CAPABILITIES,
15810
16182
  ANTIGRAVITY_HOOK_EVENT_NAMES,
15811
16183
  ANTIGRAVITY_PROMOTION_GATES,
15812
16184
  ANTIGRAVITY_PROVIDER_ID,
15813
16185
  ANTIGRAVITY_PROVIDER_MATURITY,
16186
+ ATTR_VCS_REPOSITORY_URL_FULL,
15814
16187
  BUILT_IN_PROVIDERS,
15815
16188
  CANONICAL_EVENT_TYPES,
15816
16189
  CANONICAL_SCHEMA_VERSION,
@@ -15902,6 +16275,7 @@ export {
15902
16275
  MAX_DELIVERY_COMPONENTS,
15903
16276
  MAX_DELIVERY_GAPS,
15904
16277
  MAX_DESTINATION_HEADERS,
16278
+ MAX_DESTINATION_SCOPES,
15905
16279
  MAX_EXPORT_DESTINATIONS,
15906
16280
  MAX_EXTENSION_ENTRIES,
15907
16281
  MAX_IDENTIFIER_LENGTH,
@@ -15910,9 +16284,11 @@ export {
15910
16284
  MAX_LOG_RECORDS_PER_EVENT,
15911
16285
  MAX_OTLP_HEADERS,
15912
16286
  MAX_RECOVERED_START_ATTRIBUTES,
16287
+ MAX_REPOSITORY_REFERENCE_LENGTH,
15913
16288
  MAX_RESOURCE_ATTRIBUTES,
15914
16289
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
15915
16290
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
16291
+ MAX_SCOPE_REPOSITORIES,
15916
16292
  MAX_SESSION_CONTEXT_SEGMENTS,
15917
16293
  MAX_TARGET_HINT_PATHS,
15918
16294
  MAX_TARGET_PATH_LENGTH,
@@ -16049,6 +16425,7 @@ export {
16049
16425
  describeResolvedConfig,
16050
16426
  describeResourceAttributeNames,
16051
16427
  describeThrown,
16428
+ destinationScopeSchema,
16052
16429
  detectDocumentFormat,
16053
16430
  detectionConfidenceSchema,
16054
16431
  detectionPolicySchema,
@@ -16065,6 +16442,7 @@ export {
16065
16442
  errorRaisedEventSchema,
16066
16443
  errorSeveritySchema,
16067
16444
  eventIdSchema,
16445
+ eventRepositoryKey,
16068
16446
  eventUsage,
16069
16447
  exportDestinationSchema,
16070
16448
  exportDestinationsSchema,
@@ -16107,6 +16485,7 @@ export {
16107
16485
  logSignalsForLifecycleEvents,
16108
16486
  logsPolicySchema,
16109
16487
  managedHookPredicate,
16488
+ matchDestinationScope,
16110
16489
  mergeAntigravityHookRegistration,
16111
16490
  mergeClaudeHookRegistration,
16112
16491
  mergeCodexHookRegistration,
@@ -16118,8 +16497,10 @@ export {
16118
16497
  minimumStaleClaimMillis,
16119
16498
  modelDescriptorSchema,
16120
16499
  nonEmptyStringSchema,
16500
+ normalizeRepositoryKey,
16121
16501
  normalizeUsage,
16122
16502
  normalizeUsageOrThrow,
16503
+ omitRestrictedContent,
16123
16504
  otelHookConfigPatchSchema,
16124
16505
  otelHookConfigSchema,
16125
16506
  otelHookErrorCodeSchema,
@@ -16136,6 +16517,7 @@ export {
16136
16517
  parseResourceAttributesValue,
16137
16518
  parseSessionContextFile,
16138
16519
  planProviderRegistration,
16520
+ pointRepositoryKey,
16139
16521
  privacyLimitsSchema,
16140
16522
  privacyPolicySchema,
16141
16523
  promptSubmittedEventSchema,
@@ -16172,6 +16554,7 @@ export {
16172
16554
  resolveConfig,
16173
16555
  resolveDeliveryIdentity,
16174
16556
  resolveDestinationHeaders,
16557
+ resolveDestinationScopes,
16175
16558
  resolveEventTargets,
16176
16559
  resolveExportDestinations,
16177
16560
  resolveInstallPath,
@@ -16183,6 +16566,10 @@ export {
16183
16566
  resolvedProviderIdSchema,
16184
16567
  resourceAttributeValueSchema,
16185
16568
  resourceAttributesSchema,
16569
+ resourceRepositoryKey,
16570
+ restrictEventContent,
16571
+ routeEventsToScopes,
16572
+ routePointsToScopes,
16186
16573
  runRegistrationLifecycle,
16187
16574
  sanitizeResourceAttributes,
16188
16575
  sanitizeSessionContextAttributes,
@@ -16195,6 +16582,7 @@ export {
16195
16582
  sessionCwdHint,
16196
16583
  sessionEndEventSchema,
16197
16584
  sessionIdSchema,
16585
+ sessionIdVariantsFor,
16198
16586
  sessionStartEventSchema,
16199
16587
  shareCorrelationPerBatch,
16200
16588
  sourceProvenanceSchema,