@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/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
  };
@@ -4094,7 +4278,8 @@ var parseClaudeCode = (input, context) => {
4094
4278
  status: "parsed",
4095
4279
  events: factory.events(),
4096
4280
  ...warnings.length === 0 ? {} : { warnings },
4097
- ...targetHints.size === 0 ? {} : { targetHints }
4281
+ ...targetHints.size === 0 ? {} : { targetHints },
4282
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
4098
4283
  };
4099
4284
  };
4100
4285
 
@@ -4959,6 +5144,13 @@ var deriveWorkspace = (context, payload) => {
4959
5144
  }
4960
5145
  return void 0;
4961
5146
  };
5147
+ var workspaceDirectoryOf = (payload) => {
5148
+ const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);
5149
+ if (roots.length > 0) {
5150
+ return roots.length === 1 ? roots[0] : void 0;
5151
+ }
5152
+ return payload.cwd !== void 0 && payload.cwd.length > 0 ? payload.cwd : void 0;
5153
+ };
4962
5154
  var invocationDiscriminator = (payload) => {
4963
5155
  switch (payload.hook_event_name) {
4964
5156
  case "sessionStart":
@@ -5418,11 +5610,13 @@ var createCursorAdapter = (options = {}) => {
5418
5610
  }
5419
5611
  }
5420
5612
  const targetHints = factory.targetHints();
5613
+ const workspaceDirectory = workspaceDirectoryOf(payload);
5421
5614
  return {
5422
5615
  status: "parsed",
5423
5616
  events: factory.events(),
5424
5617
  ...warnings.length === 0 ? {} : { warnings },
5425
- ...targetHints.size === 0 ? {} : { targetHints }
5618
+ ...targetHints.size === 0 ? {} : { targetHints },
5619
+ ...workspaceDirectory === void 0 ? {} : { workspaceDirectory }
5426
5620
  };
5427
5621
  };
5428
5622
  const hookResponse2 = (input) => {
@@ -6097,7 +6291,8 @@ var parse = (input, context) => {
6097
6291
  status: "parsed",
6098
6292
  events: factory.events(),
6099
6293
  ...warnings.length === 0 ? {} : { warnings },
6100
- ...targetHints.size === 0 ? {} : { targetHints }
6294
+ ...targetHints.size === 0 ? {} : { targetHints },
6295
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
6101
6296
  };
6102
6297
  };
6103
6298
  var hookResponse = () => SILENT_HOOK_RESPONSE;
@@ -7022,7 +7217,8 @@ var createGeminiCliAdapter = (options = {}) => {
7022
7217
  return {
7023
7218
  status: "parsed",
7024
7219
  events: factory.events(),
7025
- ...warnings.length === 0 ? {} : { warnings }
7220
+ ...warnings.length === 0 ? {} : { warnings },
7221
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
7026
7222
  };
7027
7223
  };
7028
7224
  const hookResponse2 = () => SILENT_HOOK_RESPONSE;
@@ -7291,7 +7487,12 @@ var createAntigravityAdapter = (options = {}) => {
7291
7487
  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"
7292
7488
  };
7293
7489
  }
7294
- return { status: "parsed", events: factory.events() };
7490
+ const [onlyWorkspacePath, ...otherWorkspacePaths] = payload.workspacePaths;
7491
+ return {
7492
+ status: "parsed",
7493
+ events: factory.events(),
7494
+ ...onlyWorkspacePath === void 0 || onlyWorkspacePath.length === 0 || otherWorkspacePaths.length > 0 ? {} : { workspaceDirectory: onlyWorkspacePath }
7495
+ };
7295
7496
  };
7296
7497
  const hookResponse2 = () => SILENT_HOOK_RESPONSE;
7297
7498
  return {
@@ -8138,6 +8339,28 @@ var classifyDurability = (input) => {
8138
8339
  };
8139
8340
  var isCommittable = (durability) => durability !== "lost";
8140
8341
  var MAX_ERROR_EVENTS = 8;
8342
+ var resolveWorkspaceRepositoryKey = async (locator, directory, budgetMillis) => {
8343
+ if (locator?.originRepositoryKey === void 0) {
8344
+ return void 0;
8345
+ }
8346
+ let timer;
8347
+ const deadline = new Promise((resolve5) => {
8348
+ timer = setTimeout(() => resolve5(void 0), Math.max(0, budgetMillis));
8349
+ timer.unref?.();
8350
+ });
8351
+ try {
8352
+ return await Promise.race([
8353
+ locator.originRepositoryKey(directory).catch(() => void 0),
8354
+ deadline
8355
+ ]);
8356
+ } catch {
8357
+ return void 0;
8358
+ } finally {
8359
+ if (timer !== void 0) {
8360
+ clearTimeout(timer);
8361
+ }
8362
+ }
8363
+ };
8141
8364
  var collectContentFacts = (event3) => {
8142
8365
  const facts = [];
8143
8366
  const push = (fact) => {
@@ -8781,7 +9004,8 @@ var createOtelHook = (deps) => {
8781
9004
  kind: "ready",
8782
9005
  batch: batch2,
8783
9006
  dropped: screened.dropped,
8784
- ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
9007
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints },
9008
+ ...parsed.workspaceDirectory === void 0 ? {} : { workspaceDirectory: parsed.workspaceDirectory }
8785
9009
  };
8786
9010
  };
8787
9011
  let prepared;
@@ -8849,11 +9073,19 @@ var createOtelHook = (deps) => {
8849
9073
  batch,
8850
9074
  !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
8851
9075
  );
9076
+ const workspaceRepositoryKey = !suppress && batch.length > 0 && deps.routeByWorkspaceRepository === true && prepared.workspaceDirectory !== void 0 ? await resolveWorkspaceRepositoryKey(
9077
+ deps.worktreeLocator,
9078
+ prepared.workspaceDirectory,
9079
+ deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
9080
+ ) : void 0;
8852
9081
  let emitted = 0;
8853
9082
  let exportRejected = 0;
8854
9083
  if (!suppress && batch.length > 0) {
8855
9084
  try {
8856
- const result = await deps.sink.emit(batch);
9085
+ const result = await deps.sink.emit(
9086
+ batch,
9087
+ workspaceRepositoryKey === void 0 ? void 0 : { workspaceRepositoryKey }
9088
+ );
8857
9089
  emitted = result.accepted;
8858
9090
  exportRejected = result.rejected;
8859
9091
  diagnostics.push(...result.errors);
@@ -8912,7 +9144,8 @@ var createOtelHook = (deps) => {
8912
9144
  durability,
8913
9145
  dropped,
8914
9146
  hookResponse: hookResponseFor(adapter, detection, "attributed", void 0, emitted, diagnostics),
8915
- diagnostics
9147
+ diagnostics,
9148
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey }
8916
9149
  };
8917
9150
  } catch (thrown) {
8918
9151
  const info = errorInfoFromThrown(thrown, { code: "internal-error", phase: "parsing" });
@@ -9011,15 +9244,16 @@ var MAX_WORKTREE_WALK_DEPTH = 128;
9011
9244
  var MAX_GIT_FILE_BYTES = 4096;
9012
9245
  var MAX_CACHE_ENTRIES = 1024;
9013
9246
  var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
9247
+ var MAX_GIT_CONFIG_BYTES = 64 * 1024;
9014
9248
  var MAX_BRANCH_NAME_LENGTH = 255;
9015
9249
  var ABSENT = Object.freeze({ kind: "absent" });
9016
9250
  var INVALID = Object.freeze({ kind: "invalid" });
9017
- var readBounded2 = async (filePath) => {
9251
+ var readBounded2 = async (filePath, maxBytes = MAX_GIT_FILE_BYTES) => {
9018
9252
  let handle;
9019
9253
  try {
9020
9254
  handle = await open4(filePath, "r");
9021
- const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
9022
- const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
9255
+ const buffer = Buffer.alloc(maxBytes);
9256
+ const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
9023
9257
  return buffer.subarray(0, bytesRead).toString("utf8");
9024
9258
  } catch {
9025
9259
  return void 0;
@@ -9047,6 +9281,60 @@ var parseGitDirFile = (content, worktreeRoot) => {
9047
9281
  );
9048
9282
  };
9049
9283
  var parseCommonDirFile = (content, gitDir) => resolveGitPath(firstLine(content), gitDir);
9284
+ var unquoteConfigValue = (raw) => {
9285
+ let value = "";
9286
+ let quoted = false;
9287
+ for (let index = 0; index < raw.length; index += 1) {
9288
+ const char = raw[index];
9289
+ if (char === "\\") {
9290
+ const next = raw[index + 1];
9291
+ if (next === void 0) {
9292
+ return void 0;
9293
+ }
9294
+ value += next === "n" ? "\n" : next === "t" ? " " : next;
9295
+ index += 1;
9296
+ } else if (char === '"') {
9297
+ quoted = !quoted;
9298
+ } else if (!quoted && (char === "#" || char === ";")) {
9299
+ break;
9300
+ } else {
9301
+ value += char;
9302
+ }
9303
+ }
9304
+ return quoted ? void 0 : value.trim();
9305
+ };
9306
+ var parseOriginRemoteUrl = (content) => {
9307
+ const lines = content.split(/\r?\n/);
9308
+ if (!content.endsWith("\n")) {
9309
+ lines.pop();
9310
+ }
9311
+ let inOrigin = false;
9312
+ for (const rawLine of lines) {
9313
+ const line = rawLine.trim();
9314
+ if (line.startsWith("[")) {
9315
+ const close = line.indexOf("]");
9316
+ const header = close === -1 ? "" : line.slice(1, close).trim();
9317
+ const rest = close === -1 ? "" : line.slice(close + 1).trim();
9318
+ inOrigin = /^remote\s+"origin"$/i.test(header) && header.endsWith('"origin"') || header.toLowerCase() === "remote.origin";
9319
+ if (!inOrigin || rest.length === 0 || rest.startsWith("#") || rest.startsWith(";")) {
9320
+ continue;
9321
+ }
9322
+ const entry2 = /^url\s*=(.*)$/i.exec(rest);
9323
+ if (entry2 !== null) {
9324
+ return unquoteConfigValue(entry2[1] ?? "");
9325
+ }
9326
+ continue;
9327
+ }
9328
+ if (!inOrigin) {
9329
+ continue;
9330
+ }
9331
+ const entry = /^url\s*=(.*)$/i.exec(line);
9332
+ if (entry !== null) {
9333
+ return unquoteConfigValue(entry[1] ?? "");
9334
+ }
9335
+ }
9336
+ return void 0;
9337
+ };
9050
9338
  var isMissing = async (filePath) => {
9051
9339
  try {
9052
9340
  await lstat(filePath);
@@ -9067,11 +9355,15 @@ var repositoryOf = async (worktreeRoot, gitDir) => {
9067
9355
  const commonDirFile = path5.join(gitDir, "commondir");
9068
9356
  const content = await readBounded2(commonDirFile);
9069
9357
  if (content === void 0) {
9070
- return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
9358
+ return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot, configDir: gitDir } : { kind: "linked" };
9071
9359
  }
9072
9360
  const commonDir = parseCommonDirFile(content, gitDir);
9073
9361
  const mainRoot = commonDir !== void 0 && path5.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path5.dirname(commonDir) : void 0;
9074
- return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
9362
+ return {
9363
+ kind: "linked",
9364
+ ...mainRoot === void 0 ? {} : { mainRoot },
9365
+ ...commonDir === void 0 ? {} : { configDir: commonDir }
9366
+ };
9075
9367
  };
9076
9368
  var probeDirectory = async (directory) => {
9077
9369
  const dotGit = path5.join(directory, ".git");
@@ -9096,12 +9388,21 @@ var probeDirectory = async (directory) => {
9096
9388
  return INVALID;
9097
9389
  }
9098
9390
  const branch = parseHeadBranch(head);
9099
- const repository = info.isDirectory() ? { kind: "main", mainRoot: directory } : await repositoryOf(directory, gitDir);
9391
+ const { configDir, ...repository } = info.isDirectory() ? { kind: "main", mainRoot: directory, configDir: gitDir } : await repositoryOf(directory, gitDir);
9100
9392
  return {
9101
9393
  kind: "worktree",
9102
- located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository }
9394
+ located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository },
9395
+ configDir: configDir ?? ""
9103
9396
  };
9104
9397
  };
9398
+ var readOriginRepositoryKey = async (configDir) => {
9399
+ if (configDir.length === 0) {
9400
+ return void 0;
9401
+ }
9402
+ const content = await readBounded2(path5.join(configDir, "config"), MAX_GIT_CONFIG_BYTES);
9403
+ const url = content === void 0 ? void 0 : parseOriginRemoteUrl(content);
9404
+ return url === void 0 ? void 0 : normalizeRepositoryKey(url);
9405
+ };
9105
9406
  var createFilesystemWorktreeLocator = (options = {}) => {
9106
9407
  const now = options.monotonicMillis ?? (() => performance.now());
9107
9408
  const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
@@ -9119,32 +9420,57 @@ var createFilesystemWorktreeLocator = (options = {}) => {
9119
9420
  cache.set(directory, { at, probe });
9120
9421
  return probe;
9121
9422
  };
9122
- const locate = async (absolutePath) => {
9123
- try {
9124
- if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
9423
+ const remoteCache = /* @__PURE__ */ new Map();
9424
+ const cachedOriginKey = (configDir) => {
9425
+ const hit = remoteCache.get(configDir);
9426
+ const at = now();
9427
+ if (hit !== void 0 && at - hit.at <= ttl) {
9428
+ return hit.key;
9429
+ }
9430
+ if (remoteCache.size >= MAX_CACHE_ENTRIES) {
9431
+ remoteCache.clear();
9432
+ }
9433
+ const key = readOriginRepositoryKey(configDir).catch(() => void 0);
9434
+ remoteCache.set(configDir, { at, key });
9435
+ return key;
9436
+ };
9437
+ const findWorktree = async (absolutePath) => {
9438
+ if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
9439
+ return void 0;
9440
+ }
9441
+ let directory = path5.resolve(absolutePath);
9442
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
9443
+ const probe = await cachedProbe(directory);
9444
+ if (probe.kind === "worktree") {
9445
+ return probe;
9446
+ }
9447
+ if (probe.kind === "invalid") {
9125
9448
  return void 0;
9126
9449
  }
9127
- let directory = path5.resolve(absolutePath);
9128
- for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
9129
- const probe = await cachedProbe(directory);
9130
- if (probe.kind === "worktree") {
9131
- return probe.located;
9132
- }
9133
- if (probe.kind === "invalid") {
9134
- return void 0;
9135
- }
9136
- const parent = path5.dirname(directory);
9137
- if (parent === directory) {
9138
- return void 0;
9139
- }
9140
- directory = parent;
9450
+ const parent = path5.dirname(directory);
9451
+ if (parent === directory) {
9452
+ return void 0;
9141
9453
  }
9454
+ directory = parent;
9455
+ }
9456
+ return void 0;
9457
+ };
9458
+ const locate = async (absolutePath) => {
9459
+ try {
9460
+ return (await findWorktree(absolutePath))?.located;
9461
+ } catch {
9142
9462
  return void 0;
9463
+ }
9464
+ };
9465
+ const originRepositoryKey = async (absolutePath) => {
9466
+ try {
9467
+ const probe = await findWorktree(absolutePath);
9468
+ return probe === void 0 ? void 0 : await cachedOriginKey(probe.configDir);
9143
9469
  } catch {
9144
9470
  return void 0;
9145
9471
  }
9146
9472
  };
9147
- return { locate };
9473
+ return { locate, originRepositoryKey };
9148
9474
  };
9149
9475
 
9150
9476
  // src/lifecycle/dedup.ts
@@ -9364,7 +9690,7 @@ import {
9364
9690
  } from "@opentelemetry/semantic-conventions/incubating";
9365
9691
 
9366
9692
  // src/version.ts
9367
- var VERSION = "0.13.2";
9693
+ var VERSION = "0.14.1";
9368
9694
 
9369
9695
  // src/telemetry/export-identity.ts
9370
9696
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9937,6 +10263,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
9937
10263
  };
9938
10264
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9939
10265
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
10266
+ var spanEndEdgesOf = (events) => {
10267
+ const layout = layoutBatch(events);
10268
+ const ends = /* @__PURE__ */ new Map();
10269
+ for (const [eventId, groupKey] of layout.groupOf) {
10270
+ const end = layout.groups.get(groupKey)?.end;
10271
+ if (end !== void 0) {
10272
+ ends.set(eventId, end);
10273
+ }
10274
+ }
10275
+ return ends;
10276
+ };
9940
10277
  var canonicalEventTraceIdentities = (events, options = {}) => {
9941
10278
  const layout = layoutBatch(events);
9942
10279
  const correlations = indexCorrelations(options.correlations);
@@ -13243,14 +13580,20 @@ var createSignalFanout = (options) => {
13243
13580
  };
13244
13581
  var shareCorrelationPerBatch = (correlate) => {
13245
13582
  let pending;
13246
- return (events) => {
13247
- if (pending?.events === events) {
13583
+ const resolve5 = (events) => {
13584
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
13248
13585
  return pending.result;
13249
13586
  }
13250
13587
  const result = correlate(events);
13251
- pending = { events, result };
13588
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
13252
13589
  return result;
13253
13590
  };
13591
+ const alias = (subset, batch) => {
13592
+ if (pending?.events === batch && subset !== batch) {
13593
+ pending.aliases.add(subset);
13594
+ }
13595
+ };
13596
+ return Object.assign(resolve5, { alias });
13254
13597
  };
13255
13598
 
13256
13599
  // src/telemetry/durable-metric-spool.ts
@@ -13603,6 +13946,117 @@ var createOtlpMetricSink = (options) => {
13603
13946
  };
13604
13947
  };
13605
13948
 
13949
+ // src/telemetry/destination-scope.ts
13950
+ var DISCLOSURE_RANK2 = Object.freeze({
13951
+ omitted: 0,
13952
+ masked: 1,
13953
+ redacted: 2,
13954
+ raw: 3
13955
+ });
13956
+ var omitRestrictedContent = (fact, mode) => {
13957
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
13958
+ return fact;
13959
+ }
13960
+ const { text, ...rest } = fact;
13961
+ void text;
13962
+ return { ...rest, disclosure: "omitted", truncated: false };
13963
+ };
13964
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
13965
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
13966
+ var repositoryUrlForKey = (key) => `https://${key}`;
13967
+ var hasOwnStamp = (attributes) => attributes?.[ATTR_VCS_REPOSITORY_URL_FULL] !== void 0;
13968
+ var withRoutedRepository = (event3, key) => hasOwnStamp(event3.contextAttributes) ? event3 : {
13969
+ ...event3,
13970
+ contextAttributes: { ...event3.contextAttributes, [ATTR_VCS_REPOSITORY_URL_FULL]: repositoryUrlForKey(key) }
13971
+ };
13972
+ var eventRepositoryKey = (event3, fallbackKey) => {
13973
+ const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
13974
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
13975
+ };
13976
+ var pointRepositoryKey = (point, fallbackKey) => {
13977
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
13978
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
13979
+ };
13980
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
13981
+ var restrictEventContent = (event3, mode, restrict) => {
13982
+ switch (event3.type) {
13983
+ case "prompt.submitted":
13984
+ return event3.content === void 0 ? event3 : { ...event3, content: restrict(event3.content, mode) };
13985
+ case "generation.start": {
13986
+ const inputContent = restrictFacts(event3.inputContent, mode, restrict);
13987
+ return inputContent === void 0 ? event3 : { ...event3, inputContent };
13988
+ }
13989
+ case "generation.end": {
13990
+ const outputContent = restrictFacts(event3.outputContent, mode, restrict);
13991
+ return outputContent === void 0 ? event3 : { ...event3, outputContent };
13992
+ }
13993
+ case "tool.start":
13994
+ return event3.input === void 0 ? event3 : { ...event3, input: restrict(event3.input, mode) };
13995
+ case "tool.end":
13996
+ return event3.output === void 0 ? event3 : { ...event3, output: restrict(event3.output, mode) };
13997
+ case "error.raised":
13998
+ return event3.message === void 0 ? event3 : { ...event3, message: restrict(event3.message, mode) };
13999
+ default:
14000
+ return event3;
14001
+ }
14002
+ };
14003
+ var routeEventsToScopes = (events, scopes, options) => {
14004
+ const ends = spanEndEdgesOf(events);
14005
+ const fallbackKey = options.workspaceRepositoryKey ?? options.resourceRepositoryKey;
14006
+ const traces = [];
14007
+ const logs = [];
14008
+ let unchanged = true;
14009
+ for (const event3 of events) {
14010
+ const anchor = ends.get(event3.eventId) ?? event3;
14011
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, fallbackKey));
14012
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
14013
+ unchanged = false;
14014
+ }
14015
+ if (scope === void 0) {
14016
+ continue;
14017
+ }
14018
+ const lowered = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
14019
+ const restricted = hasOwnStamp(anchor.contextAttributes) || fallbackKey === void 0 ? lowered : withRoutedRepository(lowered, fallbackKey);
14020
+ if (restricted !== event3) {
14021
+ unchanged = false;
14022
+ }
14023
+ if (scope.signals.traces) {
14024
+ traces.push(restricted);
14025
+ }
14026
+ if (scope.signals.logs) {
14027
+ logs.push(restricted);
14028
+ }
14029
+ }
14030
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
14031
+ };
14032
+ var routePointsToScopes = (scopes, pointsFor, options) => {
14033
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
14034
+ const kept = [];
14035
+ for (const variant of [true, false]) {
14036
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
14037
+ continue;
14038
+ }
14039
+ for (const point of pointsFor(variant) ?? []) {
14040
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
14041
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
14042
+ kept.push(
14043
+ hasOwnStamp(point.attributes) || options.fallbackKey === void 0 ? point : {
14044
+ ...point,
14045
+ attributes: {
14046
+ ...point.attributes,
14047
+ [ATTR_VCS_REPOSITORY_URL_FULL]: repositoryUrlForKey(options.fallbackKey)
14048
+ }
14049
+ }
14050
+ );
14051
+ }
14052
+ }
14053
+ }
14054
+ return kept;
14055
+ };
14056
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
14057
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
14058
+ );
14059
+
13606
14060
  // src/telemetry/export-destinations.ts
13607
14061
  var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
13608
14062
  traces: `destinations/${destination}/spool`,
@@ -13669,6 +14123,8 @@ var createExportDestinationSinks = (options) => {
13669
14123
  ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
13670
14124
  probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
13671
14125
  });
14126
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
14127
+ const restrict = options.restrictContent ?? omitRestrictedContent;
13672
14128
  for (const destination of resolveExportDestinations(options.exporter)) {
13673
14129
  let headers;
13674
14130
  let logHeaders;
@@ -13758,24 +14214,59 @@ var createExportDestinationSinks = (options) => {
13758
14214
  metrics,
13759
14215
  ...spool === void 0 ? {} : { spool },
13760
14216
  ...logSpool === void 0 ? {} : { logSpool },
13761
- ...metricSpool === void 0 ? {} : { metricSpool }
14217
+ ...metricSpool === void 0 ? {} : { metricSpool },
14218
+ ...destination.scopes === void 0 ? {} : {
14219
+ scopes: destination.scopes,
14220
+ route: (events, workspaceRepositoryKey) => routeEventsToScopes(events, destination.scopes ?? [], {
14221
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
14222
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey },
14223
+ restrict
14224
+ })
14225
+ }
13762
14226
  });
13763
14227
  }
13764
14228
  return { destinations, skipped };
13765
14229
  };
13766
- var createDestinationFanout = (destinations) => {
14230
+ var createScopedFanout = (destination, correlate) => {
14231
+ const route = destination.route;
14232
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
14233
+ if (route === void 0) {
14234
+ return unscoped;
14235
+ }
14236
+ const none2 = { accepted: 0, rejected: 0, errors: [] };
14237
+ return {
14238
+ ...unscoped,
14239
+ emit: async (events, emitOptions) => {
14240
+ const batch = route(events, emitOptions?.workspaceRepositoryKey);
14241
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
14242
+ await correlate(events);
14243
+ correlate.alias(batch.traces, events);
14244
+ correlate.alias(batch.logs, events);
14245
+ }
14246
+ const traces = batch.traces.length === 0 ? none2 : await destination.traces.emit(batch.traces);
14247
+ const logs = batch.logs.length === 0 ? none2 : await destination.logs.emit(batch.logs);
14248
+ return {
14249
+ accepted: traces.accepted + logs.accepted,
14250
+ rejected: traces.rejected + logs.rejected,
14251
+ errors: [...traces.errors, ...logs.errors]
14252
+ };
14253
+ }
14254
+ };
14255
+ };
14256
+ var createDestinationFanout = (destinations, options = {}) => {
13767
14257
  const fanouts = destinations.map((destination) => ({
13768
14258
  name: destination.name,
13769
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
14259
+ sink: createScopedFanout(destination, options.correlate)
13770
14260
  }));
13771
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
14261
+ const scoped = destinations.some((destination) => destination.route !== void 0);
14262
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
13772
14263
  if (only !== void 0) {
13773
14264
  return only.sink;
13774
14265
  }
13775
- const emit = async (events) => {
14266
+ const emit = async (events, emitOptions) => {
13776
14267
  const results = await Promise.all(
13777
14268
  fanouts.map(
13778
- (fanout) => fanout.sink.emit(events).catch(
14269
+ (fanout) => fanout.sink.emit(events, emitOptions).catch(
13779
14270
  (thrown) => ({
13780
14271
  accepted: 0,
13781
14272
  rejected: events.length,
@@ -13889,7 +14380,8 @@ var createHookRuntime = (options) => {
13889
14380
  // has always been governed by.
13890
14381
  allowRawContent: privacy.policy.allowRawContent
13891
14382
  },
13892
- correlate
14383
+ correlate,
14384
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
13893
14385
  });
13894
14386
  const primary = exportDestinations.destinations[0];
13895
14387
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -13906,7 +14398,7 @@ var createHookRuntime = (options) => {
13906
14398
  });
13907
14399
  const spool = primary?.spool;
13908
14400
  const logSpool = primary?.logSpool;
13909
- const sink = createDestinationFanout(exportDestinations.destinations);
14401
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
13910
14402
  const hookDeps = {
13911
14403
  stateStore,
13912
14404
  config: options.config,
@@ -13936,7 +14428,12 @@ var createHookRuntime = (options) => {
13936
14428
  })(),
13937
14429
  ...options.worktreeLocator === null ? {} : {
13938
14430
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
13939
- }
14431
+ },
14432
+ // Only a scoped destination routes by repository, so only then is the session
14433
+ // directory's remote read at all.
14434
+ routeByWorkspaceRepository: exportDestinations.destinations.some(
14435
+ (destination) => destination.scopes !== void 0
14436
+ )
13940
14437
  };
13941
14438
  const hook = createOtelHook({ ...hookDeps, sink });
13942
14439
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
@@ -13947,6 +14444,8 @@ var createHookRuntime = (options) => {
13947
14444
  (destination) => destination.metrics.enabled
13948
14445
  );
13949
14446
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
14447
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
14448
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
13950
14449
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
13951
14450
  if (deliveryRetentionMillis < staleClaimMillis) {
13952
14451
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -14012,28 +14511,64 @@ var createHookRuntime = (options) => {
14012
14511
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
14013
14512
  }
14014
14513
  }
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) {
14514
+ const resourceFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
14515
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : ingest.workspaceRepositoryKey ?? resourceFallback;
14516
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
14517
+ const metricEvents = resourceFallback === void 0 || ingest.workspaceRepositoryKey !== void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
14518
+ (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
14519
+ ...event3,
14520
+ contextAttributes: {
14521
+ ...event3.contextAttributes,
14522
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
14523
+ }
14524
+ } : event3
14525
+ );
14526
+ const pointsByVariant = /* @__PURE__ */ new Map();
14527
+ const variants = new Set(
14528
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
14529
+ );
14530
+ for (const destination of scopedMetricDestinations) {
14531
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
14532
+ variants.add(variant);
14533
+ }
14534
+ }
14535
+ for (const includeSessionId of variants) {
14536
+ const observations = deriveMetricObservations({
14537
+ events: metricEvents,
14538
+ usage: ingest.usageObservations,
14539
+ resource: metricResource,
14540
+ includeSessionId,
14541
+ ...generationStarts === void 0 ? {} : { generationStarts },
14542
+ turnStart: (sessionId) => turnStarts.get(sessionId)
14543
+ });
14544
+ if (observations.length === 0) {
14545
+ continue;
14546
+ }
14547
+ pointsByVariant.set(
14548
+ includeSessionId,
14549
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
14550
+ perSession: includeSessionId,
14551
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
14552
+ })
14553
+ );
14554
+ }
14555
+ if (pointsByVariant.size === 0) {
14024
14556
  return void 0;
14025
14557
  }
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
14558
  const context = agreedContextAttributes(ingest.events);
14031
14559
  const results = await Promise.all(
14032
14560
  metricDestinations.map(async (destination) => {
14033
- const result = await destination.metrics.exportPoints(points, context).catch(
14561
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
14562
+ fallbackKey: scopedRepositoryFallback,
14563
+ includeSessionId: metricsPolicy.includeSessionId
14564
+ });
14565
+ if (points2.length === 0) {
14566
+ return { name: destination.name, accepted: 0, rejected: 0 };
14567
+ }
14568
+ const result = await destination.metrics.exportPoints(points2, context).catch(
14034
14569
  (thrown) => ({
14035
14570
  accepted: 0,
14036
- rejected: points.length,
14571
+ rejected: points2.length,
14037
14572
  errors: [
14038
14573
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
14039
14574
  ]
@@ -14043,7 +14578,8 @@ var createHookRuntime = (options) => {
14043
14578
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
14044
14579
  })
14045
14580
  );
14046
- return { points: points.length, destinations: results };
14581
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
14582
+ return { points, destinations: results };
14047
14583
  } catch (thrown) {
14048
14584
  diagnostics.push(stateDiagnostic(thrown));
14049
14585
  logger.warn("hook-derived metrics could not be recorded for this callback", {});
@@ -15806,11 +16342,13 @@ var planProviderRegistration = (input) => {
15806
16342
  };
15807
16343
  };
15808
16344
  export {
16345
+ ALL_REPOSITORIES,
15809
16346
  ANTIGRAVITY_CAPABILITIES,
15810
16347
  ANTIGRAVITY_HOOK_EVENT_NAMES,
15811
16348
  ANTIGRAVITY_PROMOTION_GATES,
15812
16349
  ANTIGRAVITY_PROVIDER_ID,
15813
16350
  ANTIGRAVITY_PROVIDER_MATURITY,
16351
+ ATTR_VCS_REPOSITORY_URL_FULL,
15814
16352
  BUILT_IN_PROVIDERS,
15815
16353
  CANONICAL_EVENT_TYPES,
15816
16354
  CANONICAL_SCHEMA_VERSION,
@@ -15902,6 +16440,7 @@ export {
15902
16440
  MAX_DELIVERY_COMPONENTS,
15903
16441
  MAX_DELIVERY_GAPS,
15904
16442
  MAX_DESTINATION_HEADERS,
16443
+ MAX_DESTINATION_SCOPES,
15905
16444
  MAX_EXPORT_DESTINATIONS,
15906
16445
  MAX_EXTENSION_ENTRIES,
15907
16446
  MAX_IDENTIFIER_LENGTH,
@@ -15910,9 +16449,11 @@ export {
15910
16449
  MAX_LOG_RECORDS_PER_EVENT,
15911
16450
  MAX_OTLP_HEADERS,
15912
16451
  MAX_RECOVERED_START_ATTRIBUTES,
16452
+ MAX_REPOSITORY_REFERENCE_LENGTH,
15913
16453
  MAX_RESOURCE_ATTRIBUTES,
15914
16454
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
15915
16455
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
16456
+ MAX_SCOPE_REPOSITORIES,
15916
16457
  MAX_SESSION_CONTEXT_SEGMENTS,
15917
16458
  MAX_TARGET_HINT_PATHS,
15918
16459
  MAX_TARGET_PATH_LENGTH,
@@ -16049,6 +16590,7 @@ export {
16049
16590
  describeResolvedConfig,
16050
16591
  describeResourceAttributeNames,
16051
16592
  describeThrown,
16593
+ destinationScopeSchema,
16052
16594
  detectDocumentFormat,
16053
16595
  detectionConfidenceSchema,
16054
16596
  detectionPolicySchema,
@@ -16065,6 +16607,7 @@ export {
16065
16607
  errorRaisedEventSchema,
16066
16608
  errorSeveritySchema,
16067
16609
  eventIdSchema,
16610
+ eventRepositoryKey,
16068
16611
  eventUsage,
16069
16612
  exportDestinationSchema,
16070
16613
  exportDestinationsSchema,
@@ -16107,6 +16650,7 @@ export {
16107
16650
  logSignalsForLifecycleEvents,
16108
16651
  logsPolicySchema,
16109
16652
  managedHookPredicate,
16653
+ matchDestinationScope,
16110
16654
  mergeAntigravityHookRegistration,
16111
16655
  mergeClaudeHookRegistration,
16112
16656
  mergeCodexHookRegistration,
@@ -16118,8 +16662,10 @@ export {
16118
16662
  minimumStaleClaimMillis,
16119
16663
  modelDescriptorSchema,
16120
16664
  nonEmptyStringSchema,
16665
+ normalizeRepositoryKey,
16121
16666
  normalizeUsage,
16122
16667
  normalizeUsageOrThrow,
16668
+ omitRestrictedContent,
16123
16669
  otelHookConfigPatchSchema,
16124
16670
  otelHookConfigSchema,
16125
16671
  otelHookErrorCodeSchema,
@@ -16132,10 +16678,12 @@ export {
16132
16678
  parseGitDirFile,
16133
16679
  parseHeadBranch,
16134
16680
  parseHeaderValueReference,
16681
+ parseOriginRemoteUrl,
16135
16682
  parseOtlpHeadersValue,
16136
16683
  parseResourceAttributesValue,
16137
16684
  parseSessionContextFile,
16138
16685
  planProviderRegistration,
16686
+ pointRepositoryKey,
16139
16687
  privacyLimitsSchema,
16140
16688
  privacyPolicySchema,
16141
16689
  promptSubmittedEventSchema,
@@ -16172,6 +16720,7 @@ export {
16172
16720
  resolveConfig,
16173
16721
  resolveDeliveryIdentity,
16174
16722
  resolveDestinationHeaders,
16723
+ resolveDestinationScopes,
16175
16724
  resolveEventTargets,
16176
16725
  resolveExportDestinations,
16177
16726
  resolveInstallPath,
@@ -16183,6 +16732,10 @@ export {
16183
16732
  resolvedProviderIdSchema,
16184
16733
  resourceAttributeValueSchema,
16185
16734
  resourceAttributesSchema,
16735
+ resourceRepositoryKey,
16736
+ restrictEventContent,
16737
+ routeEventsToScopes,
16738
+ routePointsToScopes,
16186
16739
  runRegistrationLifecycle,
16187
16740
  sanitizeResourceAttributes,
16188
16741
  sanitizeSessionContextAttributes,
@@ -16195,6 +16748,7 @@ export {
16195
16748
  sessionCwdHint,
16196
16749
  sessionEndEventSchema,
16197
16750
  sessionIdSchema,
16751
+ sessionIdVariantsFor,
16198
16752
  sessionStartEventSchema,
16199
16753
  shareCorrelationPerBatch,
16200
16754
  sourceProvenanceSchema,