@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
@@ -1,6 +1,6 @@
1
- import { i as DetectionPolicy } from './schema-CD61uW99.js';
1
+ import { i as DetectionPolicy } from './schema-oRsbo7WO.js';
2
2
  import { OtelHookErrorInfo } from './errors.js';
3
- import { P as ProviderAdapter, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext } from './adapter-DyCb7y1N.js';
3
+ import { P as ProviderAdapter, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext } from './adapter-But5fFCk.js';
4
4
 
5
5
  type DetectionCandidate = {
6
6
  readonly adapter: ProviderAdapter;
package/dist/runtime.d.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { c as LogLevel, d as Logger, W as WorktreeLocator, S as SessionContextReader, h as SessionContextSegment } from './ports-DhpSDIkp.js';
2
- export { A as AppliedDelivery, C as Clock, E as EventIdSeed, I as IdGenerator, a as InvocationIdSeed, L as LOG_LEVEL_RANK, b as LocatedWorktree, P as PayloadEnricher, e as PayloadEnrichment, f as PayloadEnrichmentInput, R as ReadCursor, g as SessionContextRequest, i as StateRecord, j as StateStore, k as StateValue, T as TelemetryEmitResult, l as TelemetrySink, m as appliedDeliverySchema, n as logLevelSchema, s as stateRecordSchema, o as stateValueSchema } from './ports-DhpSDIkp.js';
3
- export { D as DeterministicIdOptions, F as FixedClock, a as FixedClockOptions, I as InMemoryStateStore, b as InMemoryStateStoreOptions, L as LogRecord, R as RecordingLogger, c as RecordingTelemetrySink, d as RecordingTelemetrySinkOptions, e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, h as createNullTelemetrySink, i as createRandomIdGenerator, j as createRecordingLogger, k as createRecordingTelemetrySink, l as createSystemClock } from './memory-B3r6sZtC.js';
4
- export { C as CumulativeUsageSeries, D as DeliveryDurability, a as DeliveryOrigin, b as DeliveryResolution, c as DeliveryUnavailableReason, H as HookIngestInput, d as HookIngestOptions, e as HookIngestOutcome, O as OtelHook, f as OtelHookDependencies, R as ResolvedDeliveryIdentity, U as UsageObservation, g as UsageScope, h as classifyDurability, i as createOtelHook, j as hostDeliveryIdentity, k as isCommittable, r as resolveDeliveryIdentity, u as usageScopeSchema } from './hook-CKLpgrYP.js';
1
+ import { c as LogLevel, d as Logger, W as WorktreeLocator, S as SessionContextReader, h as SessionContextSegment } from './ports-qZTwK-z2.js';
2
+ export { A as AppliedDelivery, C as Clock, E as EventIdSeed, I as IdGenerator, a as InvocationIdSeed, L as LOG_LEVEL_RANK, b as LocatedWorktree, P as PayloadEnricher, e as PayloadEnrichment, f as PayloadEnrichmentInput, R as ReadCursor, g as SessionContextRequest, i as StateRecord, j as StateStore, k as StateValue, T as TelemetryEmitOptions, l as TelemetryEmitResult, m as TelemetrySink, n as appliedDeliverySchema, o as logLevelSchema, s as stateRecordSchema, p as stateValueSchema } from './ports-qZTwK-z2.js';
3
+ export { D as DeterministicIdOptions, F as FixedClock, a as FixedClockOptions, I as InMemoryStateStore, b as InMemoryStateStoreOptions, L as LogRecord, R as RecordingLogger, c as RecordingTelemetrySink, d as RecordingTelemetrySinkOptions, e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, h as createNullTelemetrySink, i as createRandomIdGenerator, j as createRecordingLogger, k as createRecordingTelemetrySink, l as createSystemClock } from './memory-gipZUiXP.js';
4
+ export { C as CumulativeUsageSeries, D as DeliveryDurability, a as DeliveryOrigin, b as DeliveryResolution, c as DeliveryUnavailableReason, H as HookIngestInput, d as HookIngestOptions, e as HookIngestOutcome, O as OtelHook, f as OtelHookDependencies, R as ResolvedDeliveryIdentity, U as UsageObservation, g as UsageScope, h as classifyDurability, i as createOtelHook, j as hostDeliveryIdentity, k as isCommittable, r as resolveDeliveryIdentity, u as usageScopeSchema } from './hook-D7XABd4f.js';
5
5
  import { b as CanonicalEvent, u as TargetHint } from './events-fcomX6d5.js';
6
6
  import { d as EventId } from './primitives-CJ8-rn-f.js';
7
- import { P as PrivacyService } from './service-CbI9CObT.js';
7
+ import { P as PrivacyService } from './service-DySC7KQM.js';
8
8
  import 'zod';
9
9
  import './errors.js';
10
10
  import './taxonomy-DwhTtuWd.js';
11
- import './schema-CD61uW99.js';
11
+ import './schema-oRsbo7WO.js';
12
12
  import './identity-BrVBs901.js';
13
- import './adapter-DyCb7y1N.js';
13
+ import './adapter-But5fFCk.js';
14
14
  import './policy-CimmCfRp.js';
15
15
  import './content-M9xIKG7h.js';
16
- import './registry-DM-4YvIA.js';
16
+ import './registry-D9rmMYxw.js';
17
17
 
18
18
  declare const createNullLogger: () => Logger;
19
19
  type StderrLoggerOptions = {
@@ -60,6 +60,14 @@ declare const createStderrLogger: (options?: StderrLoggerOptions) => Logger;
60
60
  * does not skip past it to an enclosing repository that the event did not
61
61
  * target. A repository that cannot be named costs only `mainRoot`.
62
62
  *
63
+ * The repository's `origin` remote is read on request only
64
+ * ({@link WorktreeLocator.originRepositoryKey}), from the `config` file of the
65
+ * repository's common git dir — the git dir itself when there is no `commondir`.
66
+ * It is reduced to its repository key at once (`normalizeRepositoryKey`), so the
67
+ * URL itself, with any credentials in it, never leaves this module. Includes,
68
+ * `insteadOf` rewrites and per-worktree config are not followed: a remote that
69
+ * needs them names no key, which is the safe answer for routing.
70
+ *
63
71
  * Everything is bounded: walk depth, bytes read per file, and cache size. Every
64
72
  * failure is `undefined`; nothing throws.
65
73
  */
@@ -73,6 +81,13 @@ declare const parseHeadBranch: (head: string) => string | undefined;
73
81
  declare const parseGitDirFile: (content: string, worktreeRoot: string) => string | undefined;
74
82
  /** A `commondir` file → the common git dir it names, resolved against the git dir. */
75
83
  declare const parseCommonDirFile: (content: string, gitDir: string) => string | undefined;
84
+ /**
85
+ * The first `url` of `[remote "origin"]` in a git `config` file's text, or
86
+ * `undefined`. Section and key names are case-insensitive as in git; the
87
+ * subsection name is not. A final line without its newline may be cut by the
88
+ * read bound, so it is not trusted.
89
+ */
90
+ declare const parseOriginRemoteUrl: (content: string) => string | undefined;
76
91
  type FilesystemWorktreeLocatorOptions = {
77
92
  /** Monotonic milliseconds for cache expiry. Defaults to `performance.now()`. */
78
93
  readonly monotonicMillis?: () => number;
@@ -209,4 +224,4 @@ type DirectorySessionContextReaderOptions = {
209
224
  */
210
225
  declare const createDirectorySessionContextReader: (options: DirectorySessionContextReaderOptions) => SessionContextReader;
211
226
 
212
- export { DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS, DEFAULT_SESSION_CONTEXT_MAX_BYTES, DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS, DEFAULT_WORKTREE_CACHE_TTL_MILLIS, type DirectorySessionContextReaderOptions, type FilesystemWorktreeLocatorOptions, LogLevel, Logger, MAX_SESSION_CONTEXT_SEGMENTS, MAX_WORKTREE_WALK_DEPTH, type ResolveEventTargetsInput, type ResolveEventTargetsResult, SESSION_CONTEXT_AGENT_TOOLS, SESSION_CONTEXT_FILE_VERSION, SessionContextReader, SessionContextSegment, type StderrLoggerOptions, WorktreeLocator, createDirectorySessionContextReader, createFilesystemWorktreeLocator, createNullLogger, createStderrLogger, isReservedSessionContextKey, isSessionContextFileName, parseCommonDirFile, parseGitDirFile, parseHeadBranch, parseSessionContextFile, resolveEventTargets, sanitizeSessionContextAttributes, segmentInForce, sessionContextAgentTool, sessionContextFilePath, stampSessionContext };
227
+ export { DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS, DEFAULT_SESSION_CONTEXT_MAX_BYTES, DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS, DEFAULT_WORKTREE_CACHE_TTL_MILLIS, type DirectorySessionContextReaderOptions, type FilesystemWorktreeLocatorOptions, LogLevel, Logger, MAX_SESSION_CONTEXT_SEGMENTS, MAX_WORKTREE_WALK_DEPTH, type ResolveEventTargetsInput, type ResolveEventTargetsResult, SESSION_CONTEXT_AGENT_TOOLS, SESSION_CONTEXT_FILE_VERSION, SessionContextReader, SessionContextSegment, type StderrLoggerOptions, WorktreeLocator, createDirectorySessionContextReader, createFilesystemWorktreeLocator, createNullLogger, createStderrLogger, isReservedSessionContextKey, isSessionContextFileName, parseCommonDirFile, parseGitDirFile, parseHeadBranch, parseOriginRemoteUrl, parseSessionContextFile, resolveEventTargets, sanitizeSessionContextAttributes, segmentInForce, sessionContextAgentTool, sessionContextFilePath, stampSessionContext };
package/dist/runtime.js CHANGED
@@ -1471,6 +1471,59 @@ var OTLP_HEADER_VARIABLES = Object.freeze({
1471
1471
  logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1472
1472
  });
1473
1473
 
1474
+ // src/config/repository-key.ts
1475
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
1476
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
1477
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
1478
+ var trimTrailingSlashes = (value) => {
1479
+ let end = value.length;
1480
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1481
+ return value.slice(0, end);
1482
+ };
1483
+ var keyOf = (host, pathname) => {
1484
+ const withoutSlashes = trimTrailingSlashes(pathname);
1485
+ const cleanedPath = trimTrailingSlashes(
1486
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
1487
+ );
1488
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
1489
+ return void 0;
1490
+ }
1491
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
1492
+ return `${host}${withSlash}`.toLowerCase();
1493
+ };
1494
+ var normalizeRepositoryKey = (reference) => {
1495
+ const trimmed = reference.trim();
1496
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
1497
+ return void 0;
1498
+ }
1499
+ if (SCHEME_PATTERN.test(trimmed)) {
1500
+ let url;
1501
+ try {
1502
+ url = new URL(trimmed);
1503
+ } catch {
1504
+ return void 0;
1505
+ }
1506
+ if (url.protocol === "file:") {
1507
+ return void 0;
1508
+ }
1509
+ return keyOf(url.hostname, url.pathname);
1510
+ }
1511
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
1512
+ return void 0;
1513
+ }
1514
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
1515
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
1516
+ const [, host, pathPart] = scp;
1517
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
1518
+ }
1519
+ try {
1520
+ const url = new URL(`https://${trimmed}`);
1521
+ return keyOf(url.hostname, url.pathname);
1522
+ } catch {
1523
+ return void 0;
1524
+ }
1525
+ };
1526
+
1474
1527
  // src/config/destinations.ts
1475
1528
  var DEFAULT_DESTINATION_NAME = "default";
1476
1529
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
@@ -1489,6 +1542,30 @@ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1489
1542
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1490
1543
  );
1491
1544
  var endpointSchema = z13.string().url().max(2048);
1545
+ var MAX_DESTINATION_SCOPES = 64;
1546
+ var MAX_SCOPE_REPOSITORIES = 256;
1547
+ var ALL_REPOSITORIES = "*";
1548
+ var repositoryReferenceSchema = z13.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
1549
+ (value) => normalizeRepositoryKey(value) !== void 0,
1550
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
1551
+ );
1552
+ var destinationScopeSchema = z13.strictObject({
1553
+ /**
1554
+ * Repository URLs (any spelling of the remote; compared by host and path,
1555
+ * case-insensitively, without `.git`), or `"*"` for every record that names
1556
+ * a repository. A record that names none never matches a scope.
1557
+ */
1558
+ repositories: z13.union([
1559
+ z13.literal(ALL_REPOSITORIES),
1560
+ z13.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
1561
+ ]),
1562
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
1563
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1564
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
1565
+ contentMode: contentModeSchema.optional(),
1566
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
1567
+ includeSessionId: z13.boolean().optional()
1568
+ });
1492
1569
  var exportDestinationSchema = z13.strictObject({
1493
1570
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1494
1571
  name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -1522,7 +1599,15 @@ var exportDestinationSchema = z13.strictObject({
1522
1599
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
1523
1600
  * default: a destination receives hook-derived metrics only when it lists them.
1524
1601
  */
1525
- signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1602
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1603
+ /**
1604
+ * Per-repository filter. Absent: every record goes to this destination, as
1605
+ * before scopes existed. Present: a record goes only when its repository
1606
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
1607
+ * decides its signals, content mode, and session id — and a record that
1608
+ * names no repository is not sent here at all.
1609
+ */
1610
+ scopes: z13.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
1526
1611
  }).refine(
1527
1612
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1528
1613
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -1821,6 +1906,23 @@ var DEFAULT_CONFIG = Object.freeze({
1821
1906
 
1822
1907
  // src/privacy/service.ts
1823
1908
  import { createHash as createHash2 } from "crypto";
1909
+ var DISCLOSURE_RANK = Object.freeze({
1910
+ omitted: 0,
1911
+ masked: 1,
1912
+ redacted: 2,
1913
+ raw: 3
1914
+ });
1915
+ var WHITESPACE = /\s/u;
1916
+ var withoutTrailingToken = (text) => {
1917
+ let end = text.length;
1918
+ while (end > 0) {
1919
+ const low = text.charCodeAt(end - 1);
1920
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
1921
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
1922
+ end -= width;
1923
+ }
1924
+ return text.slice(0, end);
1925
+ };
1824
1926
  var compilePatterns = (sources, flags) => {
1825
1927
  const compiled = [];
1826
1928
  for (const source of sources) {
@@ -2158,7 +2260,31 @@ var createPrivacyService = (policyInput) => {
2158
2260
  flattenToAttributes,
2159
2261
  sanitizeAttributes,
2160
2262
  sanitizeExtensions,
2161
- boundString
2263
+ boundString,
2264
+ restrictContent: (fact, mode) => {
2265
+ const target = CONTENT_MODE_DISCLOSURE[mode];
2266
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
2267
+ return fact;
2268
+ }
2269
+ const { text, ...rest } = fact;
2270
+ switch (target) {
2271
+ case "omitted":
2272
+ return { ...rest, disclosure: "omitted", truncated: false };
2273
+ case "masked":
2274
+ return { ...rest, disclosure: "masked", text: maskText(text) };
2275
+ case "redacted": {
2276
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
2277
+ return {
2278
+ ...rest,
2279
+ disclosure: "redacted",
2280
+ text: redacted.text,
2281
+ secretsRedacted: fact.secretsRedacted + redacted.count
2282
+ };
2283
+ }
2284
+ case "raw":
2285
+ return fact;
2286
+ }
2287
+ }
2162
2288
  };
2163
2289
  };
2164
2290
 
@@ -2794,6 +2920,28 @@ var classifyDurability = (input) => {
2794
2920
  };
2795
2921
  var isCommittable = (durability) => durability !== "lost";
2796
2922
  var MAX_ERROR_EVENTS = 8;
2923
+ var resolveWorkspaceRepositoryKey = async (locator, directory, budgetMillis) => {
2924
+ if (locator?.originRepositoryKey === void 0) {
2925
+ return void 0;
2926
+ }
2927
+ let timer;
2928
+ const deadline = new Promise((resolve3) => {
2929
+ timer = setTimeout(() => resolve3(void 0), Math.max(0, budgetMillis));
2930
+ timer.unref?.();
2931
+ });
2932
+ try {
2933
+ return await Promise.race([
2934
+ locator.originRepositoryKey(directory).catch(() => void 0),
2935
+ deadline
2936
+ ]);
2937
+ } catch {
2938
+ return void 0;
2939
+ } finally {
2940
+ if (timer !== void 0) {
2941
+ clearTimeout(timer);
2942
+ }
2943
+ }
2944
+ };
2797
2945
  var collectContentFacts = (event2) => {
2798
2946
  const facts = [];
2799
2947
  const push = (fact) => {
@@ -3437,7 +3585,8 @@ var createOtelHook = (deps) => {
3437
3585
  kind: "ready",
3438
3586
  batch: batch2,
3439
3587
  dropped: screened.dropped,
3440
- ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
3588
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints },
3589
+ ...parsed.workspaceDirectory === void 0 ? {} : { workspaceDirectory: parsed.workspaceDirectory }
3441
3590
  };
3442
3591
  };
3443
3592
  let prepared;
@@ -3505,11 +3654,19 @@ var createOtelHook = (deps) => {
3505
3654
  batch,
3506
3655
  !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
3507
3656
  );
3657
+ const workspaceRepositoryKey = !suppress && batch.length > 0 && deps.routeByWorkspaceRepository === true && prepared.workspaceDirectory !== void 0 ? await resolveWorkspaceRepositoryKey(
3658
+ deps.worktreeLocator,
3659
+ prepared.workspaceDirectory,
3660
+ deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
3661
+ ) : void 0;
3508
3662
  let emitted = 0;
3509
3663
  let exportRejected = 0;
3510
3664
  if (!suppress && batch.length > 0) {
3511
3665
  try {
3512
- const result = await deps.sink.emit(batch);
3666
+ const result = await deps.sink.emit(
3667
+ batch,
3668
+ workspaceRepositoryKey === void 0 ? void 0 : { workspaceRepositoryKey }
3669
+ );
3513
3670
  emitted = result.accepted;
3514
3671
  exportRejected = result.rejected;
3515
3672
  diagnostics.push(...result.errors);
@@ -3568,7 +3725,8 @@ var createOtelHook = (deps) => {
3568
3725
  durability,
3569
3726
  dropped,
3570
3727
  hookResponse: hookResponseFor(adapter, detection, "attributed", void 0, emitted, diagnostics),
3571
- diagnostics
3728
+ diagnostics,
3729
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey }
3572
3730
  };
3573
3731
  } catch (thrown) {
3574
3732
  const info = errorInfoFromThrown(thrown, { code: "internal-error", phase: "parsing" });
@@ -3667,15 +3825,16 @@ var MAX_WORKTREE_WALK_DEPTH = 128;
3667
3825
  var MAX_GIT_FILE_BYTES = 4096;
3668
3826
  var MAX_CACHE_ENTRIES = 1024;
3669
3827
  var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
3828
+ var MAX_GIT_CONFIG_BYTES = 64 * 1024;
3670
3829
  var MAX_BRANCH_NAME_LENGTH = 255;
3671
3830
  var ABSENT = Object.freeze({ kind: "absent" });
3672
3831
  var INVALID = Object.freeze({ kind: "invalid" });
3673
- var readBounded2 = async (filePath) => {
3832
+ var readBounded2 = async (filePath, maxBytes = MAX_GIT_FILE_BYTES) => {
3674
3833
  let handle;
3675
3834
  try {
3676
3835
  handle = await open2(filePath, "r");
3677
- const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
3678
- const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
3836
+ const buffer = Buffer.alloc(maxBytes);
3837
+ const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
3679
3838
  return buffer.subarray(0, bytesRead).toString("utf8");
3680
3839
  } catch {
3681
3840
  return void 0;
@@ -3703,6 +3862,60 @@ var parseGitDirFile = (content, worktreeRoot) => {
3703
3862
  );
3704
3863
  };
3705
3864
  var parseCommonDirFile = (content, gitDir) => resolveGitPath(firstLine(content), gitDir);
3865
+ var unquoteConfigValue = (raw) => {
3866
+ let value = "";
3867
+ let quoted = false;
3868
+ for (let index = 0; index < raw.length; index += 1) {
3869
+ const char = raw[index];
3870
+ if (char === "\\") {
3871
+ const next = raw[index + 1];
3872
+ if (next === void 0) {
3873
+ return void 0;
3874
+ }
3875
+ value += next === "n" ? "\n" : next === "t" ? " " : next;
3876
+ index += 1;
3877
+ } else if (char === '"') {
3878
+ quoted = !quoted;
3879
+ } else if (!quoted && (char === "#" || char === ";")) {
3880
+ break;
3881
+ } else {
3882
+ value += char;
3883
+ }
3884
+ }
3885
+ return quoted ? void 0 : value.trim();
3886
+ };
3887
+ var parseOriginRemoteUrl = (content) => {
3888
+ const lines = content.split(/\r?\n/);
3889
+ if (!content.endsWith("\n")) {
3890
+ lines.pop();
3891
+ }
3892
+ let inOrigin = false;
3893
+ for (const rawLine of lines) {
3894
+ const line = rawLine.trim();
3895
+ if (line.startsWith("[")) {
3896
+ const close = line.indexOf("]");
3897
+ const header = close === -1 ? "" : line.slice(1, close).trim();
3898
+ const rest = close === -1 ? "" : line.slice(close + 1).trim();
3899
+ inOrigin = /^remote\s+"origin"$/i.test(header) && header.endsWith('"origin"') || header.toLowerCase() === "remote.origin";
3900
+ if (!inOrigin || rest.length === 0 || rest.startsWith("#") || rest.startsWith(";")) {
3901
+ continue;
3902
+ }
3903
+ const entry2 = /^url\s*=(.*)$/i.exec(rest);
3904
+ if (entry2 !== null) {
3905
+ return unquoteConfigValue(entry2[1] ?? "");
3906
+ }
3907
+ continue;
3908
+ }
3909
+ if (!inOrigin) {
3910
+ continue;
3911
+ }
3912
+ const entry = /^url\s*=(.*)$/i.exec(line);
3913
+ if (entry !== null) {
3914
+ return unquoteConfigValue(entry[1] ?? "");
3915
+ }
3916
+ }
3917
+ return void 0;
3918
+ };
3706
3919
  var isMissing = async (filePath) => {
3707
3920
  try {
3708
3921
  await lstat(filePath);
@@ -3723,11 +3936,15 @@ var repositoryOf = async (worktreeRoot, gitDir) => {
3723
3936
  const commonDirFile = path3.join(gitDir, "commondir");
3724
3937
  const content = await readBounded2(commonDirFile);
3725
3938
  if (content === void 0) {
3726
- return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
3939
+ return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot, configDir: gitDir } : { kind: "linked" };
3727
3940
  }
3728
3941
  const commonDir = parseCommonDirFile(content, gitDir);
3729
3942
  const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
3730
- return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
3943
+ return {
3944
+ kind: "linked",
3945
+ ...mainRoot === void 0 ? {} : { mainRoot },
3946
+ ...commonDir === void 0 ? {} : { configDir: commonDir }
3947
+ };
3731
3948
  };
3732
3949
  var probeDirectory = async (directory) => {
3733
3950
  const dotGit = path3.join(directory, ".git");
@@ -3752,12 +3969,21 @@ var probeDirectory = async (directory) => {
3752
3969
  return INVALID;
3753
3970
  }
3754
3971
  const branch = parseHeadBranch(head);
3755
- const repository = info.isDirectory() ? { kind: "main", mainRoot: directory } : await repositoryOf(directory, gitDir);
3972
+ const { configDir, ...repository } = info.isDirectory() ? { kind: "main", mainRoot: directory, configDir: gitDir } : await repositoryOf(directory, gitDir);
3756
3973
  return {
3757
3974
  kind: "worktree",
3758
- located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository }
3975
+ located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository },
3976
+ configDir: configDir ?? ""
3759
3977
  };
3760
3978
  };
3979
+ var readOriginRepositoryKey = async (configDir) => {
3980
+ if (configDir.length === 0) {
3981
+ return void 0;
3982
+ }
3983
+ const content = await readBounded2(path3.join(configDir, "config"), MAX_GIT_CONFIG_BYTES);
3984
+ const url = content === void 0 ? void 0 : parseOriginRemoteUrl(content);
3985
+ return url === void 0 ? void 0 : normalizeRepositoryKey(url);
3986
+ };
3761
3987
  var createFilesystemWorktreeLocator = (options = {}) => {
3762
3988
  const now = options.monotonicMillis ?? (() => performance.now());
3763
3989
  const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
@@ -3775,32 +4001,57 @@ var createFilesystemWorktreeLocator = (options = {}) => {
3775
4001
  cache.set(directory, { at, probe });
3776
4002
  return probe;
3777
4003
  };
3778
- const locate = async (absolutePath) => {
3779
- try {
3780
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
4004
+ const remoteCache = /* @__PURE__ */ new Map();
4005
+ const cachedOriginKey = (configDir) => {
4006
+ const hit = remoteCache.get(configDir);
4007
+ const at = now();
4008
+ if (hit !== void 0 && at - hit.at <= ttl) {
4009
+ return hit.key;
4010
+ }
4011
+ if (remoteCache.size >= MAX_CACHE_ENTRIES) {
4012
+ remoteCache.clear();
4013
+ }
4014
+ const key = readOriginRepositoryKey(configDir).catch(() => void 0);
4015
+ remoteCache.set(configDir, { at, key });
4016
+ return key;
4017
+ };
4018
+ const findWorktree = async (absolutePath) => {
4019
+ if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
4020
+ return void 0;
4021
+ }
4022
+ let directory = path3.resolve(absolutePath);
4023
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
4024
+ const probe = await cachedProbe(directory);
4025
+ if (probe.kind === "worktree") {
4026
+ return probe;
4027
+ }
4028
+ if (probe.kind === "invalid") {
3781
4029
  return void 0;
3782
4030
  }
3783
- let directory = path3.resolve(absolutePath);
3784
- for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
3785
- const probe = await cachedProbe(directory);
3786
- if (probe.kind === "worktree") {
3787
- return probe.located;
3788
- }
3789
- if (probe.kind === "invalid") {
3790
- return void 0;
3791
- }
3792
- const parent = path3.dirname(directory);
3793
- if (parent === directory) {
3794
- return void 0;
3795
- }
3796
- directory = parent;
4031
+ const parent = path3.dirname(directory);
4032
+ if (parent === directory) {
4033
+ return void 0;
3797
4034
  }
4035
+ directory = parent;
4036
+ }
4037
+ return void 0;
4038
+ };
4039
+ const locate = async (absolutePath) => {
4040
+ try {
4041
+ return (await findWorktree(absolutePath))?.located;
4042
+ } catch {
3798
4043
  return void 0;
4044
+ }
4045
+ };
4046
+ const originRepositoryKey = async (absolutePath) => {
4047
+ try {
4048
+ const probe = await findWorktree(absolutePath);
4049
+ return probe === void 0 ? void 0 : await cachedOriginKey(probe.configDir);
3799
4050
  } catch {
3800
4051
  return void 0;
3801
4052
  }
3802
4053
  };
3803
- return { locate };
4054
+ return { locate, originRepositoryKey };
3804
4055
  };
3805
4056
  export {
3806
4057
  DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS,
@@ -3835,6 +4086,7 @@ export {
3835
4086
  parseCommonDirFile,
3836
4087
  parseGitDirFile,
3837
4088
  parseHeadBranch,
4089
+ parseOriginRemoteUrl,
3838
4090
  parseSessionContextFile,
3839
4091
  resolveDeliveryIdentity,
3840
4092
  resolveEventTargets,