@osfactory/otel-hook 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{adapter-DXpNtnaf.d.ts → adapter-BS7xHKGQ.d.ts} +9 -3
  2. package/dist/cli.js +1043 -487
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{events-VxBnDFaO.d.ts → events-CzZ5kukS.d.ts} +177 -1
  5. package/dist/{filesystem-store-J8jjDMTh.d.ts → filesystem-store-BcOveJYY.d.ts} +1 -1
  6. package/dist/{hook-_mlO3akA.d.ts → hook-DxTakjAD.d.ts} +12 -4
  7. package/dist/index.d.ts +12 -12
  8. package/dist/index.js +1171 -599
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.d.ts +4 -4
  11. package/dist/install.js +103 -68
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +14 -8
  14. package/dist/integration.js +547 -121
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +3 -3
  17. package/dist/lifecycle.js +27 -2
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-DXVBc8V9.d.ts → memory-DkTohdIa.d.ts} +2 -2
  20. package/dist/model.d.ts +1 -1
  21. package/dist/model.js +84 -41
  22. package/dist/model.js.map +1 -1
  23. package/dist/{otlp-log-sink-DTSa0KRF.d.ts → otlp-log-sink-DaZDPKnR.d.ts} +3 -3
  24. package/dist/{payload-BWV5-4n3.d.ts → payload-2lnpKodw.d.ts} +1 -1
  25. package/dist/{ports-Q8x0ODhs.d.ts → ports-B0rC49b3.d.ts} +28 -2
  26. package/dist/providers.d.ts +26 -9
  27. package/dist/providers.js +668 -452
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-Dqr3VNmT.d.ts → registry-DVnPA_b6.d.ts} +1 -1
  30. package/dist/runtime.d.ts +103 -11
  31. package/dist/runtime.js +416 -67
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{semconv-CIU-2kGO.d.ts → semconv-CtnDdsPk.d.ts} +1 -1
  34. package/dist/state.d.ts +4 -4
  35. package/dist/state.js.map +1 -1
  36. package/dist/telemetry.d.ts +6 -6
  37. package/dist/telemetry.js +92 -10
  38. package/dist/telemetry.js.map +1 -1
  39. package/dist/testing.d.ts +13 -7
  40. package/dist/testing.js +821 -492
  41. package/dist/testing.js.map +1 -1
  42. package/package.json +4 -1
package/dist/runtime.js CHANGED
@@ -837,7 +837,7 @@ var resolveDeliveryIdentity = (input) => {
837
837
  };
838
838
 
839
839
  // src/runtime/hook.ts
840
- import { z as z15 } from "zod";
840
+ import { z as z16 } from "zod";
841
841
 
842
842
  // src/config/schema.ts
843
843
  import { z as z8 } from "zod";
@@ -1591,11 +1591,11 @@ var createPrivacyService = (policyInput) => {
1591
1591
  };
1592
1592
  const flattenToAttributes = (value, prefix) => {
1593
1593
  const attributes = {};
1594
- const walk = (current, path) => {
1594
+ const walk = (current, path3) => {
1595
1595
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1596
1596
  const primitive = toAttributePrimitive(current);
1597
1597
  if (primitive !== void 0) {
1598
- attributes[path] = primitive;
1598
+ attributes[path3] = primitive;
1599
1599
  }
1600
1600
  return;
1601
1601
  }
@@ -1614,16 +1614,16 @@ var createPrivacyService = (policyInput) => {
1614
1614
  primitives.push(entryPrimitive);
1615
1615
  }
1616
1616
  if (uniform) {
1617
- attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1617
+ attributes[path3] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1618
1618
  return;
1619
1619
  }
1620
1620
  for (const [index, entry] of current.entries()) {
1621
- walk(entry, `${path}.${index}`);
1621
+ walk(entry, `${path3}.${index}`);
1622
1622
  }
1623
1623
  return;
1624
1624
  }
1625
1625
  for (const [key, entry] of Object.entries(current)) {
1626
- walk(entry, path === "" ? key : `${path}.${key}`);
1626
+ walk(entry, path3 === "" ? key : `${path3}.${key}`);
1627
1627
  }
1628
1628
  };
1629
1629
  walk(value, prefix);
@@ -1716,23 +1716,50 @@ var createPrivacyService = (policyInput) => {
1716
1716
  };
1717
1717
 
1718
1718
  // src/providers/adapter.ts
1719
- import { z as z14 } from "zod";
1719
+ import { z as z15 } from "zod";
1720
1720
 
1721
1721
  // src/model/events.ts
1722
+ import { z as z14 } from "zod";
1723
+
1724
+ // src/model/target.ts
1722
1725
  import { z as z13 } from "zod";
1723
- var modelDescriptorSchema = z13.strictObject({
1726
+ var targetSourceSchema = z13.enum(["tool-path", "shell-cwd", "session-cwd"]);
1727
+ var MAX_TARGET_HINT_PATHS = 8;
1728
+ var MAX_TARGET_PATH_LENGTH = 4096;
1729
+ var localPathSchema = z13.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
1730
+ var targetHintSchema = z13.strictObject({
1731
+ source: targetSourceSchema,
1732
+ paths: z13.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
1733
+ /** Absolute directory that relative `paths` resolve against. */
1734
+ baseDirectory: localPathSchema.optional()
1735
+ }).readonly();
1736
+ var worktreeKindSchema = z13.enum(["main", "linked"]);
1737
+ var workspaceTargetSchema = z13.strictObject({
1738
+ workspaceId: workspaceIdSchema,
1739
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
1740
+ vcsBranchName: nonEmptyStringSchema.optional(),
1741
+ source: targetSourceSchema,
1742
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
1743
+ repositoryId: workspaceIdSchema.optional(),
1744
+ worktreeKind: worktreeKindSchema.optional()
1745
+ }).readonly();
1746
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
1747
+ var subagentIdSchema = z13.string().regex(SUBAGENT_ID_PATTERN);
1748
+
1749
+ // src/model/events.ts
1750
+ var modelDescriptorSchema = z14.strictObject({
1724
1751
  modelId: nonEmptyStringSchema,
1725
1752
  /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
1726
1753
  vendor: nonEmptyStringSchema.optional(),
1727
1754
  family: nonEmptyStringSchema.optional()
1728
1755
  });
1729
- var costFactsSchema = z13.strictObject({
1756
+ var costFactsSchema = z14.strictObject({
1730
1757
  /** ISO 4217 code. */
1731
- currency: z13.string().length(3),
1732
- amount: z13.number().min(0).finite(),
1733
- source: z13.enum(["provider-reported", "computed"])
1758
+ currency: z14.string().length(3),
1759
+ amount: z14.number().min(0).finite(),
1760
+ source: z14.enum(["provider-reported", "computed"])
1734
1761
  });
1735
- var canonicalEventTypeSchema = z13.enum([
1762
+ var canonicalEventTypeSchema = z14.enum([
1736
1763
  "session.start",
1737
1764
  "session.end",
1738
1765
  "prompt.submitted",
@@ -1746,7 +1773,7 @@ var canonicalEventTypeSchema = z13.enum([
1746
1773
  "error.raised"
1747
1774
  ]);
1748
1775
  var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
1749
- var outcomeSchema = z13.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1776
+ var outcomeSchema = z14.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1750
1777
  var baseEventFields = {
1751
1778
  schemaVersion: canonicalSchemaVersionSchema,
1752
1779
  eventId: eventIdSchema,
@@ -1757,39 +1784,45 @@ var baseEventFields = {
1757
1784
  occurredAt: epochMillisSchema,
1758
1785
  provenance: sourceProvenanceSchema,
1759
1786
  workspace: workspaceIdentitySchema,
1787
+ /**
1788
+ * The provider's own id for the subagent this event was emitted inside (e.g.
1789
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
1790
+ * factory, never by hand.
1791
+ */
1792
+ subagentId: subagentIdSchema.optional(),
1760
1793
  extensions: extensionsSchema.default(emptyExtensions)
1761
1794
  };
1762
- var event = (shape) => z13.strictObject({ ...baseEventFields, ...shape });
1795
+ var event = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
1763
1796
  var sessionStartEventSchema = event({
1764
- type: z13.literal("session.start"),
1765
- sessionKind: z13.enum(["interactive", "non-interactive", "unknown"]),
1797
+ type: z14.literal("session.start"),
1798
+ sessionKind: z14.enum(["interactive", "non-interactive", "unknown"]),
1766
1799
  agentName: nonEmptyStringSchema.optional(),
1767
1800
  agentVersion: nonEmptyStringSchema.optional(),
1768
1801
  model: modelDescriptorSchema.optional()
1769
1802
  });
1770
1803
  var sessionEndEventSchema = event({
1771
- type: z13.literal("session.end"),
1772
- reason: z13.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1804
+ type: z14.literal("session.end"),
1805
+ reason: z14.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1773
1806
  durationMillis: durationMillisSchema.optional(),
1774
1807
  /** Session totals, typically cumulative. */
1775
1808
  usage: canonicalUsageSchema.optional(),
1776
1809
  cost: costFactsSchema.optional()
1777
1810
  });
1778
1811
  var promptSubmittedEventSchema = event({
1779
- type: z13.literal("prompt.submitted"),
1780
- promptSource: z13.enum(["user", "automation", "resumed", "unknown"]),
1812
+ type: z14.literal("prompt.submitted"),
1813
+ promptSource: z14.enum(["user", "automation", "resumed", "unknown"]),
1781
1814
  content: contentFactSchema.optional(),
1782
- turnIndex: z13.number().int().min(0).optional()
1815
+ turnIndex: z14.number().int().min(0).optional()
1783
1816
  });
1784
1817
  var generationStartEventSchema = event({
1785
- type: z13.literal("generation.start"),
1818
+ type: z14.literal("generation.start"),
1786
1819
  generationId: nonEmptyStringSchema,
1787
1820
  model: modelDescriptorSchema,
1788
1821
  requestedMaxOutputTokens: tokenCountSchema.optional(),
1789
1822
  inputContent: contentFactsSchema.optional()
1790
1823
  });
1791
1824
  var generationEndEventSchema = event({
1792
- type: z13.literal("generation.end"),
1825
+ type: z14.literal("generation.end"),
1793
1826
  generationId: nonEmptyStringSchema,
1794
1827
  model: modelDescriptorSchema,
1795
1828
  outcome: outcomeSchema,
@@ -1799,7 +1832,7 @@ var generationEndEventSchema = event({
1799
1832
  cost: costFactsSchema.optional(),
1800
1833
  outputContent: contentFactsSchema.optional()
1801
1834
  });
1802
- var toolKindSchema = z13.enum([
1835
+ var toolKindSchema = z14.enum([
1803
1836
  "read",
1804
1837
  "write",
1805
1838
  "execute",
@@ -1810,59 +1843,63 @@ var toolKindSchema = z13.enum([
1810
1843
  "unknown"
1811
1844
  ]);
1812
1845
  var toolStartEventSchema = event({
1813
- type: z13.literal("tool.start"),
1846
+ type: z14.literal("tool.start"),
1814
1847
  toolCallId: nonEmptyStringSchema,
1815
1848
  toolName: nonEmptyStringSchema,
1816
1849
  toolKind: toolKindSchema,
1817
1850
  generationId: nonEmptyStringSchema.optional(),
1818
- input: contentFactSchema.optional()
1851
+ input: contentFactSchema.optional(),
1852
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1853
+ target: workspaceTargetSchema.optional()
1819
1854
  });
1820
1855
  var toolEndEventSchema = event({
1821
- type: z13.literal("tool.end"),
1856
+ type: z14.literal("tool.end"),
1822
1857
  toolCallId: nonEmptyStringSchema,
1823
1858
  toolName: nonEmptyStringSchema,
1824
1859
  outcome: outcomeSchema,
1825
1860
  durationMillis: durationMillisSchema.optional(),
1826
1861
  /** Present when the host asked for or recorded a permission decision. */
1827
- permissionDecision: z13.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1828
- output: contentFactSchema.optional()
1862
+ permissionDecision: z14.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1863
+ output: contentFactSchema.optional(),
1864
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1865
+ target: workspaceTargetSchema.optional()
1829
1866
  });
1830
1867
  var subagentStartEventSchema = event({
1831
- type: z13.literal("subagent.start"),
1868
+ type: z14.literal("subagent.start"),
1832
1869
  subagentInvocationId: invocationIdSchema,
1833
1870
  subagentType: nonEmptyStringSchema.optional(),
1834
1871
  /** 0 for the top-level agent; 1 for its direct children. */
1835
- delegationDepth: z13.number().int().min(0).max(64),
1872
+ delegationDepth: z14.number().int().min(0).max(64),
1836
1873
  model: modelDescriptorSchema.optional()
1837
1874
  });
1838
1875
  var subagentEndEventSchema = event({
1839
- type: z13.literal("subagent.end"),
1876
+ type: z14.literal("subagent.end"),
1840
1877
  subagentInvocationId: invocationIdSchema,
1841
1878
  outcome: outcomeSchema,
1842
1879
  durationMillis: durationMillisSchema.optional(),
1843
1880
  usage: canonicalUsageSchema.optional()
1844
1881
  });
1845
1882
  var compactionPerformedEventSchema = event({
1846
- type: z13.literal("compaction.performed"),
1847
- trigger: z13.enum(["automatic", "manual", "unknown"]),
1883
+ type: z14.literal("compaction.performed"),
1884
+ trigger: z14.enum(["automatic", "manual", "unknown"]),
1848
1885
  /** Provider-reported context size before and after compaction, if known. */
1849
1886
  contextTokensBefore: tokenCountSchema.optional(),
1850
1887
  contextTokensAfter: tokenCountSchema.optional(),
1851
- droppedMessageCount: z13.number().int().min(0).optional(),
1888
+ droppedMessageCount: z14.number().int().min(0).optional(),
1852
1889
  usage: canonicalUsageSchema.optional()
1853
1890
  });
1854
1891
  var errorRaisedEventSchema = event({
1855
- type: z13.literal("error.raised"),
1892
+ type: z14.literal("error.raised"),
1856
1893
  errorCode: otelHookErrorCodeSchema,
1857
1894
  severity: errorSeveritySchema,
1858
1895
  phase: errorPhaseSchema,
1859
- retryable: z13.boolean(),
1896
+ retryable: z14.boolean(),
1860
1897
  /** Error text is content: it is described, never embedded verbatim by default. */
1861
1898
  message: contentFactSchema.optional(),
1862
1899
  /** Non-sensitive, provider-agnostic short label. */
1863
1900
  detail: nonEmptyStringSchema.optional()
1864
1901
  });
1865
- var canonicalEventSchema = z13.discriminatedUnion("type", [
1902
+ var canonicalEventSchema = z14.discriminatedUnion("type", [
1866
1903
  sessionStartEventSchema,
1867
1904
  sessionEndEventSchema,
1868
1905
  promptSubmittedEventSchema,
@@ -1877,26 +1914,26 @@ var canonicalEventSchema = z13.discriminatedUnion("type", [
1877
1914
  ]);
1878
1915
 
1879
1916
  // src/providers/adapter.ts
1880
- var providerDetectionSchema = z14.strictObject({
1917
+ var providerDetectionSchema = z15.strictObject({
1881
1918
  providerId: resolvedProviderIdSchema,
1882
1919
  confidence: detectionConfidenceSchema,
1883
1920
  /**
1884
1921
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
1885
1922
  * Reasons are exported in diagnostics, so they must not quote payload values.
1886
1923
  */
1887
- reasons: z14.array(z14.string().min(1).max(160)).max(8),
1924
+ reasons: z15.array(z15.string().min(1).max(160)).max(8),
1888
1925
  providerVersion: nonEmptyStringSchema.optional(),
1889
1926
  /** The provider's own name for this event, when the payload states one. */
1890
1927
  sourceEventName: nonEmptyStringSchema.optional()
1891
1928
  });
1892
- var deliveryIdentifierSupportSchema = z14.enum(["none", "partial", "all"]);
1929
+ var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
1893
1930
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
1894
- var deliveryComponentSchema = z14.string().regex(
1931
+ var deliveryComponentSchema = z15.string().regex(
1895
1932
  DELIVERY_COMPONENT_PATTERN,
1896
1933
  "delivery component must be identifier-shaped: no whitespace, no path separators"
1897
1934
  );
1898
1935
  var MAX_DELIVERY_COMPONENTS = 8;
1899
- var providerDeliveryClaimSchema = z14.strictObject({
1936
+ var providerDeliveryClaimSchema = z15.strictObject({
1900
1937
  /**
1901
1938
  * The provider's own session/conversation id. Scopes the callback identity, so
1902
1939
  * two sessions reusing one tool-call id never collide.
@@ -1908,26 +1945,26 @@ var providerDeliveryClaimSchema = z14.strictObject({
1908
1945
  * Identifier-shaped payload fields that, together with `sourceEventName`,
1909
1946
  * name this callback within the session exactly once.
1910
1947
  */
1911
- components: z14.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
1948
+ components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
1912
1949
  /**
1913
1950
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
1914
1951
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
1915
1952
  * quote their values.
1916
1953
  */
1917
- evidence: z14.array(z14.string().min(1).max(160)).min(1).max(4).readonly()
1954
+ evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
1918
1955
  });
1919
1956
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
1920
- var deliveryGapReasonSchema = z14.string().regex(
1957
+ var deliveryGapReasonSchema = z15.string().regex(
1921
1958
  DELIVERY_GAP_REASON_PATTERN,
1922
1959
  "delivery gap reason must be one line of prose: no path separators, no control characters"
1923
1960
  );
1924
1961
  var MAX_DELIVERY_GAPS = 48;
1925
- var providerDeliveryGapsSchema = z14.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
1962
+ var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
1926
1963
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
1927
1964
  });
1928
- var providerCapabilitiesSchema = z14.strictObject({
1965
+ var providerCapabilitiesSchema = z15.strictObject({
1929
1966
  /** Event types the adapter can produce. */
1930
- lifecycleEvents: z14.array(canonicalEventTypeSchema).max(32).readonly(),
1967
+ lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
1931
1968
  usageTemporality: usageTemporalitySchema,
1932
1969
  /**
1933
1970
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -1946,32 +1983,32 @@ var providerCapabilitiesSchema = z14.strictObject({
1946
1983
  * Subagent snapshots keep their own series regardless: a delegated agent's
1947
1984
  * counter is not a point on the parent session's curve.
1948
1985
  */
1949
- cumulativeUsageSeries: z14.enum(["event-scope", "session-lifetime"]).optional(),
1950
- reportsCachedInput: z14.boolean(),
1951
- reportsCacheCreation: z14.boolean(),
1986
+ cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
1987
+ reportsCachedInput: z15.boolean(),
1988
+ reportsCacheCreation: z15.boolean(),
1952
1989
  cacheCreationAccounting: cacheCreationAccountingSchema,
1953
- reportsReasoningOutput: z14.boolean(),
1954
- reportsProviderTotal: z14.boolean(),
1955
- reportsCost: z14.boolean(),
1956
- emitsSubagentEvents: z14.boolean(),
1957
- emitsCompactionEvents: z14.boolean(),
1990
+ reportsReasoningOutput: z15.boolean(),
1991
+ reportsProviderTotal: z15.boolean(),
1992
+ reportsCost: z15.boolean(),
1993
+ emitsSubagentEvents: z15.boolean(),
1994
+ emitsCompactionEvents: z15.boolean(),
1958
1995
  /** True when the provider reads a structured response from stdout. */
1959
- requiresHookResponse: z14.boolean(),
1996
+ requiresHookResponse: z15.boolean(),
1960
1997
  /** How much of this provider's hook traffic is replay-identifiable. */
1961
1998
  deliveryIdentifier: deliveryIdentifierSupportSchema
1962
1999
  });
1963
- var providerHookResponseSchema = z14.strictObject({
2000
+ var providerHookResponseSchema = z15.strictObject({
1964
2001
  /**
1965
2002
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
1966
2003
  * the type forbids expressing anything else (ADR 0004).
1967
2004
  */
1968
- exitCode: z14.literal(0),
2005
+ exitCode: z15.literal(0),
1969
2006
  /** Protocol response text. Omit to write nothing at all. */
1970
- stdout: z14.string().max(8192).optional(),
2007
+ stdout: z15.string().max(8192).optional(),
1971
2008
  /** Non-sensitive diagnostic text for stderr. */
1972
- stderr: z14.string().max(8192).optional(),
2009
+ stderr: z15.string().max(8192).optional(),
1973
2010
  /** Declares which of the two stdout contracts this response follows. */
1974
- contract: z14.enum(["silent", "provider-protocol"])
2011
+ contract: z15.enum(["silent", "provider-protocol"])
1975
2012
  });
1976
2013
  var SILENT_HOOK_RESPONSE = Object.freeze({
1977
2014
  exitCode: 0,
@@ -2137,6 +2174,145 @@ var createProviderRegistry = (adapters) => {
2137
2174
  var createDuplicateAdapterError = (id) => new Error(`duplicate provider adapter id: ${id}`);
2138
2175
  var BUILT_IN_PROVIDERS = Object.freeze([]);
2139
2176
 
2177
+ // src/runtime/target-resolution.ts
2178
+ import * as path from "path";
2179
+
2180
+ // src/privacy/workspace.ts
2181
+ var canonicalizeGitRemote = (remoteUrl) => {
2182
+ const trimmed = remoteUrl.trim();
2183
+ const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);
2184
+ const withoutScheme = scpLike ? `${scpLike[2] ?? ""}/${scpLike[3] ?? ""}` : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/^[^@/]+@/, "");
2185
+ return withoutScheme.replace(/:\d+\//, "/").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
2186
+ };
2187
+ var keySourceOf = (input) => {
2188
+ switch (input.kind) {
2189
+ case "git-remote":
2190
+ return "git-remote";
2191
+ case "git-root":
2192
+ return "git-root";
2193
+ case "working-directory":
2194
+ return "working-directory";
2195
+ case "explicit":
2196
+ return "explicit";
2197
+ case "unknown":
2198
+ return "unknown";
2199
+ }
2200
+ };
2201
+ var keyMaterialOf = (input) => {
2202
+ switch (input.kind) {
2203
+ case "git-remote":
2204
+ return canonicalizeGitRemote(input.remoteUrl);
2205
+ case "git-root":
2206
+ case "working-directory":
2207
+ return input.absolutePath.replace(/[/\\]+$/, "");
2208
+ case "explicit":
2209
+ return input.value;
2210
+ case "unknown":
2211
+ return void 0;
2212
+ }
2213
+ };
2214
+ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
2215
+ const keySource = keySourceOf(input);
2216
+ const material = keyMaterialOf(input);
2217
+ const workspaceId = material === void 0 || material === "" ? "unknown:0000000000000000" : privacy.deriveOpaqueId(`workspace/${keySource}`, material);
2218
+ return workspaceIdentitySchema.parse({
2219
+ workspaceId,
2220
+ keySource: material === void 0 || material === "" ? "unknown" : keySource,
2221
+ ...labels.repositoryName === void 0 ? {} : { repositoryName: labels.repositoryName.slice(0, 128) },
2222
+ ...labels.vcsBranchName === void 0 ? {} : { vcsBranchName: labels.vcsBranchName.slice(0, 128) },
2223
+ ...labels.vcsRevisionId === void 0 ? {} : { vcsRevisionId: privacy.deriveOpaqueId("workspace/revision", labels.vcsRevisionId) }
2224
+ });
2225
+ };
2226
+
2227
+ // src/runtime/target-resolution.ts
2228
+ var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
2229
+ var absolutePathsOf = (hint) => {
2230
+ const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
2231
+ const resolved = [];
2232
+ for (const candidate of hint.paths) {
2233
+ if (path.isAbsolute(candidate)) {
2234
+ resolved.push(path.resolve(candidate));
2235
+ } else if (base !== void 0) {
2236
+ resolved.push(path.resolve(base, candidate));
2237
+ } else {
2238
+ return void 0;
2239
+ }
2240
+ }
2241
+ return resolved;
2242
+ };
2243
+ var resolveHint = async (hint, locator, privacy) => {
2244
+ const paths = absolutePathsOf(hint);
2245
+ if (paths === void 0) {
2246
+ return void 0;
2247
+ }
2248
+ const located = await Promise.all(
2249
+ [...new Set(paths)].map((candidate) => locator.locate(candidate))
2250
+ );
2251
+ const [first] = located;
2252
+ if (first === void 0 || located.some((entry) => entry?.root !== first.root)) {
2253
+ return void 0;
2254
+ }
2255
+ const identity = deriveWorkspaceIdentity(
2256
+ privacy,
2257
+ { kind: "git-root", absolutePath: first.root },
2258
+ first.branch === void 0 ? {} : { vcsBranchName: first.branch }
2259
+ );
2260
+ if (identity.keySource !== "git-root") {
2261
+ return void 0;
2262
+ }
2263
+ const repository = first.mainRoot === void 0 ? void 0 : deriveWorkspaceIdentity(privacy, { kind: "git-root", absolutePath: first.mainRoot });
2264
+ const parsed = workspaceTargetSchema.safeParse({
2265
+ workspaceId: identity.workspaceId,
2266
+ ...identity.vcsBranchName === void 0 ? {} : { vcsBranchName: identity.vcsBranchName },
2267
+ source: hint.source,
2268
+ ...repository?.keySource === "git-root" ? { repositoryId: repository.workspaceId } : {},
2269
+ ...first.kind === void 0 ? {} : { worktreeKind: first.kind }
2270
+ });
2271
+ return parsed.success ? parsed.data : void 0;
2272
+ };
2273
+ var resolveEventTargets = async (input) => {
2274
+ const pending = input.events.filter(
2275
+ (event2) => (event2.type === "tool.start" || event2.type === "tool.end") && input.hints.has(event2.eventId)
2276
+ );
2277
+ if (pending.length === 0) {
2278
+ return { events: input.events, resolved: 0, timedOut: false };
2279
+ }
2280
+ const targets = /* @__PURE__ */ new Map();
2281
+ const work = Promise.all(
2282
+ pending.map(async (event2) => {
2283
+ const hint = input.hints.get(event2.eventId);
2284
+ if (hint === void 0) {
2285
+ return;
2286
+ }
2287
+ try {
2288
+ const target = await resolveHint(hint, input.locator, input.privacy);
2289
+ if (target !== void 0) {
2290
+ targets.set(event2.eventId, target);
2291
+ }
2292
+ } catch {
2293
+ }
2294
+ })
2295
+ ).then(() => "done");
2296
+ let timer;
2297
+ const deadline = new Promise((resolve3) => {
2298
+ timer = setTimeout(() => resolve3("timeout"), Math.max(0, input.budgetMillis));
2299
+ timer.unref?.();
2300
+ });
2301
+ const finished = await Promise.race([work, deadline]);
2302
+ if (timer !== void 0) {
2303
+ clearTimeout(timer);
2304
+ }
2305
+ const settled = new Map(targets);
2306
+ const events = input.events.map((event2) => {
2307
+ const target = settled.get(event2.eventId);
2308
+ if (target === void 0 || event2.type !== "tool.start" && event2.type !== "tool.end") {
2309
+ return event2;
2310
+ }
2311
+ return { ...event2, target };
2312
+ });
2313
+ return { events, resolved: settled.size, timedOut: finished === "timeout" };
2314
+ };
2315
+
2140
2316
  // src/state/async-lock.ts
2141
2317
  var LockWaitTimeoutError = class extends Error {
2142
2318
  lockKey;
@@ -2166,7 +2342,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
2166
2342
  };
2167
2343
 
2168
2344
  // src/runtime/hook.ts
2169
- var usageScopeSchema = z15.enum(["session", "generation", "subagent"]);
2345
+ var usageScopeSchema = z16.enum(["session", "generation", "subagent"]);
2170
2346
  var classifyDurability = (input) => {
2171
2347
  if (!input.attempted) {
2172
2348
  return "nothing-to-deliver";
@@ -2705,7 +2881,12 @@ var createOtelHook = (deps) => {
2705
2881
  );
2706
2882
  }
2707
2883
  }
2708
- return { kind: "ready", batch: batch2, dropped: screened.dropped };
2884
+ return {
2885
+ kind: "ready",
2886
+ batch: batch2,
2887
+ dropped: screened.dropped,
2888
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
2889
+ };
2709
2890
  };
2710
2891
  let prepared;
2711
2892
  try {
@@ -2750,7 +2931,24 @@ var createOtelHook = (deps) => {
2750
2931
  if (prepared.kind === "early") {
2751
2932
  return prepared.outcome;
2752
2933
  }
2753
- const { batch, dropped } = prepared;
2934
+ const { dropped } = prepared;
2935
+ let batch = prepared.batch;
2936
+ if (!suppress && deps.worktreeLocator !== void 0 && prepared.targetHints !== void 0 && prepared.targetHints.size > 0) {
2937
+ const targeted = await resolveEventTargets({
2938
+ events: batch,
2939
+ hints: prepared.targetHints,
2940
+ locator: deps.worktreeLocator,
2941
+ privacy,
2942
+ budgetMillis: deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
2943
+ });
2944
+ batch = targeted.events;
2945
+ if (targeted.timedOut) {
2946
+ logger.debug("worktree target resolution exceeded its budget", {
2947
+ "provider.id": detection.providerId,
2948
+ "target.resolved": targeted.resolved
2949
+ });
2950
+ }
2951
+ }
2754
2952
  let emitted = 0;
2755
2953
  let exportRejected = 0;
2756
2954
  if (!suppress && batch.length > 0) {
@@ -2898,11 +3096,158 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
2898
3096
  }
2899
3097
  return events;
2900
3098
  };
3099
+
3100
+ // src/runtime/git-worktree.ts
3101
+ import { lstat, open, stat } from "fs/promises";
3102
+ import * as path2 from "path";
3103
+ var MAX_WORKTREE_WALK_DEPTH = 128;
3104
+ var MAX_GIT_FILE_BYTES = 4096;
3105
+ var MAX_CACHE_ENTRIES = 1024;
3106
+ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
3107
+ var MAX_BRANCH_NAME_LENGTH = 255;
3108
+ var ABSENT = Object.freeze({ kind: "absent" });
3109
+ var INVALID = Object.freeze({ kind: "invalid" });
3110
+ var readBounded = async (filePath) => {
3111
+ let handle;
3112
+ try {
3113
+ handle = await open(filePath, "r");
3114
+ const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
3115
+ const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
3116
+ return buffer.subarray(0, bytesRead).toString("utf8");
3117
+ } catch {
3118
+ return void 0;
3119
+ } finally {
3120
+ await handle?.close().catch(() => void 0);
3121
+ }
3122
+ };
3123
+ var parseHeadBranch = (head) => {
3124
+ const line = head.split(/\r?\n/, 1)[0]?.trim() ?? "";
3125
+ const match = /^ref:\s*refs\/heads\/(.+)$/.exec(line);
3126
+ const branch = match?.[1];
3127
+ if (branch === void 0 || branch.length === 0 || branch.length > MAX_BRANCH_NAME_LENGTH || // git forbids these in ref names; their presence means this is not one.
3128
+ [...branch].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || /[ ~^:?*[\\]/.test(branch)) {
3129
+ return void 0;
3130
+ }
3131
+ return branch;
3132
+ };
3133
+ var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
3134
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path2.resolve(base, target);
3135
+ var parseGitDirFile = (content, worktreeRoot) => {
3136
+ const line = firstLine(content);
3137
+ return resolveGitPath(
3138
+ line.startsWith("gitdir:") ? line.slice("gitdir:".length).trim() : void 0,
3139
+ worktreeRoot
3140
+ );
3141
+ };
3142
+ var parseCommonDirFile = (content, gitDir) => resolveGitPath(firstLine(content), gitDir);
3143
+ var isMissing = async (filePath) => {
3144
+ try {
3145
+ await lstat(filePath);
3146
+ return false;
3147
+ } catch (error) {
3148
+ const code = error.code;
3149
+ return code === "ENOENT" || code === "ENOTDIR";
3150
+ }
3151
+ };
3152
+ var isDirectory = async (directory) => {
3153
+ try {
3154
+ return (await stat(directory)).isDirectory();
3155
+ } catch {
3156
+ return false;
3157
+ }
3158
+ };
3159
+ var repositoryOf = async (worktreeRoot, gitDir) => {
3160
+ const commonDirFile = path2.join(gitDir, "commondir");
3161
+ const content = await readBounded(commonDirFile);
3162
+ if (content === void 0) {
3163
+ return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
3164
+ }
3165
+ const commonDir = parseCommonDirFile(content, gitDir);
3166
+ const mainRoot = commonDir !== void 0 && path2.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path2.dirname(commonDir) : void 0;
3167
+ return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
3168
+ };
3169
+ var probeDirectory = async (directory) => {
3170
+ const dotGit = path2.join(directory, ".git");
3171
+ let info;
3172
+ try {
3173
+ info = await stat(dotGit);
3174
+ } catch {
3175
+ return ABSENT;
3176
+ }
3177
+ let gitDir;
3178
+ if (info.isDirectory()) {
3179
+ gitDir = dotGit;
3180
+ } else if (info.isFile()) {
3181
+ const content = await readBounded(dotGit);
3182
+ gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
3183
+ }
3184
+ if (gitDir === void 0) {
3185
+ return INVALID;
3186
+ }
3187
+ const head = await readBounded(path2.join(gitDir, "HEAD"));
3188
+ if (head === void 0) {
3189
+ return INVALID;
3190
+ }
3191
+ const branch = parseHeadBranch(head);
3192
+ const repository = info.isDirectory() ? { kind: "main", mainRoot: directory } : await repositoryOf(directory, gitDir);
3193
+ return {
3194
+ kind: "worktree",
3195
+ located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository }
3196
+ };
3197
+ };
3198
+ var createFilesystemWorktreeLocator = (options = {}) => {
3199
+ const now = options.monotonicMillis ?? (() => performance.now());
3200
+ const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
3201
+ const cache = /* @__PURE__ */ new Map();
3202
+ const cachedProbe = (directory) => {
3203
+ const hit = cache.get(directory);
3204
+ const at = now();
3205
+ if (hit !== void 0 && at - hit.at <= ttl) {
3206
+ return hit.probe;
3207
+ }
3208
+ if (cache.size >= MAX_CACHE_ENTRIES) {
3209
+ cache.clear();
3210
+ }
3211
+ const probe = probeDirectory(directory).catch(() => INVALID);
3212
+ cache.set(directory, { at, probe });
3213
+ return probe;
3214
+ };
3215
+ const locate = async (absolutePath) => {
3216
+ try {
3217
+ if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
3218
+ return void 0;
3219
+ }
3220
+ let directory = path2.resolve(absolutePath);
3221
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
3222
+ const probe = await cachedProbe(directory);
3223
+ if (probe.kind === "worktree") {
3224
+ return probe.located;
3225
+ }
3226
+ if (probe.kind === "invalid") {
3227
+ return void 0;
3228
+ }
3229
+ const parent = path2.dirname(directory);
3230
+ if (parent === directory) {
3231
+ return void 0;
3232
+ }
3233
+ directory = parent;
3234
+ }
3235
+ return void 0;
3236
+ } catch {
3237
+ return void 0;
3238
+ }
3239
+ };
3240
+ return { locate };
3241
+ };
2901
3242
  export {
3243
+ DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
3244
+ DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
2902
3245
  LOG_LEVEL_RANK,
3246
+ MAX_WORKTREE_WALK_DEPTH,
2903
3247
  appliedDeliverySchema,
2904
3248
  classifyDurability,
2905
3249
  createDeterministicIdGenerator,
3250
+ createFilesystemWorktreeLocator,
2906
3251
  createFixedClock,
2907
3252
  createInMemoryStateStore,
2908
3253
  createNullLogger,
@@ -2916,7 +3261,11 @@ export {
2916
3261
  hostDeliveryIdentity,
2917
3262
  isCommittable,
2918
3263
  logLevelSchema,
3264
+ parseCommonDirFile,
3265
+ parseGitDirFile,
3266
+ parseHeadBranch,
2919
3267
  resolveDeliveryIdentity,
3268
+ resolveEventTargets,
2920
3269
  stateRecordSchema,
2921
3270
  stateValueSchema,
2922
3271
  usageScopeSchema