@osfactory/otel-hook 0.13.2 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +57 -0
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-But5fFCk.d.ts} +9 -2
  3. package/dist/cli.js +628 -73
  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-8tNkIC8a.d.ts} +110 -10
  10. package/dist/{filesystem-store-B3CpiIRl.d.ts → filesystem-store-Z8XgDtFj.d.ts} +1 -1
  11. package/dist/{hook-CKLpgrYP.d.ts → hook-D7XABd4f.d.ts} +19 -5
  12. package/dist/index.d.ts +14 -14
  13. package/dist/index.js +626 -72
  14. package/dist/index.js.map +1 -1
  15. package/dist/install.d.ts +4 -4
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +9 -9
  18. package/dist/integration.js +555 -65
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.d.ts +1 -1
  21. package/dist/lifecycle.js +1 -1
  22. package/dist/lifecycle.js.map +1 -1
  23. package/dist/{memory-B3r6sZtC.d.ts → memory-gipZUiXP.d.ts} +1 -1
  24. package/dist/{payload-DLK7QaBB.d.ts → payload-DWdx9yk3.d.ts} +1 -1
  25. package/dist/{ports-DhpSDIkp.d.ts → ports-qZTwK-z2.d.ts} +22 -2
  26. package/dist/privacy.d.ts +2 -2
  27. package/dist/privacy.js +42 -1
  28. package/dist/privacy.js.map +1 -1
  29. package/dist/providers.d.ts +9 -9
  30. package/dist/providers.js +22 -5
  31. package/dist/providers.js.map +1 -1
  32. package/dist/{registry-DM-4YvIA.d.ts → registry-D9rmMYxw.d.ts} +2 -2
  33. package/dist/runtime.d.ts +24 -9
  34. package/dist/runtime.js +282 -30
  35. package/dist/runtime.js.map +1 -1
  36. package/dist/{schema-CD61uW99.d.ts → schema-oRsbo7WO.d.ts} +45 -0
  37. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  38. package/dist/state.d.ts +3 -3
  39. package/dist/state.js.map +1 -1
  40. package/dist/telemetry.d.ts +6 -5
  41. package/dist/telemetry.js +304 -17
  42. package/dist/telemetry.js.map +1 -1
  43. package/dist/testing.d.ts +8 -8
  44. package/dist/testing.js +185 -10
  45. package/dist/testing.js.map +1 -1
  46. 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
 
@@ -4144,7 +4330,12 @@ var createAntigravityAdapter = (options = {}) => {
4144
4330
  reason: payload.fullyIdle ? "Stop signals execution/turn completion (fullyIdle=true) but exposes no session or generation identity, so it cannot become session.end or generation.end without inventing one" : "Stop received while the agent is not fully idle; the conversation continues and the hook exposes no lifecycle fact the canonical model can represent"
4145
4331
  };
4146
4332
  }
4147
- return { status: "parsed", events: factory.events() };
4333
+ const [onlyWorkspacePath, ...otherWorkspacePaths] = payload.workspacePaths;
4334
+ return {
4335
+ status: "parsed",
4336
+ events: factory.events(),
4337
+ ...onlyWorkspacePath === void 0 || onlyWorkspacePath.length === 0 || otherWorkspacePaths.length > 0 ? {} : { workspaceDirectory: onlyWorkspacePath }
4338
+ };
4148
4339
  };
4149
4340
  const hookResponse2 = () => SILENT_HOOK_RESPONSE;
4150
4341
  return {
@@ -5211,7 +5402,8 @@ var parseClaudeCode = (input, context) => {
5211
5402
  status: "parsed",
5212
5403
  events: factory.events(),
5213
5404
  ...warnings.length === 0 ? {} : { warnings },
5214
- ...targetHints.size === 0 ? {} : { targetHints }
5405
+ ...targetHints.size === 0 ? {} : { targetHints },
5406
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
5215
5407
  };
5216
5408
  };
5217
5409
 
@@ -5873,7 +6065,8 @@ var parse = (input, context) => {
5873
6065
  status: "parsed",
5874
6066
  events: factory.events(),
5875
6067
  ...warnings.length === 0 ? {} : { warnings },
5876
- ...targetHints.size === 0 ? {} : { targetHints }
6068
+ ...targetHints.size === 0 ? {} : { targetHints },
6069
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
5877
6070
  };
5878
6071
  };
5879
6072
  var hookResponse = () => SILENT_HOOK_RESPONSE;
@@ -6360,6 +6553,13 @@ var deriveWorkspace = (context, payload) => {
6360
6553
  }
6361
6554
  return void 0;
6362
6555
  };
6556
+ var workspaceDirectoryOf = (payload) => {
6557
+ const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);
6558
+ if (roots.length > 0) {
6559
+ return roots.length === 1 ? roots[0] : void 0;
6560
+ }
6561
+ return payload.cwd !== void 0 && payload.cwd.length > 0 ? payload.cwd : void 0;
6562
+ };
6363
6563
  var invocationDiscriminator = (payload) => {
6364
6564
  switch (payload.hook_event_name) {
6365
6565
  case "sessionStart":
@@ -6819,11 +7019,13 @@ var createCursorAdapter = (options = {}) => {
6819
7019
  }
6820
7020
  }
6821
7021
  const targetHints = factory.targetHints();
7022
+ const workspaceDirectory = workspaceDirectoryOf(payload);
6822
7023
  return {
6823
7024
  status: "parsed",
6824
7025
  events: factory.events(),
6825
7026
  ...warnings.length === 0 ? {} : { warnings },
6826
- ...targetHints.size === 0 ? {} : { targetHints }
7027
+ ...targetHints.size === 0 ? {} : { targetHints },
7028
+ ...workspaceDirectory === void 0 ? {} : { workspaceDirectory }
6827
7029
  };
6828
7030
  };
6829
7031
  const hookResponse2 = (input) => {
@@ -7477,7 +7679,8 @@ var createGeminiCliAdapter = (options = {}) => {
7477
7679
  return {
7478
7680
  status: "parsed",
7479
7681
  events: factory.events(),
7480
- ...warnings.length === 0 ? {} : { warnings }
7682
+ ...warnings.length === 0 ? {} : { warnings },
7683
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
7481
7684
  };
7482
7685
  };
7483
7686
  const hookResponse2 = () => SILENT_HOOK_RESPONSE;
@@ -9149,7 +9352,7 @@ import {
9149
9352
  } from "@opentelemetry/semantic-conventions/incubating";
9150
9353
 
9151
9354
  // src/version.ts
9152
- var VERSION = "0.13.2";
9355
+ var VERSION = "0.14.1";
9153
9356
 
9154
9357
  // src/telemetry/semconv.ts
9155
9358
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -9632,6 +9835,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
9632
9835
  };
9633
9836
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9634
9837
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9838
+ var spanEndEdgesOf = (events) => {
9839
+ const layout = layoutBatch(events);
9840
+ const ends = /* @__PURE__ */ new Map();
9841
+ for (const [eventId, groupKey] of layout.groupOf) {
9842
+ const end = layout.groups.get(groupKey)?.end;
9843
+ if (end !== void 0) {
9844
+ ends.set(eventId, end);
9845
+ }
9846
+ }
9847
+ return ends;
9848
+ };
9635
9849
  var canonicalEventTraceIdentities = (events, options = {}) => {
9636
9850
  const layout = layoutBatch(events);
9637
9851
  const correlations = indexCorrelations(options.correlations);
@@ -11173,6 +11387,117 @@ var createOtlpMetricSink = (options) => {
11173
11387
  };
11174
11388
  };
11175
11389
 
11390
+ // src/telemetry/destination-scope.ts
11391
+ var DISCLOSURE_RANK2 = Object.freeze({
11392
+ omitted: 0,
11393
+ masked: 1,
11394
+ redacted: 2,
11395
+ raw: 3
11396
+ });
11397
+ var omitRestrictedContent = (fact, mode) => {
11398
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
11399
+ return fact;
11400
+ }
11401
+ const { text, ...rest } = fact;
11402
+ void text;
11403
+ return { ...rest, disclosure: "omitted", truncated: false };
11404
+ };
11405
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
11406
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
11407
+ var repositoryUrlForKey = (key) => `https://${key}`;
11408
+ var hasOwnStamp = (attributes) => attributes?.[ATTR_VCS_REPOSITORY_URL_FULL] !== void 0;
11409
+ var withRoutedRepository = (event3, key) => hasOwnStamp(event3.contextAttributes) ? event3 : {
11410
+ ...event3,
11411
+ contextAttributes: { ...event3.contextAttributes, [ATTR_VCS_REPOSITORY_URL_FULL]: repositoryUrlForKey(key) }
11412
+ };
11413
+ var eventRepositoryKey = (event3, fallbackKey) => {
11414
+ const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
11415
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
11416
+ };
11417
+ var pointRepositoryKey = (point, fallbackKey) => {
11418
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
11419
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
11420
+ };
11421
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
11422
+ var restrictEventContent = (event3, mode, restrict) => {
11423
+ switch (event3.type) {
11424
+ case "prompt.submitted":
11425
+ return event3.content === void 0 ? event3 : { ...event3, content: restrict(event3.content, mode) };
11426
+ case "generation.start": {
11427
+ const inputContent = restrictFacts(event3.inputContent, mode, restrict);
11428
+ return inputContent === void 0 ? event3 : { ...event3, inputContent };
11429
+ }
11430
+ case "generation.end": {
11431
+ const outputContent = restrictFacts(event3.outputContent, mode, restrict);
11432
+ return outputContent === void 0 ? event3 : { ...event3, outputContent };
11433
+ }
11434
+ case "tool.start":
11435
+ return event3.input === void 0 ? event3 : { ...event3, input: restrict(event3.input, mode) };
11436
+ case "tool.end":
11437
+ return event3.output === void 0 ? event3 : { ...event3, output: restrict(event3.output, mode) };
11438
+ case "error.raised":
11439
+ return event3.message === void 0 ? event3 : { ...event3, message: restrict(event3.message, mode) };
11440
+ default:
11441
+ return event3;
11442
+ }
11443
+ };
11444
+ var routeEventsToScopes = (events, scopes, options) => {
11445
+ const ends = spanEndEdgesOf(events);
11446
+ const fallbackKey = options.workspaceRepositoryKey ?? options.resourceRepositoryKey;
11447
+ const traces = [];
11448
+ const logs = [];
11449
+ let unchanged = true;
11450
+ for (const event3 of events) {
11451
+ const anchor = ends.get(event3.eventId) ?? event3;
11452
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, fallbackKey));
11453
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
11454
+ unchanged = false;
11455
+ }
11456
+ if (scope === void 0) {
11457
+ continue;
11458
+ }
11459
+ const lowered = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
11460
+ const restricted = hasOwnStamp(anchor.contextAttributes) || fallbackKey === void 0 ? lowered : withRoutedRepository(lowered, fallbackKey);
11461
+ if (restricted !== event3) {
11462
+ unchanged = false;
11463
+ }
11464
+ if (scope.signals.traces) {
11465
+ traces.push(restricted);
11466
+ }
11467
+ if (scope.signals.logs) {
11468
+ logs.push(restricted);
11469
+ }
11470
+ }
11471
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
11472
+ };
11473
+ var routePointsToScopes = (scopes, pointsFor, options) => {
11474
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
11475
+ const kept = [];
11476
+ for (const variant of [true, false]) {
11477
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
11478
+ continue;
11479
+ }
11480
+ for (const point of pointsFor(variant) ?? []) {
11481
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
11482
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
11483
+ kept.push(
11484
+ hasOwnStamp(point.attributes) || options.fallbackKey === void 0 ? point : {
11485
+ ...point,
11486
+ attributes: {
11487
+ ...point.attributes,
11488
+ [ATTR_VCS_REPOSITORY_URL_FULL]: repositoryUrlForKey(options.fallbackKey)
11489
+ }
11490
+ }
11491
+ );
11492
+ }
11493
+ }
11494
+ }
11495
+ return kept;
11496
+ };
11497
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
11498
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
11499
+ );
11500
+
11176
11501
  // src/telemetry/signal-fanout.ts
11177
11502
  var createSignalFanout = (options) => {
11178
11503
  const emit = async (events) => {
@@ -11205,14 +11530,20 @@ var createSignalFanout = (options) => {
11205
11530
  };
11206
11531
  var shareCorrelationPerBatch = (correlate) => {
11207
11532
  let pending;
11208
- return (events) => {
11209
- if (pending?.events === events) {
11533
+ const resolve8 = (events) => {
11534
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
11210
11535
  return pending.result;
11211
11536
  }
11212
11537
  const result = correlate(events);
11213
- pending = { events, result };
11538
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
11214
11539
  return result;
11215
11540
  };
11541
+ const alias = (subset, batch) => {
11542
+ if (pending?.events === batch && subset !== batch) {
11543
+ pending.aliases.add(subset);
11544
+ }
11545
+ };
11546
+ return Object.assign(resolve8, { alias });
11216
11547
  };
11217
11548
 
11218
11549
  // src/telemetry/export-destinations.ts
@@ -11281,6 +11612,8 @@ var createExportDestinationSinks = (options) => {
11281
11612
  ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
11282
11613
  probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
11283
11614
  });
11615
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
11616
+ const restrict = options.restrictContent ?? omitRestrictedContent;
11284
11617
  for (const destination of resolveExportDestinations(options.exporter)) {
11285
11618
  let headers;
11286
11619
  let logHeaders;
@@ -11370,24 +11703,59 @@ var createExportDestinationSinks = (options) => {
11370
11703
  metrics,
11371
11704
  ...spool === void 0 ? {} : { spool },
11372
11705
  ...logSpool === void 0 ? {} : { logSpool },
11373
- ...metricSpool === void 0 ? {} : { metricSpool }
11706
+ ...metricSpool === void 0 ? {} : { metricSpool },
11707
+ ...destination.scopes === void 0 ? {} : {
11708
+ scopes: destination.scopes,
11709
+ route: (events, workspaceRepositoryKey) => routeEventsToScopes(events, destination.scopes ?? [], {
11710
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
11711
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey },
11712
+ restrict
11713
+ })
11714
+ }
11374
11715
  });
11375
11716
  }
11376
11717
  return { destinations, skipped };
11377
11718
  };
11378
- var createDestinationFanout = (destinations) => {
11719
+ var createScopedFanout = (destination, correlate) => {
11720
+ const route = destination.route;
11721
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
11722
+ if (route === void 0) {
11723
+ return unscoped;
11724
+ }
11725
+ const none2 = { accepted: 0, rejected: 0, errors: [] };
11726
+ return {
11727
+ ...unscoped,
11728
+ emit: async (events, emitOptions) => {
11729
+ const batch = route(events, emitOptions?.workspaceRepositoryKey);
11730
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
11731
+ await correlate(events);
11732
+ correlate.alias(batch.traces, events);
11733
+ correlate.alias(batch.logs, events);
11734
+ }
11735
+ const traces = batch.traces.length === 0 ? none2 : await destination.traces.emit(batch.traces);
11736
+ const logs = batch.logs.length === 0 ? none2 : await destination.logs.emit(batch.logs);
11737
+ return {
11738
+ accepted: traces.accepted + logs.accepted,
11739
+ rejected: traces.rejected + logs.rejected,
11740
+ errors: [...traces.errors, ...logs.errors]
11741
+ };
11742
+ }
11743
+ };
11744
+ };
11745
+ var createDestinationFanout = (destinations, options = {}) => {
11379
11746
  const fanouts = destinations.map((destination) => ({
11380
11747
  name: destination.name,
11381
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
11748
+ sink: createScopedFanout(destination, options.correlate)
11382
11749
  }));
11383
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
11750
+ const scoped = destinations.some((destination) => destination.route !== void 0);
11751
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
11384
11752
  if (only !== void 0) {
11385
11753
  return only.sink;
11386
11754
  }
11387
- const emit = async (events) => {
11755
+ const emit = async (events, emitOptions) => {
11388
11756
  const results = await Promise.all(
11389
11757
  fanouts.map(
11390
- (fanout) => fanout.sink.emit(events).catch(
11758
+ (fanout) => fanout.sink.emit(events, emitOptions).catch(
11391
11759
  (thrown) => ({
11392
11760
  accepted: 0,
11393
11761
  rejected: events.length,
@@ -11610,8 +11978,25 @@ var describeDestinationLine = (destination) => {
11610
11978
  );
11611
11979
  }
11612
11980
  }
11613
- return `${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`;
11981
+ if (destination.scopes === void 0) {
11982
+ if (destination.enabled) {
11983
+ parts.push("all repositories");
11984
+ }
11985
+ } else {
11986
+ parts.push(`scoped (${String(destination.scopes.length)} scope(s); records without a repository are not sent)`);
11987
+ }
11988
+ const lines = [`${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`];
11989
+ for (const [index, scope] of (destination.scopes ?? []).entries()) {
11990
+ lines.push(` scope ${String(index + 1)}: ${describeScopeLine(scope)}`);
11991
+ }
11992
+ return lines.join("\n");
11614
11993
  };
11994
+ var describeScopeLine = (scope) => [
11995
+ scope.repositories === "*" ? "every repository" : scope.repositories.join(", "),
11996
+ scope.signals.length === 0 ? "no signals" : scope.signals.join("+"),
11997
+ `content ${scope.contentMode ?? "as configured"}`,
11998
+ scope.includeSessionId ? "session.id on metrics" : "no session.id on metrics"
11999
+ ].join("; ");
11615
12000
  var sumSpoolStats = (all) => {
11616
12001
  const oldest = all.map((stats) => stats.oldestEnqueuedAt).filter((value) => value !== void 0);
11617
12002
  const lastDropped = all.map((stats) => stats.dropped.lastDroppedAt).filter((value) => value !== void 0);
@@ -15192,6 +15577,28 @@ var classifyDurability = (input) => {
15192
15577
  };
15193
15578
  var isCommittable = (durability) => durability !== "lost";
15194
15579
  var MAX_ERROR_EVENTS = 8;
15580
+ var resolveWorkspaceRepositoryKey = async (locator, directory, budgetMillis) => {
15581
+ if (locator?.originRepositoryKey === void 0) {
15582
+ return void 0;
15583
+ }
15584
+ let timer;
15585
+ const deadline = new Promise((resolve8) => {
15586
+ timer = setTimeout(() => resolve8(void 0), Math.max(0, budgetMillis));
15587
+ timer.unref?.();
15588
+ });
15589
+ try {
15590
+ return await Promise.race([
15591
+ locator.originRepositoryKey(directory).catch(() => void 0),
15592
+ deadline
15593
+ ]);
15594
+ } catch {
15595
+ return void 0;
15596
+ } finally {
15597
+ if (timer !== void 0) {
15598
+ clearTimeout(timer);
15599
+ }
15600
+ }
15601
+ };
15195
15602
  var collectContentFacts = (event3) => {
15196
15603
  const facts = [];
15197
15604
  const push = (fact) => {
@@ -15835,7 +16242,8 @@ var createOtelHook = (deps) => {
15835
16242
  kind: "ready",
15836
16243
  batch: batch2,
15837
16244
  dropped: screened.dropped,
15838
- ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
16245
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints },
16246
+ ...parsed.workspaceDirectory === void 0 ? {} : { workspaceDirectory: parsed.workspaceDirectory }
15839
16247
  };
15840
16248
  };
15841
16249
  let prepared;
@@ -15903,11 +16311,19 @@ var createOtelHook = (deps) => {
15903
16311
  batch,
15904
16312
  !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
15905
16313
  );
16314
+ const workspaceRepositoryKey = !suppress && batch.length > 0 && deps.routeByWorkspaceRepository === true && prepared.workspaceDirectory !== void 0 ? await resolveWorkspaceRepositoryKey(
16315
+ deps.worktreeLocator,
16316
+ prepared.workspaceDirectory,
16317
+ deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
16318
+ ) : void 0;
15906
16319
  let emitted = 0;
15907
16320
  let exportRejected = 0;
15908
16321
  if (!suppress && batch.length > 0) {
15909
16322
  try {
15910
- const result = await deps.sink.emit(batch);
16323
+ const result = await deps.sink.emit(
16324
+ batch,
16325
+ workspaceRepositoryKey === void 0 ? void 0 : { workspaceRepositoryKey }
16326
+ );
15911
16327
  emitted = result.accepted;
15912
16328
  exportRejected = result.rejected;
15913
16329
  diagnostics.push(...result.errors);
@@ -15966,7 +16382,8 @@ var createOtelHook = (deps) => {
15966
16382
  durability,
15967
16383
  dropped,
15968
16384
  hookResponse: hookResponseFor(adapter, detection, "attributed", void 0, emitted, diagnostics),
15969
- diagnostics
16385
+ diagnostics,
16386
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey }
15970
16387
  };
15971
16388
  } catch (thrown) {
15972
16389
  const info = errorInfoFromThrown(thrown, { code: "internal-error", phase: "parsing" });
@@ -16065,15 +16482,16 @@ var MAX_WORKTREE_WALK_DEPTH = 128;
16065
16482
  var MAX_GIT_FILE_BYTES = 4096;
16066
16483
  var MAX_CACHE_ENTRIES = 1024;
16067
16484
  var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
16485
+ var MAX_GIT_CONFIG_BYTES = 64 * 1024;
16068
16486
  var MAX_BRANCH_NAME_LENGTH = 255;
16069
16487
  var ABSENT = Object.freeze({ kind: "absent" });
16070
16488
  var INVALID = Object.freeze({ kind: "invalid" });
16071
- var readBounded2 = async (filePath) => {
16489
+ var readBounded2 = async (filePath, maxBytes = MAX_GIT_FILE_BYTES) => {
16072
16490
  let handle;
16073
16491
  try {
16074
16492
  handle = await open8(filePath, "r");
16075
- const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
16076
- const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
16493
+ const buffer = Buffer.alloc(maxBytes);
16494
+ const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
16077
16495
  return buffer.subarray(0, bytesRead).toString("utf8");
16078
16496
  } catch {
16079
16497
  return void 0;
@@ -16101,6 +16519,60 @@ var parseGitDirFile = (content, worktreeRoot) => {
16101
16519
  );
16102
16520
  };
16103
16521
  var parseCommonDirFile = (content, gitDir) => resolveGitPath(firstLine(content), gitDir);
16522
+ var unquoteConfigValue = (raw) => {
16523
+ let value = "";
16524
+ let quoted = false;
16525
+ for (let index = 0; index < raw.length; index += 1) {
16526
+ const char = raw[index];
16527
+ if (char === "\\") {
16528
+ const next = raw[index + 1];
16529
+ if (next === void 0) {
16530
+ return void 0;
16531
+ }
16532
+ value += next === "n" ? "\n" : next === "t" ? " " : next;
16533
+ index += 1;
16534
+ } else if (char === '"') {
16535
+ quoted = !quoted;
16536
+ } else if (!quoted && (char === "#" || char === ";")) {
16537
+ break;
16538
+ } else {
16539
+ value += char;
16540
+ }
16541
+ }
16542
+ return quoted ? void 0 : value.trim();
16543
+ };
16544
+ var parseOriginRemoteUrl = (content) => {
16545
+ const lines = content.split(/\r?\n/);
16546
+ if (!content.endsWith("\n")) {
16547
+ lines.pop();
16548
+ }
16549
+ let inOrigin = false;
16550
+ for (const rawLine of lines) {
16551
+ const line = rawLine.trim();
16552
+ if (line.startsWith("[")) {
16553
+ const close = line.indexOf("]");
16554
+ const header = close === -1 ? "" : line.slice(1, close).trim();
16555
+ const rest = close === -1 ? "" : line.slice(close + 1).trim();
16556
+ inOrigin = /^remote\s+"origin"$/i.test(header) && header.endsWith('"origin"') || header.toLowerCase() === "remote.origin";
16557
+ if (!inOrigin || rest.length === 0 || rest.startsWith("#") || rest.startsWith(";")) {
16558
+ continue;
16559
+ }
16560
+ const entry2 = /^url\s*=(.*)$/i.exec(rest);
16561
+ if (entry2 !== null) {
16562
+ return unquoteConfigValue(entry2[1] ?? "");
16563
+ }
16564
+ continue;
16565
+ }
16566
+ if (!inOrigin) {
16567
+ continue;
16568
+ }
16569
+ const entry = /^url\s*=(.*)$/i.exec(line);
16570
+ if (entry !== null) {
16571
+ return unquoteConfigValue(entry[1] ?? "");
16572
+ }
16573
+ }
16574
+ return void 0;
16575
+ };
16104
16576
  var isMissing = async (filePath) => {
16105
16577
  try {
16106
16578
  await lstat(filePath);
@@ -16121,11 +16593,15 @@ var repositoryOf = async (worktreeRoot, gitDir) => {
16121
16593
  const commonDirFile = path15.join(gitDir, "commondir");
16122
16594
  const content = await readBounded2(commonDirFile);
16123
16595
  if (content === void 0) {
16124
- return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
16596
+ return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot, configDir: gitDir } : { kind: "linked" };
16125
16597
  }
16126
16598
  const commonDir = parseCommonDirFile(content, gitDir);
16127
16599
  const mainRoot = commonDir !== void 0 && path15.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path15.dirname(commonDir) : void 0;
16128
- return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
16600
+ return {
16601
+ kind: "linked",
16602
+ ...mainRoot === void 0 ? {} : { mainRoot },
16603
+ ...commonDir === void 0 ? {} : { configDir: commonDir }
16604
+ };
16129
16605
  };
16130
16606
  var probeDirectory = async (directory) => {
16131
16607
  const dotGit = path15.join(directory, ".git");
@@ -16150,12 +16626,21 @@ var probeDirectory = async (directory) => {
16150
16626
  return INVALID;
16151
16627
  }
16152
16628
  const branch = parseHeadBranch(head);
16153
- const repository = info.isDirectory() ? { kind: "main", mainRoot: directory } : await repositoryOf(directory, gitDir);
16629
+ const { configDir, ...repository } = info.isDirectory() ? { kind: "main", mainRoot: directory, configDir: gitDir } : await repositoryOf(directory, gitDir);
16154
16630
  return {
16155
16631
  kind: "worktree",
16156
- located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository }
16632
+ located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository },
16633
+ configDir: configDir ?? ""
16157
16634
  };
16158
16635
  };
16636
+ var readOriginRepositoryKey = async (configDir) => {
16637
+ if (configDir.length === 0) {
16638
+ return void 0;
16639
+ }
16640
+ const content = await readBounded2(path15.join(configDir, "config"), MAX_GIT_CONFIG_BYTES);
16641
+ const url = content === void 0 ? void 0 : parseOriginRemoteUrl(content);
16642
+ return url === void 0 ? void 0 : normalizeRepositoryKey(url);
16643
+ };
16159
16644
  var createFilesystemWorktreeLocator = (options = {}) => {
16160
16645
  const now = options.monotonicMillis ?? (() => performance.now());
16161
16646
  const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
@@ -16173,32 +16658,57 @@ var createFilesystemWorktreeLocator = (options = {}) => {
16173
16658
  cache.set(directory, { at, probe });
16174
16659
  return probe;
16175
16660
  };
16176
- const locate = async (absolutePath) => {
16177
- try {
16178
- if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16661
+ const remoteCache = /* @__PURE__ */ new Map();
16662
+ const cachedOriginKey = (configDir) => {
16663
+ const hit = remoteCache.get(configDir);
16664
+ const at = now();
16665
+ if (hit !== void 0 && at - hit.at <= ttl) {
16666
+ return hit.key;
16667
+ }
16668
+ if (remoteCache.size >= MAX_CACHE_ENTRIES) {
16669
+ remoteCache.clear();
16670
+ }
16671
+ const key = readOriginRepositoryKey(configDir).catch(() => void 0);
16672
+ remoteCache.set(configDir, { at, key });
16673
+ return key;
16674
+ };
16675
+ const findWorktree = async (absolutePath) => {
16676
+ if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16677
+ return void 0;
16678
+ }
16679
+ let directory = path15.resolve(absolutePath);
16680
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
16681
+ const probe = await cachedProbe(directory);
16682
+ if (probe.kind === "worktree") {
16683
+ return probe;
16684
+ }
16685
+ if (probe.kind === "invalid") {
16179
16686
  return void 0;
16180
16687
  }
16181
- let directory = path15.resolve(absolutePath);
16182
- for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
16183
- const probe = await cachedProbe(directory);
16184
- if (probe.kind === "worktree") {
16185
- return probe.located;
16186
- }
16187
- if (probe.kind === "invalid") {
16188
- return void 0;
16189
- }
16190
- const parent = path15.dirname(directory);
16191
- if (parent === directory) {
16192
- return void 0;
16193
- }
16194
- directory = parent;
16688
+ const parent = path15.dirname(directory);
16689
+ if (parent === directory) {
16690
+ return void 0;
16195
16691
  }
16692
+ directory = parent;
16693
+ }
16694
+ return void 0;
16695
+ };
16696
+ const locate = async (absolutePath) => {
16697
+ try {
16698
+ return (await findWorktree(absolutePath))?.located;
16699
+ } catch {
16196
16700
  return void 0;
16701
+ }
16702
+ };
16703
+ const originRepositoryKey = async (absolutePath) => {
16704
+ try {
16705
+ const probe = await findWorktree(absolutePath);
16706
+ return probe === void 0 ? void 0 : await cachedOriginKey(probe.configDir);
16197
16707
  } catch {
16198
16708
  return void 0;
16199
16709
  }
16200
16710
  };
16201
- return { locate };
16711
+ return { locate, originRepositoryKey };
16202
16712
  };
16203
16713
 
16204
16714
  // src/integration/hook-runtime.ts
@@ -16286,7 +16796,8 @@ var createHookRuntime = (options) => {
16286
16796
  // has always been governed by.
16287
16797
  allowRawContent: privacy.policy.allowRawContent
16288
16798
  },
16289
- correlate
16799
+ correlate,
16800
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
16290
16801
  });
16291
16802
  const primary = exportDestinations.destinations[0];
16292
16803
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -16303,7 +16814,7 @@ var createHookRuntime = (options) => {
16303
16814
  });
16304
16815
  const spool = primary?.spool;
16305
16816
  const logSpool = primary?.logSpool;
16306
- const sink = createDestinationFanout(exportDestinations.destinations);
16817
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
16307
16818
  const hookDeps = {
16308
16819
  stateStore,
16309
16820
  config: options.config,
@@ -16333,7 +16844,12 @@ var createHookRuntime = (options) => {
16333
16844
  })(),
16334
16845
  ...options.worktreeLocator === null ? {} : {
16335
16846
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
16336
- }
16847
+ },
16848
+ // Only a scoped destination routes by repository, so only then is the session
16849
+ // directory's remote read at all.
16850
+ routeByWorkspaceRepository: exportDestinations.destinations.some(
16851
+ (destination) => destination.scopes !== void 0
16852
+ )
16337
16853
  };
16338
16854
  const hook = createOtelHook({ ...hookDeps, sink });
16339
16855
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
@@ -16344,6 +16860,8 @@ var createHookRuntime = (options) => {
16344
16860
  (destination) => destination.metrics.enabled
16345
16861
  );
16346
16862
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
16863
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
16864
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
16347
16865
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
16348
16866
  if (deliveryRetentionMillis < staleClaimMillis) {
16349
16867
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -16409,28 +16927,64 @@ var createHookRuntime = (options) => {
16409
16927
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
16410
16928
  }
16411
16929
  }
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) {
16930
+ const resourceFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
16931
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : ingest.workspaceRepositoryKey ?? resourceFallback;
16932
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
16933
+ const metricEvents = resourceFallback === void 0 || ingest.workspaceRepositoryKey !== void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
16934
+ (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
16935
+ ...event3,
16936
+ contextAttributes: {
16937
+ ...event3.contextAttributes,
16938
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
16939
+ }
16940
+ } : event3
16941
+ );
16942
+ const pointsByVariant = /* @__PURE__ */ new Map();
16943
+ const variants = new Set(
16944
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
16945
+ );
16946
+ for (const destination of scopedMetricDestinations) {
16947
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
16948
+ variants.add(variant);
16949
+ }
16950
+ }
16951
+ for (const includeSessionId of variants) {
16952
+ const observations = deriveMetricObservations({
16953
+ events: metricEvents,
16954
+ usage: ingest.usageObservations,
16955
+ resource: metricResource,
16956
+ includeSessionId,
16957
+ ...generationStarts === void 0 ? {} : { generationStarts },
16958
+ turnStart: (sessionId) => turnStarts.get(sessionId)
16959
+ });
16960
+ if (observations.length === 0) {
16961
+ continue;
16962
+ }
16963
+ pointsByVariant.set(
16964
+ includeSessionId,
16965
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
16966
+ perSession: includeSessionId,
16967
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
16968
+ })
16969
+ );
16970
+ }
16971
+ if (pointsByVariant.size === 0) {
16421
16972
  return void 0;
16422
16973
  }
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
16974
  const context = agreedContextAttributes(ingest.events);
16428
16975
  const results = await Promise.all(
16429
16976
  metricDestinations.map(async (destination) => {
16430
- const result = await destination.metrics.exportPoints(points, context).catch(
16977
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
16978
+ fallbackKey: scopedRepositoryFallback,
16979
+ includeSessionId: metricsPolicy.includeSessionId
16980
+ });
16981
+ if (points2.length === 0) {
16982
+ return { name: destination.name, accepted: 0, rejected: 0 };
16983
+ }
16984
+ const result = await destination.metrics.exportPoints(points2, context).catch(
16431
16985
  (thrown) => ({
16432
16986
  accepted: 0,
16433
- rejected: points.length,
16987
+ rejected: points2.length,
16434
16988
  errors: [
16435
16989
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
16436
16990
  ]
@@ -16440,7 +16994,8 @@ var createHookRuntime = (options) => {
16440
16994
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
16441
16995
  })
16442
16996
  );
16443
- return { points: points.length, destinations: results };
16997
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
16998
+ return { points, destinations: results };
16444
16999
  } catch (thrown) {
16445
17000
  diagnostics.push(stateDiagnostic(thrown));
16446
17001
  logger.warn("hook-derived metrics could not be recorded for this callback", {});