@osfactory/otel-hook 0.9.0 → 0.10.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 (49) hide show
  1. package/README.md +42 -1
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-B9RwW6TO.d.ts} +14 -2
  3. package/dist/cli.js +1272 -784
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +5 -3
  6. package/dist/config.js +28 -5
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C6Bm89W6.d.ts → destinations-DWOkVxV1.d.ts} +1 -1
  9. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  10. package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-lORbe25J.d.ts} +5 -5
  11. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-DX3dGIgu.d.ts} +1 -1
  12. package/dist/{hook-zA1b4cWd.d.ts → hook-BAxXoKsp.d.ts} +10 -5
  13. package/dist/index.d.ts +14 -14
  14. package/dist/index.js +643 -110
  15. package/dist/index.js.map +1 -1
  16. package/dist/install.d.ts +4 -4
  17. package/dist/install.js +31 -2
  18. package/dist/install.js.map +1 -1
  19. package/dist/integration.d.ts +17 -10
  20. package/dist/integration.js +3864 -3107
  21. package/dist/integration.js.map +1 -1
  22. package/dist/lifecycle.d.ts +3 -3
  23. package/dist/lifecycle.js +8 -1
  24. package/dist/lifecycle.js.map +1 -1
  25. package/dist/{memory-Bl9ANVff.d.ts → memory-aJilVG4R.d.ts} +2 -2
  26. package/dist/model.d.ts +1 -1
  27. package/dist/model.js +7 -0
  28. package/dist/model.js.map +1 -1
  29. package/dist/{payload-Ci8_ERm6.d.ts → payload-D7gc0-WQ.d.ts} +41 -2
  30. package/dist/{ports-n7KFOpKo.d.ts → ports-plO5MKrY.d.ts} +63 -2
  31. package/dist/providers.d.ts +146 -10
  32. package/dist/providers.js +397 -13
  33. package/dist/providers.js.map +1 -1
  34. package/dist/{registry-B8ZHc2bc.d.ts → registry-C7XO4DzD.d.ts} +2 -2
  35. package/dist/runtime.d.ts +8 -8
  36. package/dist/runtime.js +1356 -1217
  37. package/dist/runtime.js.map +1 -1
  38. package/dist/{schema-BxiVsU-d.d.ts → schema-CHb3GU1r.d.ts} +30 -1
  39. package/dist/{semconv-fPRb-dpU.d.ts → semconv-Dw7gcQcg.d.ts} +1 -1
  40. package/dist/state.d.ts +4 -4
  41. package/dist/state.js +607 -39
  42. package/dist/state.js.map +1 -1
  43. package/dist/telemetry.d.ts +6 -6
  44. package/dist/telemetry.js +13 -3
  45. package/dist/telemetry.js.map +1 -1
  46. package/dist/testing.d.ts +10 -8
  47. package/dist/testing.js +209 -25
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -350,6 +350,7 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
350
350
  "--logs",
351
351
  "--no-logs",
352
352
  "--logs-content",
353
+ "--claude-transcript-usage",
353
354
  "--include-experimental",
354
355
  "--no-experimental",
355
356
  "--dry-run",
@@ -533,7 +534,8 @@ var parsePolicy = (tokens, errors) => {
533
534
  ...includeExperimental === void 0 ? {} : { includeExperimental },
534
535
  ...logsEnabled === void 0 ? {} : { logsEnabled },
535
536
  ...logsEndpoint === void 0 ? {} : { logsEndpoint },
536
- ...tokens.booleans.has("--logs-content") ? { logsIncludeContent: true } : {}
537
+ ...tokens.booleans.has("--logs-content") ? { logsIncludeContent: true } : {},
538
+ ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {}
537
539
  };
538
540
  };
539
541
  var parseIdentity = (tokens, errors) => {
@@ -588,6 +590,7 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
588
590
  "--no-logs",
589
591
  "--logs-endpoint",
590
592
  "--logs-content",
593
+ "--claude-transcript-usage",
591
594
  "--max-input-bytes",
592
595
  "--no-export",
593
596
  "--no-spool",
@@ -617,6 +620,7 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
617
620
  "--no-logs",
618
621
  "--logs-endpoint",
619
622
  "--logs-content",
623
+ "--claude-transcript-usage",
620
624
  "--include-experimental",
621
625
  "--no-experimental"
622
626
  ]);
@@ -861,6 +865,10 @@ Exporter and runtime policy (never identity):
861
865
  --logs-content permit disclosed content text in a log body. Needs
862
866
  --content-mode too: this decides whether the logs
863
867
  pipeline may carry what that one discloses
868
+ --claude-transcript-usage Claude Code only: at Stop, read the transcript the
869
+ payload names (bounded) for the turn's model and
870
+ summed token usage. Off by default; also
871
+ OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
864
872
  --max-input-bytes <n> stdin bound (default 1048576)
865
873
  --attr <key=value> opaque consumer attribute for this invocation,
866
874
  carried unchanged (not a resource attribute)
@@ -1335,7 +1343,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
1335
1343
  maxArrayLength: "OTEL_HOOK_MAX_ARRAY_LENGTH",
1336
1344
  maxEventsPerInvocation: "OTEL_HOOK_MAX_EVENTS_PER_INVOCATION",
1337
1345
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
1338
- logLevel: "OTEL_HOOK_LOG_LEVEL"
1346
+ logLevel: "OTEL_HOOK_LOG_LEVEL",
1347
+ /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
1348
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
1339
1349
  });
1340
1350
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
1341
1351
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -1512,11 +1522,14 @@ var parseEnvironmentConfig = (env) => {
1512
1522
  };
1513
1523
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
1514
1524
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
1525
+ const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
1526
+ const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
1515
1527
  const patch = {
1516
1528
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
1517
1529
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
1518
1530
  ...Object.keys(detection).length === 0 ? {} : { detection },
1519
- ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
1531
+ ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
1532
+ ...Object.keys(providers).length === 0 ? {} : { providers }
1520
1533
  };
1521
1534
  return { patch, warnings };
1522
1535
  };
@@ -1801,11 +1814,18 @@ var diagnosticsPolicySchema = z7.strictObject({
1801
1814
  /** Emit `error.raised` events for contained failures. */
1802
1815
  emitErrorEvents: z7.boolean()
1803
1816
  });
1817
+ var providersPolicySchema = z7.strictObject({
1818
+ claudeCode: z7.strictObject({
1819
+ readTranscriptUsage: z7.boolean()
1820
+ }).optional()
1821
+ });
1804
1822
  var otelHookConfigSchema = z7.strictObject({
1805
1823
  exporter: exporterPolicySchema,
1806
1824
  privacy: privacyPolicySchema,
1807
1825
  detection: detectionPolicySchema,
1808
- diagnostics: diagnosticsPolicySchema
1826
+ diagnostics: diagnosticsPolicySchema,
1827
+ /** Optional so a hand-built configuration from before it existed stays valid. */
1828
+ providers: providersPolicySchema.optional()
1809
1829
  });
1810
1830
  var otelHookConfigPatchSchema = z7.strictObject({
1811
1831
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -1817,7 +1837,10 @@ var otelHookConfigPatchSchema = z7.strictObject({
1817
1837
  }).optional(),
1818
1838
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1819
1839
  detection: detectionPolicySchema.partial().optional(),
1820
- diagnostics: diagnosticsPolicySchema.partial().optional()
1840
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
1841
+ providers: z7.strictObject({
1842
+ claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
1843
+ }).partial().optional()
1821
1844
  });
1822
1845
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
1823
1846
  enabled: true,
@@ -1840,23 +1863,28 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
1840
1863
  logLevel: "warn",
1841
1864
  emitErrorEvents: true
1842
1865
  });
1866
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
1867
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
1868
+ });
1843
1869
  var DEFAULT_CONFIG = Object.freeze({
1844
1870
  exporter: DEFAULT_EXPORTER_POLICY,
1845
1871
  privacy: DEFAULT_PRIVACY_POLICY,
1846
1872
  detection: DEFAULT_DETECTION_POLICY,
1847
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
1873
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
1874
+ providers: DEFAULT_PROVIDERS_POLICY
1848
1875
  });
1876
+ var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
1849
1877
 
1850
1878
  // src/config/resolve.ts
1851
1879
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1852
1880
  var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
1853
1881
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1854
- var mergeLeaf = (target, patch, source, provenance, path13) => {
1882
+ var mergeLeaf = (target, patch, source, provenance, path14) => {
1855
1883
  for (const [key, value] of Object.entries(patch)) {
1856
1884
  if (value === void 0) {
1857
1885
  continue;
1858
1886
  }
1859
- const childPath = path13 === "" ? key : `${path13}.${key}`;
1887
+ const childPath = path14 === "" ? key : `${path14}.${key}`;
1860
1888
  const existing = target[key];
1861
1889
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
1862
1890
  const child = { ...existing ?? {} };
@@ -1870,14 +1898,14 @@ var mergeLeaf = (target, patch, source, provenance, path13) => {
1870
1898
  };
1871
1899
  var initialProvenance = (config) => {
1872
1900
  const provenance = {};
1873
- const walk = (value, path13) => {
1901
+ const walk = (value, path14) => {
1874
1902
  if (isPlainObject(value)) {
1875
1903
  for (const [key, child] of Object.entries(value)) {
1876
- walk(child, path13 === "" ? key : `${path13}.${key}`);
1904
+ walk(child, path14 === "" ? key : `${path14}.${key}`);
1877
1905
  }
1878
1906
  return;
1879
1907
  }
1880
- provenance[path13] = "defaults";
1908
+ provenance[path14] = "defaults";
1881
1909
  };
1882
1910
  walk(config, "");
1883
1911
  return provenance;
@@ -2039,123 +2067,411 @@ var describeResolvedConfig = (config) => {
2039
2067
  };
2040
2068
 
2041
2069
  // src/runtime/ports.ts
2042
- import { z as z10 } from "zod";
2070
+ import { z as z16 } from "zod";
2043
2071
 
2044
- // src/model/usage.ts
2072
+ // src/model/events.ts
2073
+ import { z as z15 } from "zod";
2074
+
2075
+ // src/model/content.ts
2045
2076
  import { z as z9 } from "zod";
2046
- var usageTemporalitySchema = z9.enum(["delta", "cumulative"]);
2047
- var cacheCreationAccountingSchema = z9.enum([
2048
- "included-in-input",
2049
- "disjoint-from-input",
2050
- "not-reported"
2077
+ var contentKindSchema = z9.enum([
2078
+ "prompt",
2079
+ "response",
2080
+ "reasoning",
2081
+ "tool-input",
2082
+ "tool-output",
2083
+ "error-message",
2084
+ "system-instruction",
2085
+ "attachment"
2051
2086
  ]);
2052
- var providerTotalAgreementSchema = z9.enum(["unreported", "agrees", "disagrees"]);
2053
- var usageReportSchema = z9.strictObject({
2054
- temporality: usageTemporalitySchema,
2055
- /** Inclusive input tokens. */
2056
- inputTokens: tokenCountSchema.optional(),
2057
- /** Subset of `inputTokens` served from a prompt cache. */
2058
- cachedInputTokens: tokenCountSchema.optional(),
2059
- /** Tokens written to a prompt cache. */
2060
- cacheCreationInputTokens: tokenCountSchema.optional(),
2061
- /** Required when `cacheCreationInputTokens` is present and non-zero. */
2062
- cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
2063
- /** Inclusive output tokens. */
2064
- outputTokens: tokenCountSchema.optional(),
2065
- /** Subset of `outputTokens` spent on reasoning. */
2066
- reasoningOutputTokens: tokenCountSchema.optional(),
2067
- /** Total exactly as the provider reported it, if it reported one. */
2068
- providerTotalTokens: tokenCountSchema.optional()
2087
+ var contentRoleSchema = z9.enum(["user", "assistant", "system", "tool", "unknown"]);
2088
+ var contentDisclosureSchema = z9.enum(["omitted", "masked", "redacted", "raw"]);
2089
+ var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
2090
+ var contentFactSchema = z9.strictObject({
2091
+ kind: contentKindSchema,
2092
+ role: contentRoleSchema.optional(),
2093
+ /** Unicode code point count of the original content. */
2094
+ characterLength: z9.number().int().min(0),
2095
+ /** UTF-8 byte length of the original content. */
2096
+ byteLength: z9.number().int().min(0),
2097
+ /** Stable salted digest of the original content. */
2098
+ contentHash: z9.string().regex(CONTENT_HASH_PATTERN),
2099
+ disclosure: contentDisclosureSchema,
2100
+ /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
2101
+ text: z9.string().optional(),
2102
+ /** True when `text` was cut short by the configured string bound. */
2103
+ truncated: z9.boolean(),
2104
+ /** Number of secret-looking spans replaced while producing `text`. */
2105
+ secretsRedacted: z9.number().int().min(0),
2106
+ /** Optional non-sensitive label, e.g. a MIME type or tool name. */
2107
+ label: nonEmptyStringSchema.optional()
2069
2108
  });
2070
- var canonicalUsageSchema = z9.strictObject({
2071
- temporality: usageTemporalitySchema,
2072
- inputTokens: tokenCountSchema,
2073
- cachedInputTokens: tokenCountSchema,
2074
- cacheCreationInputTokens: tokenCountSchema,
2075
- cacheCreationAccounting: cacheCreationAccountingSchema,
2076
- outputTokens: tokenCountSchema,
2077
- reasoningOutputTokens: tokenCountSchema,
2078
- /** Derived: input tokens that were neither cache reads nor cache writes. */
2079
- uncachedInputTokens: tokenCountSchema,
2080
- /** Derived: canonical billable total. */
2081
- totalTokens: tokenCountSchema,
2082
- providerTotalTokens: tokenCountSchema.optional(),
2083
- providerTotalAgreement: providerTotalAgreementSchema
2084
- }).check((ctx) => {
2085
- const usage = ctx.value;
2086
- const push = (message) => {
2087
- ctx.issues.push({ code: "custom", input: usage, message });
2088
- };
2089
- if (usage.cachedInputTokens > usage.inputTokens) {
2090
- push("cachedInputTokens must not exceed inputTokens (it is a subset)");
2091
- }
2092
- if (usage.reasoningOutputTokens > usage.outputTokens) {
2093
- push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
2094
- }
2095
- if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
2096
- push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
2097
- }
2098
- const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
2099
- if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
2100
- push(
2101
- "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
2102
- );
2109
+ var contentFactsSchema = z9.array(contentFactSchema).max(64);
2110
+ var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
2111
+ var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
2112
+
2113
+ // src/model/extensions.ts
2114
+ import { z as z10 } from "zod";
2115
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
2116
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
2117
+ "otelhook",
2118
+ "otel",
2119
+ "telemetry"
2120
+ ]);
2121
+ var MAX_EXTENSION_ENTRIES = 64;
2122
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
2123
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
2124
+ var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
2125
+ var extensionsSchema = z10.record(z10.string(), attributeValueSchema).check((ctx) => {
2126
+ const keys = Object.keys(ctx.value);
2127
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
2128
+ ctx.issues.push({
2129
+ code: "custom",
2130
+ input: ctx.value,
2131
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
2132
+ });
2103
2133
  }
2104
- const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
2105
- if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
2106
- push(`uncachedInputTokens must equal ${expectedUncached}`);
2134
+ for (const key of keys) {
2135
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
2136
+ ctx.issues.push({
2137
+ code: "custom",
2138
+ input: ctx.value,
2139
+ path: [key],
2140
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
2141
+ });
2142
+ continue;
2143
+ }
2144
+ if (isReservedExtensionNamespace(key)) {
2145
+ ctx.issues.push({
2146
+ code: "custom",
2147
+ input: ctx.value,
2148
+ path: [key],
2149
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
2150
+ });
2151
+ }
2107
2152
  }
2108
- const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
2109
- const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
2110
- if (usage.totalTokens !== expectedTotal) {
2111
- push(`totalTokens must equal ${expectedTotal}`);
2153
+ });
2154
+ var EMPTY_EXTENSIONS = Object.freeze({});
2155
+ var emptyExtensions = () => ({});
2156
+
2157
+ // src/model/identity.ts
2158
+ import { z as z11 } from "zod";
2159
+ var workspaceKeySourceSchema = z11.enum([
2160
+ "git-remote",
2161
+ "git-root",
2162
+ "working-directory",
2163
+ "explicit",
2164
+ "unknown"
2165
+ ]);
2166
+ var workspaceIdentitySchema = z11.strictObject({
2167
+ workspaceId: workspaceIdSchema,
2168
+ keySource: workspaceKeySourceSchema,
2169
+ /** Repository name only; never an owner path or URL with credentials. */
2170
+ repositoryName: nonEmptyStringSchema.optional(),
2171
+ vcsBranchName: nonEmptyStringSchema.optional(),
2172
+ /** Opaque handle for the checked-out revision. */
2173
+ vcsRevisionId: nonEmptyStringSchema.optional()
2174
+ }).readonly();
2175
+ var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
2176
+ var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
2177
+ workspaceId: UNKNOWN_WORKSPACE_ID,
2178
+ keySource: "unknown"
2179
+ });
2180
+ var sourceProvenanceSchema = z11.strictObject({
2181
+ providerId: resolvedProviderIdSchema,
2182
+ providerVersion: nonEmptyStringSchema.optional(),
2183
+ adapterId: nonEmptyStringSchema,
2184
+ adapterVersion: nonEmptyStringSchema,
2185
+ detectionConfidence: detectionConfidenceSchema,
2186
+ /** The provider's own name for the source event, e.g. a hook event name. */
2187
+ sourceEventName: nonEmptyStringSchema.optional(),
2188
+ transport: sourceTransportSchema
2189
+ }).readonly();
2190
+ var consumerAttributesSchema = attributesSchema.readonly();
2191
+ var invocationIdentitySchema = z11.strictObject({
2192
+ invocationId: invocationIdSchema,
2193
+ sessionId: sessionIdSchema,
2194
+ /** Set when this invocation runs beneath another agent invocation. */
2195
+ parentInvocationId: invocationIdSchema.optional(),
2196
+ /** Root of the session tree when the provider exposes one. */
2197
+ rootSessionId: sessionIdSchema.optional(),
2198
+ /** Stable handle for the agent process/instance, when available. */
2199
+ agentInstanceId: nonEmptyStringSchema.optional(),
2200
+ provenance: sourceProvenanceSchema,
2201
+ workspace: workspaceIdentitySchema,
2202
+ startedAt: epochMillisSchema,
2203
+ consumerAttributes: consumerAttributesSchema
2204
+ }).readonly();
2205
+ var identityClaimFieldsSchema = z11.strictObject({
2206
+ invocationId: invocationIdSchema.optional(),
2207
+ sessionId: sessionIdSchema.optional(),
2208
+ parentInvocationId: invocationIdSchema.optional(),
2209
+ rootSessionId: sessionIdSchema.optional(),
2210
+ agentInstanceId: nonEmptyStringSchema.optional(),
2211
+ workspace: workspaceIdentitySchema.optional(),
2212
+ startedAt: epochMillisSchema.optional()
2213
+ });
2214
+ var identityClaimSchema = z11.strictObject({
2215
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
2216
+ source: nonEmptyStringSchema,
2217
+ confidence: detectionConfidenceSchema,
2218
+ fields: identityClaimFieldsSchema
2219
+ });
2220
+ var CLAIM_FIELDS = [
2221
+ "invocationId",
2222
+ "sessionId",
2223
+ "parentInvocationId",
2224
+ "rootSessionId",
2225
+ "agentInstanceId",
2226
+ "workspace",
2227
+ "startedAt"
2228
+ ];
2229
+ var renderClaimValue = (value) => {
2230
+ if (typeof value === "string") {
2231
+ return value;
2112
2232
  }
2113
- const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
2114
- if (usage.providerTotalAgreement !== expectedAgreement) {
2115
- push(`providerTotalAgreement must be ${expectedAgreement}`);
2233
+ if (typeof value === "number" || typeof value === "boolean") {
2234
+ return String(value);
2116
2235
  }
2117
- });
2118
- var normalizeUsage = (report) => {
2119
- const parsed = usageReportSchema.safeParse(report);
2120
- if (!parsed.success) {
2121
- return {
2122
- status: "invalid",
2123
- issues: parsed.error.issues.map((issue) => ({
2124
- code: "invalid-report",
2125
- message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
2126
- }))
2127
- };
2236
+ if (value !== null && typeof value === "object" && "workspaceId" in value) {
2237
+ const { workspaceId } = value;
2238
+ return typeof workspaceId === "string" ? workspaceId : "<workspace>";
2128
2239
  }
2129
- const input = parsed.data;
2240
+ return "<opaque>";
2241
+ };
2242
+ var resolveInvocationIdentity = (input) => {
2243
+ const parsedClaims = [];
2130
2244
  const issues = [];
2131
- const notes = [];
2132
- const inputTokens = input.inputTokens ?? 0;
2133
- const cachedInputTokens = input.cachedInputTokens ?? 0;
2134
- const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
2135
- const outputTokens = input.outputTokens ?? 0;
2136
- const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
2137
- let accounting;
2138
- if (cacheCreationInputTokens === 0) {
2139
- accounting = input.cacheCreationAccounting ?? "not-reported";
2140
- if (accounting !== "not-reported") {
2141
- notes.push(
2142
- `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
2245
+ for (const [index, claim] of input.claims.entries()) {
2246
+ const parsed2 = identityClaimSchema.safeParse(claim);
2247
+ if (parsed2.success) {
2248
+ parsedClaims.push(parsed2.data);
2249
+ } else {
2250
+ issues.push(
2251
+ `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
2143
2252
  );
2144
2253
  }
2145
- } else if (input.cacheCreationAccounting === void 0) {
2146
- issues.push({
2147
- code: "cache-creation-accounting-missing",
2148
- message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
2149
- });
2150
- accounting = "not-reported";
2151
- } else if (input.cacheCreationAccounting === "not-reported") {
2152
- issues.push({
2153
- code: "cache-creation-accounting-missing",
2154
- message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
2155
- });
2156
- accounting = "not-reported";
2157
- } else {
2158
- accounting = input.cacheCreationAccounting;
2254
+ }
2255
+ if (issues.length > 0) {
2256
+ return { status: "invalid", issues };
2257
+ }
2258
+ const conflicts = [];
2259
+ const selected = {};
2260
+ for (const field of CLAIM_FIELDS) {
2261
+ const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
2262
+ if (contributors.length === 0) {
2263
+ continue;
2264
+ }
2265
+ const bestRank = Math.max(
2266
+ ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
2267
+ );
2268
+ const best = contributors.filter(
2269
+ (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
2270
+ );
2271
+ const rendered = /* @__PURE__ */ new Map();
2272
+ for (const claim of best) {
2273
+ const key = JSON.stringify(claim.fields[field]);
2274
+ const sources = rendered.get(key) ?? [];
2275
+ sources.push(claim.source);
2276
+ rendered.set(key, sources);
2277
+ }
2278
+ if (rendered.size > 1) {
2279
+ const [firstBest] = best;
2280
+ conflicts.push({
2281
+ field,
2282
+ confidence: firstBest?.confidence ?? "none",
2283
+ values: best.map((claim) => renderClaimValue(claim.fields[field])),
2284
+ sources: best.map((claim) => claim.source)
2285
+ });
2286
+ continue;
2287
+ }
2288
+ const [winner] = best;
2289
+ if (winner !== void 0) {
2290
+ selected[field] = winner.fields[field];
2291
+ }
2292
+ }
2293
+ if (conflicts.length > 0) {
2294
+ return { status: "conflict", conflicts };
2295
+ }
2296
+ const missing = [];
2297
+ if (selected.invocationId === void 0) {
2298
+ missing.push("invocationId");
2299
+ }
2300
+ if (selected.sessionId === void 0) {
2301
+ missing.push("sessionId");
2302
+ }
2303
+ if (missing.length > 0) {
2304
+ return { status: "incomplete", missing };
2305
+ }
2306
+ const startedAt = selected.startedAt ?? input.fallback?.startedAt;
2307
+ if (startedAt === void 0) {
2308
+ return { status: "incomplete", missing: ["startedAt"] };
2309
+ }
2310
+ const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
2311
+ const candidate = {
2312
+ invocationId: selected.invocationId,
2313
+ sessionId: selected.sessionId,
2314
+ ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
2315
+ ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
2316
+ ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
2317
+ provenance: input.provenance,
2318
+ workspace,
2319
+ startedAt,
2320
+ consumerAttributes: input.consumerAttributes ?? {}
2321
+ };
2322
+ const parsed = invocationIdentitySchema.safeParse(candidate);
2323
+ if (!parsed.success) {
2324
+ return {
2325
+ status: "invalid",
2326
+ issues: parsed.error.issues.map(
2327
+ (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
2328
+ )
2329
+ };
2330
+ }
2331
+ return { status: "resolved", identity: parsed.data };
2332
+ };
2333
+
2334
+ // src/model/target.ts
2335
+ import { z as z12 } from "zod";
2336
+ var targetSourceSchema = z12.enum(["tool-path", "shell-cwd", "session-cwd"]);
2337
+ var MAX_TARGET_HINT_PATHS = 8;
2338
+ var MAX_TARGET_PATH_LENGTH = 4096;
2339
+ var localPathSchema = z12.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
2340
+ var targetHintSchema = z12.strictObject({
2341
+ source: targetSourceSchema,
2342
+ paths: z12.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
2343
+ /** Absolute directory that relative `paths` resolve against. */
2344
+ baseDirectory: localPathSchema.optional()
2345
+ }).readonly();
2346
+ var sessionCwdHint = (cwd) => cwd === void 0 || cwd.length === 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
2347
+ var worktreeKindSchema = z12.enum(["main", "linked"]);
2348
+ var workspaceTargetSchema = z12.strictObject({
2349
+ workspaceId: workspaceIdSchema,
2350
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
2351
+ vcsBranchName: nonEmptyStringSchema.optional(),
2352
+ source: targetSourceSchema,
2353
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
2354
+ repositoryId: workspaceIdSchema.optional(),
2355
+ worktreeKind: worktreeKindSchema.optional()
2356
+ }).readonly();
2357
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2358
+ var subagentIdSchema = z12.string().regex(SUBAGENT_ID_PATTERN);
2359
+
2360
+ // src/model/usage.ts
2361
+ import { z as z13 } from "zod";
2362
+ var usageTemporalitySchema = z13.enum(["delta", "cumulative"]);
2363
+ var cacheCreationAccountingSchema = z13.enum([
2364
+ "included-in-input",
2365
+ "disjoint-from-input",
2366
+ "not-reported"
2367
+ ]);
2368
+ var providerTotalAgreementSchema = z13.enum(["unreported", "agrees", "disagrees"]);
2369
+ var usageReportSchema = z13.strictObject({
2370
+ temporality: usageTemporalitySchema,
2371
+ /** Inclusive input tokens. */
2372
+ inputTokens: tokenCountSchema.optional(),
2373
+ /** Subset of `inputTokens` served from a prompt cache. */
2374
+ cachedInputTokens: tokenCountSchema.optional(),
2375
+ /** Tokens written to a prompt cache. */
2376
+ cacheCreationInputTokens: tokenCountSchema.optional(),
2377
+ /** Required when `cacheCreationInputTokens` is present and non-zero. */
2378
+ cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
2379
+ /** Inclusive output tokens. */
2380
+ outputTokens: tokenCountSchema.optional(),
2381
+ /** Subset of `outputTokens` spent on reasoning. */
2382
+ reasoningOutputTokens: tokenCountSchema.optional(),
2383
+ /** Total exactly as the provider reported it, if it reported one. */
2384
+ providerTotalTokens: tokenCountSchema.optional()
2385
+ });
2386
+ var canonicalUsageSchema = z13.strictObject({
2387
+ temporality: usageTemporalitySchema,
2388
+ inputTokens: tokenCountSchema,
2389
+ cachedInputTokens: tokenCountSchema,
2390
+ cacheCreationInputTokens: tokenCountSchema,
2391
+ cacheCreationAccounting: cacheCreationAccountingSchema,
2392
+ outputTokens: tokenCountSchema,
2393
+ reasoningOutputTokens: tokenCountSchema,
2394
+ /** Derived: input tokens that were neither cache reads nor cache writes. */
2395
+ uncachedInputTokens: tokenCountSchema,
2396
+ /** Derived: canonical billable total. */
2397
+ totalTokens: tokenCountSchema,
2398
+ providerTotalTokens: tokenCountSchema.optional(),
2399
+ providerTotalAgreement: providerTotalAgreementSchema
2400
+ }).check((ctx) => {
2401
+ const usage = ctx.value;
2402
+ const push = (message) => {
2403
+ ctx.issues.push({ code: "custom", input: usage, message });
2404
+ };
2405
+ if (usage.cachedInputTokens > usage.inputTokens) {
2406
+ push("cachedInputTokens must not exceed inputTokens (it is a subset)");
2407
+ }
2408
+ if (usage.reasoningOutputTokens > usage.outputTokens) {
2409
+ push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
2410
+ }
2411
+ if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
2412
+ push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
2413
+ }
2414
+ const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
2415
+ if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
2416
+ push(
2417
+ "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
2418
+ );
2419
+ }
2420
+ const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
2421
+ if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
2422
+ push(`uncachedInputTokens must equal ${expectedUncached}`);
2423
+ }
2424
+ const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
2425
+ const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
2426
+ if (usage.totalTokens !== expectedTotal) {
2427
+ push(`totalTokens must equal ${expectedTotal}`);
2428
+ }
2429
+ const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
2430
+ if (usage.providerTotalAgreement !== expectedAgreement) {
2431
+ push(`providerTotalAgreement must be ${expectedAgreement}`);
2432
+ }
2433
+ });
2434
+ var normalizeUsage = (report) => {
2435
+ const parsed = usageReportSchema.safeParse(report);
2436
+ if (!parsed.success) {
2437
+ return {
2438
+ status: "invalid",
2439
+ issues: parsed.error.issues.map((issue) => ({
2440
+ code: "invalid-report",
2441
+ message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
2442
+ }))
2443
+ };
2444
+ }
2445
+ const input = parsed.data;
2446
+ const issues = [];
2447
+ const notes = [];
2448
+ const inputTokens = input.inputTokens ?? 0;
2449
+ const cachedInputTokens = input.cachedInputTokens ?? 0;
2450
+ const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
2451
+ const outputTokens = input.outputTokens ?? 0;
2452
+ const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
2453
+ let accounting;
2454
+ if (cacheCreationInputTokens === 0) {
2455
+ accounting = input.cacheCreationAccounting ?? "not-reported";
2456
+ if (accounting !== "not-reported") {
2457
+ notes.push(
2458
+ `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
2459
+ );
2460
+ }
2461
+ } else if (input.cacheCreationAccounting === void 0) {
2462
+ issues.push({
2463
+ code: "cache-creation-accounting-missing",
2464
+ message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
2465
+ });
2466
+ accounting = "not-reported";
2467
+ } else if (input.cacheCreationAccounting === "not-reported") {
2468
+ issues.push({
2469
+ code: "cache-creation-accounting-missing",
2470
+ message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
2471
+ });
2472
+ accounting = "not-reported";
2473
+ } else {
2474
+ accounting = input.cacheCreationAccounting;
2159
2475
  }
2160
2476
  if (cachedInputTokens > inputTokens) {
2161
2477
  issues.push({
@@ -2267,60 +2583,266 @@ var toReport = (usage) => ({
2267
2583
  ...usage.providerTotalTokens === void 0 ? {} : { providerTotalTokens: usage.providerTotalTokens }
2268
2584
  });
2269
2585
 
2270
- // src/runtime/ports.ts
2271
- var appliedDeliverySchema = z10.strictObject({
2272
- callbackId: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
2273
- /** How many of that delivery's observations are folded in, counted from one. */
2274
- applications: z10.number().int().min(1).max(4096)
2275
- });
2276
- var stateValueSchema = z10.discriminatedUnion("kind", [
2277
- z10.strictObject({
2278
- kind: z10.literal("usage-cumulative"),
2279
- usage: canonicalUsageSchema,
2280
- /**
2281
- * Optional: absent on every record written before this field existed, which
2282
- * reads as "unknown provenance" and simply forgoes the idempotency check
2283
- * rather than resetting a baseline to gain it.
2284
- */
2285
- appliedDelivery: appliedDeliverySchema.optional()
2286
- }),
2287
- z10.strictObject({
2288
- kind: z10.literal("sequence"),
2289
- next: sequenceNumberSchema
2290
- }),
2291
- z10.strictObject({
2292
- kind: z10.literal("attributes"),
2293
- attributes: attributesSchema
2294
- })
2295
- ]);
2296
- var stateRecordSchema = z10.strictObject({
2297
- /** Incremented on each write; lets callers detect lost updates. */
2298
- revision: z10.number().int().min(0),
2299
- updatedAt: epochMillisSchema,
2300
- value: stateValueSchema
2301
- });
2302
- var logLevelSchema = z10.enum(["silent", "error", "warn", "info", "debug"]);
2303
- var LOG_LEVEL_RANK = Object.freeze({
2304
- silent: 0,
2305
- error: 1,
2306
- warn: 2,
2307
- info: 3,
2308
- debug: 4
2309
- });
2586
+ // src/model/version.ts
2587
+ import { z as z14 } from "zod";
2588
+ var CANONICAL_SCHEMA_VERSION = 1;
2589
+ var canonicalSchemaVersionSchema = z14.literal(CANONICAL_SCHEMA_VERSION);
2310
2590
 
2311
- // src/runtime/logger.ts
2312
- var createNullLogger = () => ({
2313
- error: () => void 0,
2314
- warn: () => void 0,
2315
- info: () => void 0,
2316
- debug: () => void 0
2591
+ // src/model/events.ts
2592
+ var modelDescriptorSchema = z15.strictObject({
2593
+ modelId: nonEmptyStringSchema,
2594
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
2595
+ vendor: nonEmptyStringSchema.optional(),
2596
+ family: nonEmptyStringSchema.optional()
2317
2597
  });
2318
- var createStderrLogger = (options = {}) => {
2319
- const level = options.level ?? "warn";
2320
- const write = options.write ?? ((line) => {
2321
- process.stderr.write(line);
2322
- });
2323
- const threshold = LOG_LEVEL_RANK[level];
2598
+ var costFactsSchema = z15.strictObject({
2599
+ /** ISO 4217 code. */
2600
+ currency: z15.string().length(3),
2601
+ amount: z15.number().min(0).finite(),
2602
+ source: z15.enum(["provider-reported", "computed"])
2603
+ });
2604
+ var canonicalEventTypeSchema = z15.enum([
2605
+ "session.start",
2606
+ "session.end",
2607
+ "prompt.submitted",
2608
+ "generation.start",
2609
+ "generation.end",
2610
+ "tool.start",
2611
+ "tool.end",
2612
+ "subagent.start",
2613
+ "subagent.end",
2614
+ "compaction.performed",
2615
+ "error.raised"
2616
+ ]);
2617
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
2618
+ var outcomeSchema = z15.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
2619
+ var baseEventFields = {
2620
+ schemaVersion: canonicalSchemaVersionSchema,
2621
+ eventId: eventIdSchema,
2622
+ invocationId: invocationIdSchema,
2623
+ sessionId: sessionIdSchema,
2624
+ /** Per-invocation ordering key. Stable across replays of the same input. */
2625
+ sequence: sequenceNumberSchema,
2626
+ occurredAt: epochMillisSchema,
2627
+ provenance: sourceProvenanceSchema,
2628
+ workspace: workspaceIdentitySchema,
2629
+ /**
2630
+ * The provider's own id for the subagent this event was emitted inside (e.g.
2631
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
2632
+ * factory, never by hand.
2633
+ */
2634
+ subagentId: subagentIdSchema.optional(),
2635
+ extensions: extensionsSchema.default(emptyExtensions)
2636
+ };
2637
+ var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
2638
+ var sessionStartEventSchema = event({
2639
+ type: z15.literal("session.start"),
2640
+ sessionKind: z15.enum(["interactive", "non-interactive", "unknown"]),
2641
+ agentName: nonEmptyStringSchema.optional(),
2642
+ agentVersion: nonEmptyStringSchema.optional(),
2643
+ model: modelDescriptorSchema.optional(),
2644
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
2645
+ target: workspaceTargetSchema.optional()
2646
+ });
2647
+ var sessionEndEventSchema = event({
2648
+ type: z15.literal("session.end"),
2649
+ reason: z15.enum(["completed", "aborted", "error", "timeout", "unknown"]),
2650
+ durationMillis: durationMillisSchema.optional(),
2651
+ /** Session totals, typically cumulative. */
2652
+ usage: canonicalUsageSchema.optional(),
2653
+ cost: costFactsSchema.optional()
2654
+ });
2655
+ var promptSubmittedEventSchema = event({
2656
+ type: z15.literal("prompt.submitted"),
2657
+ promptSource: z15.enum(["user", "automation", "resumed", "unknown"]),
2658
+ content: contentFactSchema.optional(),
2659
+ turnIndex: z15.number().int().min(0).optional(),
2660
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
2661
+ target: workspaceTargetSchema.optional()
2662
+ });
2663
+ var generationStartEventSchema = event({
2664
+ type: z15.literal("generation.start"),
2665
+ generationId: nonEmptyStringSchema,
2666
+ model: modelDescriptorSchema,
2667
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
2668
+ inputContent: contentFactsSchema.optional()
2669
+ });
2670
+ var generationEndEventSchema = event({
2671
+ type: z15.literal("generation.end"),
2672
+ generationId: nonEmptyStringSchema,
2673
+ model: modelDescriptorSchema,
2674
+ outcome: outcomeSchema,
2675
+ stopReason: nonEmptyStringSchema.optional(),
2676
+ durationMillis: durationMillisSchema.optional(),
2677
+ usage: canonicalUsageSchema.optional(),
2678
+ /**
2679
+ * True when `usage` is known to cover only part of the generation (for
2680
+ * example the last model request of a multi-request turn); false when the
2681
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
2682
+ * without `usage`.
2683
+ */
2684
+ usagePartial: z15.boolean().optional(),
2685
+ cost: costFactsSchema.optional(),
2686
+ outputContent: contentFactsSchema.optional()
2687
+ });
2688
+ var toolKindSchema = z15.enum([
2689
+ "read",
2690
+ "write",
2691
+ "execute",
2692
+ "search",
2693
+ "network",
2694
+ "delegate",
2695
+ "other",
2696
+ "unknown"
2697
+ ]);
2698
+ var toolStartEventSchema = event({
2699
+ type: z15.literal("tool.start"),
2700
+ toolCallId: nonEmptyStringSchema,
2701
+ toolName: nonEmptyStringSchema,
2702
+ toolKind: toolKindSchema,
2703
+ generationId: nonEmptyStringSchema.optional(),
2704
+ input: contentFactSchema.optional(),
2705
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
2706
+ target: workspaceTargetSchema.optional()
2707
+ });
2708
+ var toolEndEventSchema = event({
2709
+ type: z15.literal("tool.end"),
2710
+ toolCallId: nonEmptyStringSchema,
2711
+ toolName: nonEmptyStringSchema,
2712
+ outcome: outcomeSchema,
2713
+ durationMillis: durationMillisSchema.optional(),
2714
+ /** Present when the host asked for or recorded a permission decision. */
2715
+ permissionDecision: z15.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
2716
+ output: contentFactSchema.optional(),
2717
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
2718
+ target: workspaceTargetSchema.optional()
2719
+ });
2720
+ var subagentStartEventSchema = event({
2721
+ type: z15.literal("subagent.start"),
2722
+ subagentInvocationId: invocationIdSchema,
2723
+ subagentType: nonEmptyStringSchema.optional(),
2724
+ /** 0 for the top-level agent; 1 for its direct children. */
2725
+ delegationDepth: z15.number().int().min(0).max(64),
2726
+ model: modelDescriptorSchema.optional()
2727
+ });
2728
+ var subagentEndEventSchema = event({
2729
+ type: z15.literal("subagent.end"),
2730
+ subagentInvocationId: invocationIdSchema,
2731
+ outcome: outcomeSchema,
2732
+ durationMillis: durationMillisSchema.optional(),
2733
+ usage: canonicalUsageSchema.optional()
2734
+ });
2735
+ var compactionPerformedEventSchema = event({
2736
+ type: z15.literal("compaction.performed"),
2737
+ trigger: z15.enum(["automatic", "manual", "unknown"]),
2738
+ /** Provider-reported context size before and after compaction, if known. */
2739
+ contextTokensBefore: tokenCountSchema.optional(),
2740
+ contextTokensAfter: tokenCountSchema.optional(),
2741
+ droppedMessageCount: z15.number().int().min(0).optional(),
2742
+ usage: canonicalUsageSchema.optional()
2743
+ });
2744
+ var errorRaisedEventSchema = event({
2745
+ type: z15.literal("error.raised"),
2746
+ errorCode: otelHookErrorCodeSchema,
2747
+ severity: errorSeveritySchema,
2748
+ phase: errorPhaseSchema,
2749
+ retryable: z15.boolean(),
2750
+ /** Error text is content: it is described, never embedded verbatim by default. */
2751
+ message: contentFactSchema.optional(),
2752
+ /** Non-sensitive, provider-agnostic short label. */
2753
+ detail: nonEmptyStringSchema.optional()
2754
+ });
2755
+ var canonicalEventSchema = z15.discriminatedUnion("type", [
2756
+ sessionStartEventSchema,
2757
+ sessionEndEventSchema,
2758
+ promptSubmittedEventSchema,
2759
+ generationStartEventSchema,
2760
+ generationEndEventSchema,
2761
+ toolStartEventSchema,
2762
+ toolEndEventSchema,
2763
+ subagentStartEventSchema,
2764
+ subagentEndEventSchema,
2765
+ compactionPerformedEventSchema,
2766
+ errorRaisedEventSchema
2767
+ ]);
2768
+ var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
2769
+ var TARGETED = new Set(TARGETED_EVENT_TYPES);
2770
+ var isTargetedEvent = (event3) => TARGETED.has(event3.type);
2771
+
2772
+ // src/runtime/ports.ts
2773
+ var appliedDeliverySchema = z16.strictObject({
2774
+ callbackId: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
2775
+ /** How many of that delivery's observations are folded in, counted from one. */
2776
+ applications: z16.number().int().min(1).max(4096)
2777
+ });
2778
+ var stateValueSchema = z16.discriminatedUnion("kind", [
2779
+ z16.strictObject({
2780
+ kind: z16.literal("usage-cumulative"),
2781
+ usage: canonicalUsageSchema,
2782
+ /**
2783
+ * Optional: absent on every record written before this field existed, which
2784
+ * reads as "unknown provenance" and simply forgoes the idempotency check
2785
+ * rather than resetting a baseline to gain it.
2786
+ */
2787
+ appliedDelivery: appliedDeliverySchema.optional()
2788
+ }),
2789
+ z16.strictObject({
2790
+ kind: z16.literal("sequence"),
2791
+ next: sequenceNumberSchema
2792
+ }),
2793
+ z16.strictObject({
2794
+ kind: z16.literal("attributes"),
2795
+ attributes: attributesSchema
2796
+ }),
2797
+ /**
2798
+ * The model a session last reported, so a later invocation whose payload names
2799
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
2800
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
2801
+ * bounded canonical shape, never a payload fragment.
2802
+ */
2803
+ z16.strictObject({
2804
+ kind: z16.literal("session-model"),
2805
+ model: modelDescriptorSchema
2806
+ }),
2807
+ /**
2808
+ * How far a {@link PayloadEnricher} has read a session's append-only source
2809
+ * (Claude Code's transcript), so the next read starts where the last ended.
2810
+ * `source` is an opaque digest of what was read, never a path.
2811
+ */
2812
+ z16.strictObject({
2813
+ kind: z16.literal("read-cursor"),
2814
+ source: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
2815
+ offset: z16.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
2816
+ })
2817
+ ]);
2818
+ var stateRecordSchema = z16.strictObject({
2819
+ /** Incremented on each write; lets callers detect lost updates. */
2820
+ revision: z16.number().int().min(0),
2821
+ updatedAt: epochMillisSchema,
2822
+ value: stateValueSchema
2823
+ });
2824
+ var logLevelSchema = z16.enum(["silent", "error", "warn", "info", "debug"]);
2825
+ var LOG_LEVEL_RANK = Object.freeze({
2826
+ silent: 0,
2827
+ error: 1,
2828
+ warn: 2,
2829
+ info: 3,
2830
+ debug: 4
2831
+ });
2832
+
2833
+ // src/runtime/logger.ts
2834
+ var createNullLogger = () => ({
2835
+ error: () => void 0,
2836
+ warn: () => void 0,
2837
+ info: () => void 0,
2838
+ debug: () => void 0
2839
+ });
2840
+ var createStderrLogger = (options = {}) => {
2841
+ const level = options.level ?? "warn";
2842
+ const write = options.write ?? ((line) => {
2843
+ process.stderr.write(line);
2844
+ });
2845
+ const threshold = LOG_LEVEL_RANK[level];
2324
2846
  const log = (entryLevel, message, fields) => {
2325
2847
  if (LOG_LEVEL_RANK[entryLevel] > threshold || threshold === 0) {
2326
2848
  return;
@@ -2408,7 +2930,8 @@ var policyFlagsToPatch = (policy) => {
2408
2930
  return {
2409
2931
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
2410
2932
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
2411
- ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
2933
+ ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
2934
+ ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {}
2412
2935
  };
2413
2936
  };
2414
2937
  var resolveCliExporterHeaders = (policy, io) => {
@@ -2543,59 +3066,8 @@ var summarizeHealth = (snapshots) => ({
2543
3066
  subsystems: [...snapshots]
2544
3067
  });
2545
3068
 
2546
- // src/model/version.ts
2547
- import { z as z11 } from "zod";
2548
- var CANONICAL_SCHEMA_VERSION = 1;
2549
- var canonicalSchemaVersionSchema = z11.literal(CANONICAL_SCHEMA_VERSION);
2550
-
2551
3069
  // src/privacy/service.ts
2552
3070
  import { createHash } from "crypto";
2553
-
2554
- // src/model/extensions.ts
2555
- import { z as z12 } from "zod";
2556
- var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
2557
- var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
2558
- "otelhook",
2559
- "otel",
2560
- "telemetry"
2561
- ]);
2562
- var MAX_EXTENSION_ENTRIES = 64;
2563
- var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
2564
- var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
2565
- var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
2566
- var extensionsSchema = z12.record(z12.string(), attributeValueSchema).check((ctx) => {
2567
- const keys = Object.keys(ctx.value);
2568
- if (keys.length > MAX_EXTENSION_ENTRIES) {
2569
- ctx.issues.push({
2570
- code: "custom",
2571
- input: ctx.value,
2572
- message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
2573
- });
2574
- }
2575
- for (const key of keys) {
2576
- if (!EXTENSION_KEY_PATTERN.test(key)) {
2577
- ctx.issues.push({
2578
- code: "custom",
2579
- input: ctx.value,
2580
- path: [key],
2581
- message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
2582
- });
2583
- continue;
2584
- }
2585
- if (isReservedExtensionNamespace(key)) {
2586
- ctx.issues.push({
2587
- code: "custom",
2588
- input: ctx.value,
2589
- path: [key],
2590
- message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
2591
- });
2592
- }
2593
- }
2594
- });
2595
- var EMPTY_EXTENSIONS = Object.freeze({});
2596
- var emptyExtensions = () => ({});
2597
-
2598
- // src/privacy/service.ts
2599
3071
  var compilePatterns = (sources, flags) => {
2600
3072
  const compiled = [];
2601
3073
  for (const source of sources) {
@@ -2813,11 +3285,11 @@ var createPrivacyService = (policyInput) => {
2813
3285
  };
2814
3286
  const flattenToAttributes = (value, prefix) => {
2815
3287
  const attributes = {};
2816
- const walk = (current, path13) => {
3288
+ const walk = (current, path14) => {
2817
3289
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2818
3290
  const primitive = toAttributePrimitive(current);
2819
3291
  if (primitive !== void 0) {
2820
- attributes[path13] = primitive;
3292
+ attributes[path14] = primitive;
2821
3293
  }
2822
3294
  return;
2823
3295
  }
@@ -2836,16 +3308,16 @@ var createPrivacyService = (policyInput) => {
2836
3308
  primitives.push(entryPrimitive);
2837
3309
  }
2838
3310
  if (uniform) {
2839
- attributes[path13] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3311
+ attributes[path14] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2840
3312
  return;
2841
3313
  }
2842
3314
  for (const [index, entry] of current.entries()) {
2843
- walk(entry, `${path13}.${index}`);
3315
+ walk(entry, `${path14}.${index}`);
2844
3316
  }
2845
3317
  return;
2846
3318
  }
2847
3319
  for (const [key, entry] of Object.entries(current)) {
2848
- walk(entry, path13 === "" ? key : `${path13}.${key}`);
3320
+ walk(entry, path14 === "" ? key : `${path14}.${key}`);
2849
3321
  }
2850
3322
  };
2851
3323
  walk(value, prefix);
@@ -2880,532 +3352,112 @@ var createPrivacyService = (policyInput) => {
2880
3352
  if (isSecretKey(key)) {
2881
3353
  extensions[key] = policy.redactionPlaceholder;
2882
3354
  continue;
2883
- }
2884
- const sanitized = sanitizeStructured(entry).value;
2885
- const candidate = attributeValueSchema.safeParse(sanitized);
2886
- if (candidate.success) {
2887
- extensions[key] = candidate.data;
2888
- } else {
2889
- droppedKeys.push(key);
2890
- }
2891
- }
2892
- return { extensions, droppedKeys };
2893
- };
2894
- return {
2895
- policy,
2896
- policyNotes: notes,
2897
- hash,
2898
- deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
2899
- describeContent: describeText,
2900
- describeUnavailableContent: (input) => ({
2901
- kind: input.kind,
2902
- ...input.role === void 0 ? {} : { role: input.role },
2903
- characterLength: 0,
2904
- byteLength: 0,
2905
- contentHash: hash(""),
2906
- disclosure: "omitted",
2907
- truncated: false,
2908
- secretsRedacted: 0,
2909
- ...input.label === void 0 ? {} : { label: input.label }
2910
- }),
2911
- describeStructured: (input) => {
2912
- const serialized = stableStringify(input.value);
2913
- const sanitized = sanitizeStructured(input.value);
2914
- const base = describeText({
2915
- kind: input.kind,
2916
- text: serialized,
2917
- ...input.role === void 0 ? {} : { role: input.role },
2918
- ...input.label === void 0 ? {} : { label: input.label }
2919
- });
2920
- if (base.text === void 0) {
2921
- return base;
2922
- }
2923
- const disclosed = disclose(stableStringify(sanitized.value));
2924
- return {
2925
- ...base,
2926
- ...disclosed.text === void 0 ? {} : { text: disclosed.text },
2927
- truncated: base.truncated || disclosed.truncated,
2928
- secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
2929
- };
2930
- },
2931
- isSecretKey,
2932
- sanitizeStructured,
2933
- flattenToAttributes,
2934
- sanitizeAttributes,
2935
- sanitizeExtensions,
2936
- boundString
2937
- };
2938
- };
2939
-
2940
- // src/model/identity.ts
2941
- import { z as z13 } from "zod";
2942
- var workspaceKeySourceSchema = z13.enum([
2943
- "git-remote",
2944
- "git-root",
2945
- "working-directory",
2946
- "explicit",
2947
- "unknown"
2948
- ]);
2949
- var workspaceIdentitySchema = z13.strictObject({
2950
- workspaceId: workspaceIdSchema,
2951
- keySource: workspaceKeySourceSchema,
2952
- /** Repository name only; never an owner path or URL with credentials. */
2953
- repositoryName: nonEmptyStringSchema.optional(),
2954
- vcsBranchName: nonEmptyStringSchema.optional(),
2955
- /** Opaque handle for the checked-out revision. */
2956
- vcsRevisionId: nonEmptyStringSchema.optional()
2957
- }).readonly();
2958
- var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
2959
- var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
2960
- workspaceId: UNKNOWN_WORKSPACE_ID,
2961
- keySource: "unknown"
2962
- });
2963
- var sourceProvenanceSchema = z13.strictObject({
2964
- providerId: resolvedProviderIdSchema,
2965
- providerVersion: nonEmptyStringSchema.optional(),
2966
- adapterId: nonEmptyStringSchema,
2967
- adapterVersion: nonEmptyStringSchema,
2968
- detectionConfidence: detectionConfidenceSchema,
2969
- /** The provider's own name for the source event, e.g. a hook event name. */
2970
- sourceEventName: nonEmptyStringSchema.optional(),
2971
- transport: sourceTransportSchema
2972
- }).readonly();
2973
- var consumerAttributesSchema = attributesSchema.readonly();
2974
- var invocationIdentitySchema = z13.strictObject({
2975
- invocationId: invocationIdSchema,
2976
- sessionId: sessionIdSchema,
2977
- /** Set when this invocation runs beneath another agent invocation. */
2978
- parentInvocationId: invocationIdSchema.optional(),
2979
- /** Root of the session tree when the provider exposes one. */
2980
- rootSessionId: sessionIdSchema.optional(),
2981
- /** Stable handle for the agent process/instance, when available. */
2982
- agentInstanceId: nonEmptyStringSchema.optional(),
2983
- provenance: sourceProvenanceSchema,
2984
- workspace: workspaceIdentitySchema,
2985
- startedAt: epochMillisSchema,
2986
- consumerAttributes: consumerAttributesSchema
2987
- }).readonly();
2988
- var identityClaimFieldsSchema = z13.strictObject({
2989
- invocationId: invocationIdSchema.optional(),
2990
- sessionId: sessionIdSchema.optional(),
2991
- parentInvocationId: invocationIdSchema.optional(),
2992
- rootSessionId: sessionIdSchema.optional(),
2993
- agentInstanceId: nonEmptyStringSchema.optional(),
2994
- workspace: workspaceIdentitySchema.optional(),
2995
- startedAt: epochMillisSchema.optional()
2996
- });
2997
- var identityClaimSchema = z13.strictObject({
2998
- /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
2999
- source: nonEmptyStringSchema,
3000
- confidence: detectionConfidenceSchema,
3001
- fields: identityClaimFieldsSchema
3002
- });
3003
- var CLAIM_FIELDS = [
3004
- "invocationId",
3005
- "sessionId",
3006
- "parentInvocationId",
3007
- "rootSessionId",
3008
- "agentInstanceId",
3009
- "workspace",
3010
- "startedAt"
3011
- ];
3012
- var renderClaimValue = (value) => {
3013
- if (typeof value === "string") {
3014
- return value;
3015
- }
3016
- if (typeof value === "number" || typeof value === "boolean") {
3017
- return String(value);
3018
- }
3019
- if (value !== null && typeof value === "object" && "workspaceId" in value) {
3020
- const { workspaceId } = value;
3021
- return typeof workspaceId === "string" ? workspaceId : "<workspace>";
3022
- }
3023
- return "<opaque>";
3024
- };
3025
- var resolveInvocationIdentity = (input) => {
3026
- const parsedClaims = [];
3027
- const issues = [];
3028
- for (const [index, claim] of input.claims.entries()) {
3029
- const parsed2 = identityClaimSchema.safeParse(claim);
3030
- if (parsed2.success) {
3031
- parsedClaims.push(parsed2.data);
3032
- } else {
3033
- issues.push(
3034
- `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
3035
- );
3036
- }
3037
- }
3038
- if (issues.length > 0) {
3039
- return { status: "invalid", issues };
3040
- }
3041
- const conflicts = [];
3042
- const selected = {};
3043
- for (const field of CLAIM_FIELDS) {
3044
- const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
3045
- if (contributors.length === 0) {
3046
- continue;
3047
- }
3048
- const bestRank = Math.max(
3049
- ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
3050
- );
3051
- const best = contributors.filter(
3052
- (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
3053
- );
3054
- const rendered = /* @__PURE__ */ new Map();
3055
- for (const claim of best) {
3056
- const key = JSON.stringify(claim.fields[field]);
3057
- const sources = rendered.get(key) ?? [];
3058
- sources.push(claim.source);
3059
- rendered.set(key, sources);
3060
- }
3061
- if (rendered.size > 1) {
3062
- const [firstBest] = best;
3063
- conflicts.push({
3064
- field,
3065
- confidence: firstBest?.confidence ?? "none",
3066
- values: best.map((claim) => renderClaimValue(claim.fields[field])),
3067
- sources: best.map((claim) => claim.source)
3068
- });
3069
- continue;
3070
- }
3071
- const [winner] = best;
3072
- if (winner !== void 0) {
3073
- selected[field] = winner.fields[field];
3074
- }
3075
- }
3076
- if (conflicts.length > 0) {
3077
- return { status: "conflict", conflicts };
3078
- }
3079
- const missing = [];
3080
- if (selected.invocationId === void 0) {
3081
- missing.push("invocationId");
3082
- }
3083
- if (selected.sessionId === void 0) {
3084
- missing.push("sessionId");
3085
- }
3086
- if (missing.length > 0) {
3087
- return { status: "incomplete", missing };
3088
- }
3089
- const startedAt = selected.startedAt ?? input.fallback?.startedAt;
3090
- if (startedAt === void 0) {
3091
- return { status: "incomplete", missing: ["startedAt"] };
3092
- }
3093
- const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
3094
- const candidate = {
3095
- invocationId: selected.invocationId,
3096
- sessionId: selected.sessionId,
3097
- ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
3098
- ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
3099
- ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
3100
- provenance: input.provenance,
3101
- workspace,
3102
- startedAt,
3103
- consumerAttributes: input.consumerAttributes ?? {}
3104
- };
3105
- const parsed = invocationIdentitySchema.safeParse(candidate);
3106
- if (!parsed.success) {
3107
- return {
3108
- status: "invalid",
3109
- issues: parsed.error.issues.map(
3110
- (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
3111
- )
3112
- };
3113
- }
3114
- return { status: "resolved", identity: parsed.data };
3115
- };
3116
-
3117
- // src/privacy/workspace.ts
3118
- var canonicalizeGitRemote = (remoteUrl) => {
3119
- const trimmed = remoteUrl.trim();
3120
- const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);
3121
- const withoutScheme = scpLike ? `${scpLike[2] ?? ""}/${scpLike[3] ?? ""}` : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/^[^@/]+@/, "");
3122
- return withoutScheme.replace(/:\d+\//, "/").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
3123
- };
3124
- var keySourceOf = (input) => {
3125
- switch (input.kind) {
3126
- case "git-remote":
3127
- return "git-remote";
3128
- case "git-root":
3129
- return "git-root";
3130
- case "working-directory":
3131
- return "working-directory";
3132
- case "explicit":
3133
- return "explicit";
3134
- case "unknown":
3135
- return "unknown";
3136
- }
3137
- };
3138
- var keyMaterialOf = (input) => {
3139
- switch (input.kind) {
3140
- case "git-remote":
3141
- return canonicalizeGitRemote(input.remoteUrl);
3142
- case "git-root":
3143
- case "working-directory":
3144
- return input.absolutePath.replace(/[/\\]+$/, "");
3145
- case "explicit":
3146
- return input.value;
3147
- case "unknown":
3148
- return void 0;
3149
- }
3150
- };
3151
- var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
3152
- const keySource = keySourceOf(input);
3153
- const material = keyMaterialOf(input);
3154
- const workspaceId = material === void 0 || material === "" ? "unknown:0000000000000000" : privacy.deriveOpaqueId(`workspace/${keySource}`, material);
3155
- return workspaceIdentitySchema.parse({
3156
- workspaceId,
3157
- keySource: material === void 0 || material === "" ? "unknown" : keySource,
3158
- ...labels.repositoryName === void 0 ? {} : { repositoryName: labels.repositoryName.slice(0, 128) },
3159
- ...labels.vcsBranchName === void 0 ? {} : { vcsBranchName: labels.vcsBranchName.slice(0, 128) },
3160
- ...labels.vcsRevisionId === void 0 ? {} : { vcsRevisionId: privacy.deriveOpaqueId("workspace/revision", labels.vcsRevisionId) }
3161
- });
3162
- };
3163
-
3164
- // src/providers/adapter.ts
3165
- import { z as z17 } from "zod";
3166
-
3167
- // src/model/events.ts
3168
- import { z as z16 } from "zod";
3169
-
3170
- // src/model/content.ts
3171
- import { z as z14 } from "zod";
3172
- var contentKindSchema = z14.enum([
3173
- "prompt",
3174
- "response",
3175
- "reasoning",
3176
- "tool-input",
3177
- "tool-output",
3178
- "error-message",
3179
- "system-instruction",
3180
- "attachment"
3181
- ]);
3182
- var contentRoleSchema = z14.enum(["user", "assistant", "system", "tool", "unknown"]);
3183
- var contentDisclosureSchema = z14.enum(["omitted", "masked", "redacted", "raw"]);
3184
- var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
3185
- var contentFactSchema = z14.strictObject({
3186
- kind: contentKindSchema,
3187
- role: contentRoleSchema.optional(),
3188
- /** Unicode code point count of the original content. */
3189
- characterLength: z14.number().int().min(0),
3190
- /** UTF-8 byte length of the original content. */
3191
- byteLength: z14.number().int().min(0),
3192
- /** Stable salted digest of the original content. */
3193
- contentHash: z14.string().regex(CONTENT_HASH_PATTERN),
3194
- disclosure: contentDisclosureSchema,
3195
- /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
3196
- text: z14.string().optional(),
3197
- /** True when `text` was cut short by the configured string bound. */
3198
- truncated: z14.boolean(),
3199
- /** Number of secret-looking spans replaced while producing `text`. */
3200
- secretsRedacted: z14.number().int().min(0),
3201
- /** Optional non-sensitive label, e.g. a MIME type or tool name. */
3202
- label: nonEmptyStringSchema.optional()
3203
- });
3204
- var contentFactsSchema = z14.array(contentFactSchema).max(64);
3205
- var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
3206
- var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
3207
-
3208
- // src/model/target.ts
3209
- import { z as z15 } from "zod";
3210
- var targetSourceSchema = z15.enum(["tool-path", "shell-cwd", "session-cwd"]);
3211
- var MAX_TARGET_HINT_PATHS = 8;
3212
- var MAX_TARGET_PATH_LENGTH = 4096;
3213
- var localPathSchema = z15.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
3214
- var targetHintSchema = z15.strictObject({
3215
- source: targetSourceSchema,
3216
- paths: z15.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
3217
- /** Absolute directory that relative `paths` resolve against. */
3218
- baseDirectory: localPathSchema.optional()
3219
- }).readonly();
3220
- var sessionCwdHint = (cwd) => cwd === void 0 || cwd.length === 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
3221
- var worktreeKindSchema = z15.enum(["main", "linked"]);
3222
- var workspaceTargetSchema = z15.strictObject({
3223
- workspaceId: workspaceIdSchema,
3224
- /** Branch checked out in that worktree; absent on a detached HEAD. */
3225
- vcsBranchName: nonEmptyStringSchema.optional(),
3226
- source: targetSourceSchema,
3227
- /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
3228
- repositoryId: workspaceIdSchema.optional(),
3229
- worktreeKind: worktreeKindSchema.optional()
3230
- }).readonly();
3231
- var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
3232
- var subagentIdSchema = z15.string().regex(SUBAGENT_ID_PATTERN);
3233
-
3234
- // src/model/events.ts
3235
- var modelDescriptorSchema = z16.strictObject({
3236
- modelId: nonEmptyStringSchema,
3237
- /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
3238
- vendor: nonEmptyStringSchema.optional(),
3239
- family: nonEmptyStringSchema.optional()
3240
- });
3241
- var costFactsSchema = z16.strictObject({
3242
- /** ISO 4217 code. */
3243
- currency: z16.string().length(3),
3244
- amount: z16.number().min(0).finite(),
3245
- source: z16.enum(["provider-reported", "computed"])
3246
- });
3247
- var canonicalEventTypeSchema = z16.enum([
3248
- "session.start",
3249
- "session.end",
3250
- "prompt.submitted",
3251
- "generation.start",
3252
- "generation.end",
3253
- "tool.start",
3254
- "tool.end",
3255
- "subagent.start",
3256
- "subagent.end",
3257
- "compaction.performed",
3258
- "error.raised"
3259
- ]);
3260
- var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
3261
- var outcomeSchema = z16.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
3262
- var baseEventFields = {
3263
- schemaVersion: canonicalSchemaVersionSchema,
3264
- eventId: eventIdSchema,
3265
- invocationId: invocationIdSchema,
3266
- sessionId: sessionIdSchema,
3267
- /** Per-invocation ordering key. Stable across replays of the same input. */
3268
- sequence: sequenceNumberSchema,
3269
- occurredAt: epochMillisSchema,
3270
- provenance: sourceProvenanceSchema,
3271
- workspace: workspaceIdentitySchema,
3272
- /**
3273
- * The provider's own id for the subagent this event was emitted inside (e.g.
3274
- * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
3275
- * factory, never by hand.
3276
- */
3277
- subagentId: subagentIdSchema.optional(),
3278
- extensions: extensionsSchema.default(emptyExtensions)
3279
- };
3280
- var event = (shape) => z16.strictObject({ ...baseEventFields, ...shape });
3281
- var sessionStartEventSchema = event({
3282
- type: z16.literal("session.start"),
3283
- sessionKind: z16.enum(["interactive", "non-interactive", "unknown"]),
3284
- agentName: nonEmptyStringSchema.optional(),
3285
- agentVersion: nonEmptyStringSchema.optional(),
3286
- model: modelDescriptorSchema.optional(),
3287
- /** The git worktree the session runs in, resolved by the core (ADR 0008). */
3288
- target: workspaceTargetSchema.optional()
3289
- });
3290
- var sessionEndEventSchema = event({
3291
- type: z16.literal("session.end"),
3292
- reason: z16.enum(["completed", "aborted", "error", "timeout", "unknown"]),
3293
- durationMillis: durationMillisSchema.optional(),
3294
- /** Session totals, typically cumulative. */
3295
- usage: canonicalUsageSchema.optional(),
3296
- cost: costFactsSchema.optional()
3297
- });
3298
- var promptSubmittedEventSchema = event({
3299
- type: z16.literal("prompt.submitted"),
3300
- promptSource: z16.enum(["user", "automation", "resumed", "unknown"]),
3301
- content: contentFactSchema.optional(),
3302
- turnIndex: z16.number().int().min(0).optional(),
3303
- /** The git worktree the session runs in, resolved by the core (ADR 0008). */
3304
- target: workspaceTargetSchema.optional()
3305
- });
3306
- var generationStartEventSchema = event({
3307
- type: z16.literal("generation.start"),
3308
- generationId: nonEmptyStringSchema,
3309
- model: modelDescriptorSchema,
3310
- requestedMaxOutputTokens: tokenCountSchema.optional(),
3311
- inputContent: contentFactsSchema.optional()
3312
- });
3313
- var generationEndEventSchema = event({
3314
- type: z16.literal("generation.end"),
3315
- generationId: nonEmptyStringSchema,
3316
- model: modelDescriptorSchema,
3317
- outcome: outcomeSchema,
3318
- stopReason: nonEmptyStringSchema.optional(),
3319
- durationMillis: durationMillisSchema.optional(),
3320
- usage: canonicalUsageSchema.optional(),
3321
- cost: costFactsSchema.optional(),
3322
- outputContent: contentFactsSchema.optional()
3323
- });
3324
- var toolKindSchema = z16.enum([
3325
- "read",
3326
- "write",
3327
- "execute",
3328
- "search",
3329
- "network",
3330
- "delegate",
3331
- "other",
3332
- "unknown"
3333
- ]);
3334
- var toolStartEventSchema = event({
3335
- type: z16.literal("tool.start"),
3336
- toolCallId: nonEmptyStringSchema,
3337
- toolName: nonEmptyStringSchema,
3338
- toolKind: toolKindSchema,
3339
- generationId: nonEmptyStringSchema.optional(),
3340
- input: contentFactSchema.optional(),
3341
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3342
- target: workspaceTargetSchema.optional()
3343
- });
3344
- var toolEndEventSchema = event({
3345
- type: z16.literal("tool.end"),
3346
- toolCallId: nonEmptyStringSchema,
3347
- toolName: nonEmptyStringSchema,
3348
- outcome: outcomeSchema,
3349
- durationMillis: durationMillisSchema.optional(),
3350
- /** Present when the host asked for or recorded a permission decision. */
3351
- permissionDecision: z16.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
3352
- output: contentFactSchema.optional(),
3353
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3354
- target: workspaceTargetSchema.optional()
3355
- });
3356
- var subagentStartEventSchema = event({
3357
- type: z16.literal("subagent.start"),
3358
- subagentInvocationId: invocationIdSchema,
3359
- subagentType: nonEmptyStringSchema.optional(),
3360
- /** 0 for the top-level agent; 1 for its direct children. */
3361
- delegationDepth: z16.number().int().min(0).max(64),
3362
- model: modelDescriptorSchema.optional()
3363
- });
3364
- var subagentEndEventSchema = event({
3365
- type: z16.literal("subagent.end"),
3366
- subagentInvocationId: invocationIdSchema,
3367
- outcome: outcomeSchema,
3368
- durationMillis: durationMillisSchema.optional(),
3369
- usage: canonicalUsageSchema.optional()
3370
- });
3371
- var compactionPerformedEventSchema = event({
3372
- type: z16.literal("compaction.performed"),
3373
- trigger: z16.enum(["automatic", "manual", "unknown"]),
3374
- /** Provider-reported context size before and after compaction, if known. */
3375
- contextTokensBefore: tokenCountSchema.optional(),
3376
- contextTokensAfter: tokenCountSchema.optional(),
3377
- droppedMessageCount: z16.number().int().min(0).optional(),
3378
- usage: canonicalUsageSchema.optional()
3379
- });
3380
- var errorRaisedEventSchema = event({
3381
- type: z16.literal("error.raised"),
3382
- errorCode: otelHookErrorCodeSchema,
3383
- severity: errorSeveritySchema,
3384
- phase: errorPhaseSchema,
3385
- retryable: z16.boolean(),
3386
- /** Error text is content: it is described, never embedded verbatim by default. */
3387
- message: contentFactSchema.optional(),
3388
- /** Non-sensitive, provider-agnostic short label. */
3389
- detail: nonEmptyStringSchema.optional()
3390
- });
3391
- var canonicalEventSchema = z16.discriminatedUnion("type", [
3392
- sessionStartEventSchema,
3393
- sessionEndEventSchema,
3394
- promptSubmittedEventSchema,
3395
- generationStartEventSchema,
3396
- generationEndEventSchema,
3397
- toolStartEventSchema,
3398
- toolEndEventSchema,
3399
- subagentStartEventSchema,
3400
- subagentEndEventSchema,
3401
- compactionPerformedEventSchema,
3402
- errorRaisedEventSchema
3403
- ]);
3404
- var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
3405
- var TARGETED = new Set(TARGETED_EVENT_TYPES);
3406
- var isTargetedEvent = (event3) => TARGETED.has(event3.type);
3355
+ }
3356
+ const sanitized = sanitizeStructured(entry).value;
3357
+ const candidate = attributeValueSchema.safeParse(sanitized);
3358
+ if (candidate.success) {
3359
+ extensions[key] = candidate.data;
3360
+ } else {
3361
+ droppedKeys.push(key);
3362
+ }
3363
+ }
3364
+ return { extensions, droppedKeys };
3365
+ };
3366
+ return {
3367
+ policy,
3368
+ policyNotes: notes,
3369
+ hash,
3370
+ deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
3371
+ describeContent: describeText,
3372
+ describeUnavailableContent: (input) => ({
3373
+ kind: input.kind,
3374
+ ...input.role === void 0 ? {} : { role: input.role },
3375
+ characterLength: 0,
3376
+ byteLength: 0,
3377
+ contentHash: hash(""),
3378
+ disclosure: "omitted",
3379
+ truncated: false,
3380
+ secretsRedacted: 0,
3381
+ ...input.label === void 0 ? {} : { label: input.label }
3382
+ }),
3383
+ describeStructured: (input) => {
3384
+ const serialized = stableStringify(input.value);
3385
+ const sanitized = sanitizeStructured(input.value);
3386
+ const base = describeText({
3387
+ kind: input.kind,
3388
+ text: serialized,
3389
+ ...input.role === void 0 ? {} : { role: input.role },
3390
+ ...input.label === void 0 ? {} : { label: input.label }
3391
+ });
3392
+ if (base.text === void 0) {
3393
+ return base;
3394
+ }
3395
+ const disclosed = disclose(stableStringify(sanitized.value));
3396
+ return {
3397
+ ...base,
3398
+ ...disclosed.text === void 0 ? {} : { text: disclosed.text },
3399
+ truncated: base.truncated || disclosed.truncated,
3400
+ secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
3401
+ };
3402
+ },
3403
+ isSecretKey,
3404
+ sanitizeStructured,
3405
+ flattenToAttributes,
3406
+ sanitizeAttributes,
3407
+ sanitizeExtensions,
3408
+ boundString
3409
+ };
3410
+ };
3411
+
3412
+ // src/privacy/workspace.ts
3413
+ var canonicalizeGitRemote = (remoteUrl) => {
3414
+ const trimmed = remoteUrl.trim();
3415
+ const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);
3416
+ const withoutScheme = scpLike ? `${scpLike[2] ?? ""}/${scpLike[3] ?? ""}` : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/^[^@/]+@/, "");
3417
+ return withoutScheme.replace(/:\d+\//, "/").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
3418
+ };
3419
+ var keySourceOf = (input) => {
3420
+ switch (input.kind) {
3421
+ case "git-remote":
3422
+ return "git-remote";
3423
+ case "git-root":
3424
+ return "git-root";
3425
+ case "working-directory":
3426
+ return "working-directory";
3427
+ case "explicit":
3428
+ return "explicit";
3429
+ case "unknown":
3430
+ return "unknown";
3431
+ }
3432
+ };
3433
+ var keyMaterialOf = (input) => {
3434
+ switch (input.kind) {
3435
+ case "git-remote":
3436
+ return canonicalizeGitRemote(input.remoteUrl);
3437
+ case "git-root":
3438
+ case "working-directory":
3439
+ return input.absolutePath.replace(/[/\\]+$/, "");
3440
+ case "explicit":
3441
+ return input.value;
3442
+ case "unknown":
3443
+ return void 0;
3444
+ }
3445
+ };
3446
+ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
3447
+ const keySource = keySourceOf(input);
3448
+ const material = keyMaterialOf(input);
3449
+ const workspaceId = material === void 0 || material === "" ? "unknown:0000000000000000" : privacy.deriveOpaqueId(`workspace/${keySource}`, material);
3450
+ return workspaceIdentitySchema.parse({
3451
+ workspaceId,
3452
+ keySource: material === void 0 || material === "" ? "unknown" : keySource,
3453
+ ...labels.repositoryName === void 0 ? {} : { repositoryName: labels.repositoryName.slice(0, 128) },
3454
+ ...labels.vcsBranchName === void 0 ? {} : { vcsBranchName: labels.vcsBranchName.slice(0, 128) },
3455
+ ...labels.vcsRevisionId === void 0 ? {} : { vcsRevisionId: privacy.deriveOpaqueId("workspace/revision", labels.vcsRevisionId) }
3456
+ });
3457
+ };
3407
3458
 
3408
3459
  // src/providers/adapter.ts
3460
+ import { z as z17 } from "zod";
3409
3461
  var providerDetectionSchema = z17.strictObject({
3410
3462
  providerId: resolvedProviderIdSchema,
3411
3463
  confidence: detectionConfidenceSchema,
@@ -4062,7 +4114,25 @@ var stopPayloadSchema2 = z19.object({
4062
4114
  * the former without suppressing the latter.
4063
4115
  */
4064
4116
  stop_hook_active: z19.boolean().optional(),
4065
- usage: claudeUsageSchema.optional()
4117
+ usage: claudeUsageSchema.optional(),
4118
+ /**
4119
+ * The model that answered this turn — harness-supplied, never upstream.
4120
+ *
4121
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
4122
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
4123
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
4124
+ * with `usage`, and it becomes the generation's response model. An unusable
4125
+ * value (empty, over 256 characters, not a string) is dropped rather than
4126
+ * failing the whole payload: the turn is still worth reporting without it.
4127
+ */
4128
+ model: z19.string().min(1).max(256).optional().catch(void 0),
4129
+ /**
4130
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
4131
+ * turn. `true` when it is the last model request alone (the tail fallback),
4132
+ * `false` when it sums every request since the previous stop. Exported as
4133
+ * `otelhook.usage.partial`; absent means the attacher did not say.
4134
+ */
4135
+ usage_partial: z19.boolean().optional().catch(void 0)
4066
4136
  });
4067
4137
  var stopFailurePayloadSchema = z19.object({
4068
4138
  ...commonFields2,
@@ -4074,7 +4144,11 @@ var stopFailurePayloadSchema = z19.object({
4074
4144
  */
4075
4145
  error_type: z19.string().min(1),
4076
4146
  error_message: z19.string().optional(),
4077
- usage: claudeUsageSchema.optional()
4147
+ usage: claudeUsageSchema.optional(),
4148
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
4149
+ model: z19.string().min(1).max(256).optional().catch(void 0),
4150
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4151
+ usage_partial: z19.boolean().optional().catch(void 0)
4078
4152
  });
4079
4153
  var claudeHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
4080
4154
  sessionStartPayloadSchema,
@@ -4606,6 +4680,13 @@ var inferToolKind = (toolName) => {
4606
4680
 
4607
4681
  // src/providers/claude/events.ts
4608
4682
  var UNKNOWN_MODEL = { modelId: "unknown" };
4683
+ var generationModels = (attached, sessionModel) => {
4684
+ const turnModel = attached === void 0 ? void 0 : { modelId: attached };
4685
+ return {
4686
+ request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
4687
+ response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
4688
+ };
4689
+ };
4609
4690
  var SESSION_END_REASON = Object.freeze({
4610
4691
  completed: "completed",
4611
4692
  aborted: "aborted",
@@ -4672,6 +4753,10 @@ var parseClaudeCode = (input, context) => {
4672
4753
  warnings.push(...normalized.warnings);
4673
4754
  return applyUsage(normalized);
4674
4755
  };
4756
+ const withPartialUsage = (usage, partial) => {
4757
+ const applied = withUsage(usage);
4758
+ return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
4759
+ };
4675
4760
  switch (payload.hook_event_name) {
4676
4761
  case "SessionStart":
4677
4762
  factory.build({
@@ -4784,11 +4869,12 @@ var parseClaudeCode = (input, context) => {
4784
4869
  payload.prompt_id ?? String(input.sequenceBase)
4785
4870
  ]);
4786
4871
  const assistantText = extractClaudeAssistantText(normalizedPayload);
4787
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
4872
+ const models = generationModels(payload.model, input.sessionModel);
4873
+ factory.build({ type: "generation.start", generationId, model: models.request });
4788
4874
  factory.build({
4789
4875
  type: "generation.end",
4790
4876
  generationId,
4791
- model: UNKNOWN_MODEL,
4877
+ model: models.response,
4792
4878
  outcome: "ok",
4793
4879
  // Always a response fact: a body when Claude sent text, otherwise a
4794
4880
  // zero-length omitted fact so the log mapping can emit metadata_only
@@ -4800,7 +4886,7 @@ var parseClaudeCode = (input, context) => {
4800
4886
  text: assistantText
4801
4887
  })
4802
4888
  ],
4803
- ...withUsage(extractedUsage ?? payload.usage)
4889
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
4804
4890
  });
4805
4891
  break;
4806
4892
  }
@@ -4811,11 +4897,12 @@ var parseClaudeCode = (input, context) => {
4811
4897
  payload.prompt_id ?? String(input.sequenceBase)
4812
4898
  ]);
4813
4899
  const assistantText = extractClaudeAssistantText(normalizedPayload);
4814
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
4900
+ const models = generationModels(payload.model, input.sessionModel);
4901
+ factory.build({ type: "generation.start", generationId, model: models.request });
4815
4902
  factory.build({
4816
4903
  type: "generation.end",
4817
4904
  generationId,
4818
- model: UNKNOWN_MODEL,
4905
+ model: models.response,
4819
4906
  outcome: mapStopFailureOutcome(payload.error_type),
4820
4907
  stopReason: payload.error_type,
4821
4908
  ...assistantText === void 0 ? {} : {
@@ -4827,7 +4914,7 @@ var parseClaudeCode = (input, context) => {
4827
4914
  })
4828
4915
  ]
4829
4916
  },
4830
- ...withUsage(extractedUsage ?? payload.usage)
4917
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
4831
4918
  });
4832
4919
  break;
4833
4920
  }
@@ -8383,7 +8470,7 @@ import {
8383
8470
  } from "@opentelemetry/semantic-conventions/incubating";
8384
8471
 
8385
8472
  // src/version.ts
8386
- var VERSION = "0.9.0";
8473
+ var VERSION = "0.10.0";
8387
8474
 
8388
8475
  // src/telemetry/semconv.ts
8389
8476
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8396,6 +8483,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
8396
8483
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
8397
8484
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
8398
8485
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
8486
+ var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
8399
8487
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
8400
8488
  var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
8401
8489
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
@@ -8668,7 +8756,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8668
8756
  // Codex turn): the key a consumer stores a usage observation under.
8669
8757
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
8670
8758
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
8671
- ...usageAttributes(end?.usage, false)
8759
+ ...usageAttributes(end?.usage, false),
8760
+ ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
8672
8761
  };
8673
8762
  status = outcomeStatus(end?.outcome);
8674
8763
  break;
@@ -9066,7 +9155,8 @@ var eventAttributes = (event3) => {
9066
9155
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
9067
9156
  [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
9068
9157
  ...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
9069
- ...usageAttributes2(event3.usage)
9158
+ ...usageAttributes2(event3.usage),
9159
+ ...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
9070
9160
  };
9071
9161
  case "tool.start":
9072
9162
  return {
@@ -11852,7 +11942,7 @@ var runRegistrationCommand = async (command, io) => {
11852
11942
  };
11853
11943
 
11854
11944
  // src/cli/run.ts
11855
- import * as path12 from "path";
11945
+ import * as path13 from "path";
11856
11946
 
11857
11947
  // src/lifecycle/dedup.ts
11858
11948
  import { randomBytes as randomBytes5 } from "crypto";
@@ -12588,6 +12678,301 @@ var createUsageAccumulator = (deps) => {
12588
12678
  return { accumulateDelta, recordReset, read, cleanup };
12589
12679
  };
12590
12680
 
12681
+ // src/providers/claude/transcript.ts
12682
+ import { createHash as createHash4 } from "crypto";
12683
+ import { open as open4, stat as stat4 } from "fs/promises";
12684
+ import path10 from "path";
12685
+ var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
12686
+ var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
12687
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
12688
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
12689
+ var MIN_TAIL_BYTES = 65536;
12690
+ var MAX_TAIL_BYTES = 16777216;
12691
+ var MAX_RANGE_BYTES = 67108864;
12692
+ var MIN_TIMEOUT_MILLIS = 10;
12693
+ var MAX_TIMEOUT_MILLIS = 5e3;
12694
+ var MAX_MODEL_ID_LENGTH = 256;
12695
+ var MAX_REQUESTS_PER_RANGE = 1e4;
12696
+ var SYNTHETIC_MODEL = "<synthetic>";
12697
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
12698
+ var clamp = (value, fallback, min, max) => {
12699
+ if (value === void 0 || !Number.isFinite(value)) {
12700
+ return fallback;
12701
+ }
12702
+ return Math.min(max, Math.max(min, Math.floor(value)));
12703
+ };
12704
+ var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
12705
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
12706
+ var assistantRecordOf = (line) => {
12707
+ if (!line.includes('"assistant"')) {
12708
+ return void 0;
12709
+ }
12710
+ let parsed;
12711
+ try {
12712
+ parsed = JSON.parse(line);
12713
+ } catch {
12714
+ return void 0;
12715
+ }
12716
+ const record = asRecord7(parsed);
12717
+ if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
12718
+ return void 0;
12719
+ }
12720
+ const message = asRecord7(record.message);
12721
+ if (message === void 0 || message.model === SYNTHETIC_MODEL) {
12722
+ return void 0;
12723
+ }
12724
+ const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
12725
+ const usage = coerceClaudeUsage(message.usage);
12726
+ if (model === void 0 && usage === void 0) {
12727
+ return void 0;
12728
+ }
12729
+ const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
12730
+ return {
12731
+ ...id === void 0 ? {} : { id },
12732
+ ...model === void 0 ? {} : { model },
12733
+ ...usage === void 0 ? {} : { usage }
12734
+ };
12735
+ };
12736
+ var cacheCreationOf = (usage) => usage.cache_creation_input_tokens ?? (usage.cache_creation === void 0 ? 0 : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));
12737
+ var sumUsage = (usages) => {
12738
+ let input = 0;
12739
+ let output = 0;
12740
+ let cacheRead = 0;
12741
+ let cacheCreation = 0;
12742
+ for (const usage of usages) {
12743
+ input += usage.input_tokens;
12744
+ output += usage.output_tokens;
12745
+ cacheRead += usage.cache_read_input_tokens ?? 0;
12746
+ cacheCreation += cacheCreationOf(usage);
12747
+ }
12748
+ return {
12749
+ input_tokens: input,
12750
+ output_tokens: output,
12751
+ cache_read_input_tokens: cacheRead,
12752
+ cache_creation_input_tokens: cacheCreation
12753
+ };
12754
+ };
12755
+ var withTimeout = async (work, timeoutMillis, onError) => {
12756
+ let timer;
12757
+ const timeout = new Promise((resolve8) => {
12758
+ timer = setTimeout(() => {
12759
+ resolve8(TIMED_OUT);
12760
+ }, timeoutMillis);
12761
+ timer.unref();
12762
+ });
12763
+ try {
12764
+ return await Promise.race([work.catch(() => onError), timeout]);
12765
+ } finally {
12766
+ clearTimeout(timer);
12767
+ }
12768
+ };
12769
+ var withRegularFile = async (transcriptPath, body) => {
12770
+ let info;
12771
+ try {
12772
+ info = await stat4(transcriptPath);
12773
+ } catch {
12774
+ return { status: "unavailable", reason: "unreadable" };
12775
+ }
12776
+ if (!info.isFile()) {
12777
+ return { status: "unavailable", reason: "not-a-file" };
12778
+ }
12779
+ let handle;
12780
+ try {
12781
+ handle = await open4(transcriptPath, "r");
12782
+ } catch {
12783
+ return { status: "unavailable", reason: "unreadable" };
12784
+ }
12785
+ try {
12786
+ const { size } = await handle.stat();
12787
+ return await body(handle, size);
12788
+ } catch {
12789
+ return { status: "unavailable", reason: "unreadable" };
12790
+ } finally {
12791
+ await handle.close().catch(() => void 0);
12792
+ }
12793
+ };
12794
+ var readBytes = async (handle, start, length) => {
12795
+ const buffer = Buffer.alloc(length);
12796
+ let filled = 0;
12797
+ while (filled < length) {
12798
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
12799
+ if (bytesRead === 0) {
12800
+ break;
12801
+ }
12802
+ filled += bytesRead;
12803
+ }
12804
+ return buffer.subarray(0, filled);
12805
+ };
12806
+ var completeLinesEnd = (bytes, start) => {
12807
+ const lastNewline = bytes.lastIndexOf(10);
12808
+ return lastNewline < 0 ? start : start + lastNewline + 1;
12809
+ };
12810
+ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
12811
+ const length = Math.min(size, maxTailBytes);
12812
+ const start = size - length;
12813
+ const bytes = await readBytes(handle, start, length);
12814
+ const endOffset = completeLinesEnd(bytes, start);
12815
+ const lines = bytes.toString("utf8").split("\n");
12816
+ if (start > 0) {
12817
+ lines.shift();
12818
+ }
12819
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
12820
+ const record = assistantRecordOf((lines[index] ?? "").trim());
12821
+ if (record !== void 0) {
12822
+ return {
12823
+ turn: {
12824
+ status: "found",
12825
+ ...record.model === void 0 ? {} : { model: record.model },
12826
+ ...record.usage === void 0 ? {} : { usage: record.usage }
12827
+ },
12828
+ endOffset
12829
+ };
12830
+ }
12831
+ }
12832
+ return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
12833
+ });
12834
+ var boundedTail = async (transcriptPath, options) => withTimeout(
12835
+ readTail(
12836
+ transcriptPath,
12837
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
12838
+ ),
12839
+ clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
12840
+ { status: "unavailable", reason: "unreadable" }
12841
+ );
12842
+ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
12843
+ if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
12844
+ return { status: "unavailable", reason: "invalid-path" };
12845
+ }
12846
+ const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
12847
+ const timeoutMillis = clamp(
12848
+ options.rangeTimeoutMillis,
12849
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
12850
+ MIN_TIMEOUT_MILLIS,
12851
+ MAX_TIMEOUT_MILLIS
12852
+ );
12853
+ const work = withRegularFile(transcriptPath, async (handle, size) => {
12854
+ if (size < fromOffset) {
12855
+ return { status: "unavailable", reason: "truncated" };
12856
+ }
12857
+ if (size - fromOffset > maxRangeBytes) {
12858
+ return { status: "unavailable", reason: "over-cap" };
12859
+ }
12860
+ const bytes = await readBytes(handle, fromOffset, size - fromOffset);
12861
+ const endOffset = completeLinesEnd(bytes, fromOffset);
12862
+ const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
12863
+ const requests = /* @__PURE__ */ new Map();
12864
+ let anonymous = 0;
12865
+ let model;
12866
+ for (const line of complete.split("\n")) {
12867
+ const record = assistantRecordOf(line.trim());
12868
+ if (record === void 0) {
12869
+ continue;
12870
+ }
12871
+ if (record.model !== void 0) {
12872
+ model = record.model;
12873
+ }
12874
+ anonymous += record.id === void 0 ? 1 : 0;
12875
+ requests.set(record.id ?? `#${String(anonymous)}`, record);
12876
+ if (requests.size > MAX_REQUESTS_PER_RANGE) {
12877
+ return { status: "unavailable", reason: "over-cap" };
12878
+ }
12879
+ }
12880
+ const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
12881
+ return {
12882
+ status: "found",
12883
+ ...model === void 0 ? {} : { model },
12884
+ ...usages.length === 0 ? {} : { usage: sumUsage(usages) },
12885
+ requestCount: requests.size,
12886
+ endOffset
12887
+ };
12888
+ });
12889
+ const result = await withTimeout(work, timeoutMillis, {
12890
+ status: "unavailable",
12891
+ reason: "unreadable"
12892
+ });
12893
+ return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
12894
+ };
12895
+ var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
12896
+ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
12897
+ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
12898
+ var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
12899
+ var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
12900
+ var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
12901
+ var createClaudeTranscriptUsageEnricher = (options = {}) => {
12902
+ const fileSize = async (transcriptPath) => {
12903
+ try {
12904
+ const info = await stat4(transcriptPath);
12905
+ return info.isFile() ? info.size : void 0;
12906
+ } catch (thrown) {
12907
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
12908
+ }
12909
+ };
12910
+ const enrich = async (input) => {
12911
+ const unchanged = { payload: input.payload };
12912
+ const record = asRecord7(input.payload);
12913
+ if (record === void 0) {
12914
+ return unchanged;
12915
+ }
12916
+ const eventName = eventNameOf(record);
12917
+ const transcriptPath = transcriptPathOf(record);
12918
+ if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
12919
+ return unchanged;
12920
+ }
12921
+ const source = sourceDigest(transcriptPath);
12922
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
12923
+ if (eventName === "SessionStart") {
12924
+ if (cursor !== void 0) {
12925
+ return unchanged;
12926
+ }
12927
+ const size = await fileSize(transcriptPath);
12928
+ if (size === void 0) {
12929
+ return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
12930
+ }
12931
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
12932
+ }
12933
+ if (!STOP_EVENTS.has(eventName)) {
12934
+ return unchanged;
12935
+ }
12936
+ if (hasUsage(record)) {
12937
+ const size = await fileSize(transcriptPath);
12938
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
12939
+ }
12940
+ const attach = (model, usage, partial) => ({
12941
+ ...record,
12942
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
12943
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
12944
+ });
12945
+ if (cursor !== void 0) {
12946
+ const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
12947
+ if (range.status === "found") {
12948
+ return {
12949
+ payload: attach(range.model, range.usage, false),
12950
+ cursor: { source, offset: range.endOffset },
12951
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
12952
+ };
12953
+ }
12954
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
12955
+ return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
12956
+ }
12957
+ }
12958
+ const tail = await boundedTail(transcriptPath, options);
12959
+ if (tail === TIMED_OUT || !("turn" in tail)) {
12960
+ return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
12961
+ }
12962
+ const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
12963
+ return {
12964
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
12965
+ cursor: { source, offset: tail.endOffset },
12966
+ notes: [`${why}; attached the last request only (usage_partial)`]
12967
+ };
12968
+ };
12969
+ return Object.freeze({
12970
+ id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
12971
+ providerId: CLAUDE_CODE_PROVIDER_ID,
12972
+ enrich
12973
+ });
12974
+ };
12975
+
12591
12976
  // src/runtime/hook.ts
12592
12977
  import { z as z23 } from "zod";
12593
12978
 
@@ -12621,9 +13006,9 @@ var resolveDeliveryIdentity = (input) => {
12621
13006
  };
12622
13007
 
12623
13008
  // src/runtime/ids.ts
12624
- import { createHash as createHash4, randomUUID } from "crypto";
13009
+ import { createHash as createHash5, randomUUID } from "crypto";
12625
13010
  var digest = (namespace, parts) => {
12626
- const hash = createHash4("sha256");
13011
+ const hash = createHash5("sha256");
12627
13012
  hash.update(namespace);
12628
13013
  for (const part of parts) {
12629
13014
  hash.update("\0");
@@ -12662,16 +13047,16 @@ var createDeterministicIdGenerator = (options = {}) => {
12662
13047
  };
12663
13048
 
12664
13049
  // src/runtime/target-resolution.ts
12665
- import * as path10 from "path";
13050
+ import * as path11 from "path";
12666
13051
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
12667
13052
  var absolutePathsOf = (hint) => {
12668
- const base = hint.baseDirectory !== void 0 && path10.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
13053
+ const base = hint.baseDirectory !== void 0 && path11.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
12669
13054
  const resolved = [];
12670
13055
  for (const candidate of hint.paths) {
12671
- if (path10.isAbsolute(candidate)) {
12672
- resolved.push(path10.resolve(candidate));
13056
+ if (path11.isAbsolute(candidate)) {
13057
+ resolved.push(path11.resolve(candidate));
12673
13058
  } else if (base !== void 0) {
12674
- resolved.push(path10.resolve(base, candidate));
13059
+ resolved.push(path11.resolve(base, candidate));
12675
13060
  } else {
12676
13061
  return void 0;
12677
13062
  }
@@ -12808,6 +13193,22 @@ var usageScopeOf = (event3) => {
12808
13193
  }
12809
13194
  };
12810
13195
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
13196
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
13197
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
13198
+ var UNKNOWN_MODEL_ID = "unknown";
13199
+ var latestSessionModel = (events) => {
13200
+ let latest;
13201
+ for (const event3 of events) {
13202
+ if (event3.subagentId !== void 0) {
13203
+ continue;
13204
+ }
13205
+ if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
13206
+ latest = event3.model;
13207
+ }
13208
+ }
13209
+ return latest;
13210
+ };
13211
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
12811
13212
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
12812
13213
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
12813
13214
  var createOtelHook = (deps) => {
@@ -12855,6 +13256,66 @@ var createOtelHook = (deps) => {
12855
13256
  return 0;
12856
13257
  }
12857
13258
  };
13259
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
13260
+ let current = payload;
13261
+ for (const enricher of deps.payloadEnrichers ?? []) {
13262
+ if (enricher.providerId !== providerId) {
13263
+ continue;
13264
+ }
13265
+ const key = readCursorKey(enricher.id, sessionId);
13266
+ let cursor;
13267
+ try {
13268
+ const record = await deps.stateStore.read(key);
13269
+ if (record?.value.kind === "read-cursor") {
13270
+ cursor = { source: record.value.source, offset: record.value.offset };
13271
+ }
13272
+ } catch (thrown) {
13273
+ diagnostics.push(
13274
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
13275
+ );
13276
+ continue;
13277
+ }
13278
+ let result;
13279
+ try {
13280
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
13281
+ } catch (thrown) {
13282
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
13283
+ "enricher.id": enricher.id,
13284
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
13285
+ });
13286
+ continue;
13287
+ }
13288
+ current = result.payload;
13289
+ if (result.notes !== void 0 && result.notes.length > 0) {
13290
+ logger.debug("payload enricher notes", {
13291
+ "enricher.id": enricher.id,
13292
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
13293
+ });
13294
+ }
13295
+ const next = result.cursor;
13296
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
13297
+ try {
13298
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
13299
+ } catch (thrown) {
13300
+ diagnostics.push(
13301
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
13302
+ );
13303
+ }
13304
+ }
13305
+ }
13306
+ return current;
13307
+ };
13308
+ const readSessionModel = async (sessionId, diagnostics) => {
13309
+ try {
13310
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
13311
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
13312
+ } catch (thrown) {
13313
+ diagnostics.push(
13314
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
13315
+ );
13316
+ return void 0;
13317
+ }
13318
+ };
12858
13319
  const deriveUsage = async (events, diagnostics, suppress, series) => {
12859
13320
  const observations = [];
12860
13321
  for (const event3 of events) {
@@ -13175,10 +13636,19 @@ var createOtelHook = (deps) => {
13175
13636
  const identity = resolution.identity;
13176
13637
  const prepare = async () => {
13177
13638
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
13639
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
13640
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
13178
13641
  let parsed;
13179
13642
  try {
13180
13643
  parsed = adapter.parse(
13181
- { ...detectionInput, detection, identity, sequenceBase },
13644
+ {
13645
+ ...detectionInput,
13646
+ payload,
13647
+ detection,
13648
+ identity,
13649
+ sequenceBase,
13650
+ ...sessionModel === void 0 ? {} : { sessionModel }
13651
+ },
13182
13652
  providerContext
13183
13653
  );
13184
13654
  } catch (thrown) {
@@ -13288,6 +13758,23 @@ var createOtelHook = (deps) => {
13288
13758
  })
13289
13759
  );
13290
13760
  }
13761
+ const reportedModel = latestSessionModel(screened.kept);
13762
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
13763
+ try {
13764
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
13765
+ kind: "session-model",
13766
+ model: reportedModel
13767
+ });
13768
+ } catch (thrown) {
13769
+ diagnostics.push(
13770
+ errorInfoFromThrown(thrown, {
13771
+ code: "state-store-failure",
13772
+ phase: "state",
13773
+ occurredAt: clock.now()
13774
+ })
13775
+ );
13776
+ }
13777
+ }
13291
13778
  }
13292
13779
  return {
13293
13780
  kind: "ready",
@@ -13506,8 +13993,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
13506
13993
  };
13507
13994
 
13508
13995
  // src/runtime/git-worktree.ts
13509
- import { lstat, open as open4, stat as stat4 } from "fs/promises";
13510
- import * as path11 from "path";
13996
+ import { lstat, open as open5, stat as stat5 } from "fs/promises";
13997
+ import * as path12 from "path";
13511
13998
  var MAX_WORKTREE_WALK_DEPTH = 128;
13512
13999
  var MAX_GIT_FILE_BYTES = 4096;
13513
14000
  var MAX_CACHE_ENTRIES = 1024;
@@ -13518,7 +14005,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
13518
14005
  var readBounded = async (filePath) => {
13519
14006
  let handle;
13520
14007
  try {
13521
- handle = await open4(filePath, "r");
14008
+ handle = await open5(filePath, "r");
13522
14009
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
13523
14010
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
13524
14011
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -13539,7 +14026,7 @@ var parseHeadBranch = (head) => {
13539
14026
  return branch;
13540
14027
  };
13541
14028
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
13542
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path11.resolve(base, target);
14029
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path12.resolve(base, target);
13543
14030
  var parseGitDirFile = (content, worktreeRoot) => {
13544
14031
  const line = firstLine(content);
13545
14032
  return resolveGitPath(
@@ -13559,26 +14046,26 @@ var isMissing = async (filePath) => {
13559
14046
  };
13560
14047
  var isDirectory = async (directory) => {
13561
14048
  try {
13562
- return (await stat4(directory)).isDirectory();
14049
+ return (await stat5(directory)).isDirectory();
13563
14050
  } catch {
13564
14051
  return false;
13565
14052
  }
13566
14053
  };
13567
14054
  var repositoryOf = async (worktreeRoot, gitDir) => {
13568
- const commonDirFile = path11.join(gitDir, "commondir");
14055
+ const commonDirFile = path12.join(gitDir, "commondir");
13569
14056
  const content = await readBounded(commonDirFile);
13570
14057
  if (content === void 0) {
13571
14058
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
13572
14059
  }
13573
14060
  const commonDir = parseCommonDirFile(content, gitDir);
13574
- const mainRoot = commonDir !== void 0 && path11.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path11.dirname(commonDir) : void 0;
14061
+ const mainRoot = commonDir !== void 0 && path12.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path12.dirname(commonDir) : void 0;
13575
14062
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
13576
14063
  };
13577
14064
  var probeDirectory = async (directory) => {
13578
- const dotGit = path11.join(directory, ".git");
14065
+ const dotGit = path12.join(directory, ".git");
13579
14066
  let info;
13580
14067
  try {
13581
- info = await stat4(dotGit);
14068
+ info = await stat5(dotGit);
13582
14069
  } catch {
13583
14070
  return ABSENT;
13584
14071
  }
@@ -13592,7 +14079,7 @@ var probeDirectory = async (directory) => {
13592
14079
  if (gitDir === void 0) {
13593
14080
  return INVALID;
13594
14081
  }
13595
- const head = await readBounded(path11.join(gitDir, "HEAD"));
14082
+ const head = await readBounded(path12.join(gitDir, "HEAD"));
13596
14083
  if (head === void 0) {
13597
14084
  return INVALID;
13598
14085
  }
@@ -13622,10 +14109,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
13622
14109
  };
13623
14110
  const locate = async (absolutePath) => {
13624
14111
  try {
13625
- if (!path11.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
14112
+ if (!path12.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
13626
14113
  return void 0;
13627
14114
  }
13628
- let directory = path11.resolve(absolutePath);
14115
+ let directory = path12.resolve(absolutePath);
13629
14116
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
13630
14117
  const probe = await cachedProbe(directory);
13631
14118
  if (probe.kind === "worktree") {
@@ -13634,7 +14121,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
13634
14121
  if (probe.kind === "invalid") {
13635
14122
  return void 0;
13636
14123
  }
13637
- const parent = path11.dirname(directory);
14124
+ const parent = path12.dirname(directory);
13638
14125
  if (parent === directory) {
13639
14126
  return void 0;
13640
14127
  }
@@ -13760,6 +14247,7 @@ var createHookRuntime = (options) => {
13760
14247
  privacy,
13761
14248
  logger,
13762
14249
  installationId: options.installationId,
14250
+ payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
13763
14251
  ...options.worktreeLocator === null ? {} : {
13764
14252
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
13765
14253
  }
@@ -14322,13 +14810,13 @@ var runHookCommand = async (command, io) => {
14322
14810
  }
14323
14811
  const identityClaims = [];
14324
14812
  if (command.identity.identityFile !== void 0) {
14325
- const read = await readIdentityFile(path12.resolve(command.identity.identityFile));
14813
+ const read = await readIdentityFile(path13.resolve(command.identity.identityFile));
14326
14814
  if ("error" in read) {
14327
14815
  logDiagnostics(logger, [read.error]);
14328
14816
  } else {
14329
14817
  const fromFile = claimFromIdentityFile(
14330
14818
  read.value,
14331
- path12.basename(command.identity.identityFile)
14819
+ path13.basename(command.identity.identityFile)
14332
14820
  );
14333
14821
  logDiagnostics(logger, fromFile.errors);
14334
14822
  identityClaims.push(...fromFile.claims);