@osfactory/otel-hook 0.2.0 → 0.3.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 (45) hide show
  1. package/dist/{adapter-DIgRACtL.d.ts → adapter-DXpNtnaf.d.ts} +2 -2
  2. package/dist/cli.js +442 -143
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config.d.ts +2 -2
  5. package/dist/config.js +5 -1
  6. package/dist/config.js.map +1 -1
  7. package/dist/{content-CoB7aNP1.d.ts → content-M9xIKG7h.d.ts} +8 -1
  8. package/dist/{hook-CGpo-vks.d.ts → hook-_mlO3akA.d.ts} +3 -3
  9. package/dist/index.d.ts +10 -10
  10. package/dist/index.js +443 -143
  11. package/dist/index.js.map +1 -1
  12. package/dist/install.d.ts +5 -5
  13. package/dist/install.js +33 -0
  14. package/dist/install.js.map +1 -1
  15. package/dist/integration.d.ts +8 -8
  16. package/dist/integration.js +115 -39
  17. package/dist/integration.js.map +1 -1
  18. package/dist/lifecycle.d.ts +1 -1
  19. package/dist/lifecycle.js +5 -3
  20. package/dist/lifecycle.js.map +1 -1
  21. package/dist/model.d.ts +1 -1
  22. package/dist/model.js +2 -0
  23. package/dist/model.js.map +1 -1
  24. package/dist/{otlp-log-sink-CeIFDDpn.d.ts → otlp-log-sink-DTSa0KRF.d.ts} +2 -2
  25. package/dist/{payload-CHr53E_v.d.ts → payload-BWV5-4n3.d.ts} +1 -1
  26. package/dist/{policy-D1CrlYn3.d.ts → policy-CimmCfRp.d.ts} +1 -1
  27. package/dist/privacy.d.ts +4 -4
  28. package/dist/privacy.js +11 -0
  29. package/dist/privacy.js.map +1 -1
  30. package/dist/providers.d.ts +8 -8
  31. package/dist/providers.js +322 -103
  32. package/dist/providers.js.map +1 -1
  33. package/dist/{registry-BzYmC9OC.d.ts → registry-Dqr3VNmT.d.ts} +1 -1
  34. package/dist/runtime.d.ts +6 -6
  35. package/dist/runtime.js +13 -1
  36. package/dist/runtime.js.map +1 -1
  37. package/dist/{semconv-Baoz-0OI.d.ts → semconv-CIU-2kGO.d.ts} +1 -0
  38. package/dist/{service-j4jEO6cZ.d.ts → service-CbI9CObT.d.ts} +8 -2
  39. package/dist/telemetry.d.ts +5 -5
  40. package/dist/telemetry.js +102 -38
  41. package/dist/telemetry.js.map +1 -1
  42. package/dist/testing.d.ts +6 -6
  43. package/dist/testing.js +338 -104
  44. package/dist/testing.js.map +1 -1
  45. package/package.json +1 -1
package/dist/testing.d.ts CHANGED
@@ -1,17 +1,17 @@
1
1
  import { O as OtelHookConfig, g as OtelHookConfigPatch } from './schema-Cn0-xz8L.js';
2
2
  import { b as CanonicalEvent } from './events-VxBnDFaO.js';
3
3
  import { I as IdentityClaim, d as InvocationIdentity, S as SourceProvenance } from './identity-BrVBs901.js';
4
- import { P as PrivacyService } from './service-j4jEO6cZ.js';
5
- import { d as ProviderCapabilities, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext, l as ProviderIdentityInput, f as ProviderDeliveryClaim, k as ProviderHookResponseInput, j as ProviderHookResponse, P as ProviderAdapter } from './adapter-DIgRACtL.js';
6
- import { P as ProviderRegistry } from './registry-BzYmC9OC.js';
4
+ import { P as PrivacyService } from './service-CbI9CObT.js';
5
+ import { d as ProviderCapabilities, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext, l as ProviderIdentityInput, f as ProviderDeliveryClaim, k as ProviderHookResponseInput, j as ProviderHookResponse, P as ProviderAdapter } from './adapter-DXpNtnaf.js';
6
+ import { P as ProviderRegistry } from './registry-Dqr3VNmT.js';
7
7
  import { c as RecordingTelemetrySink, I as InMemoryStateStore, F as FixedClock, R as RecordingLogger } from './memory-DXVBc8V9.js';
8
8
  export { e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, j as createRecordingLogger, k as createRecordingTelemetrySink } from './memory-DXVBc8V9.js';
9
- import { O as OtelHook } from './hook-CGpo-vks.js';
9
+ import { O as OtelHook } from './hook-_mlO3akA.js';
10
10
  import { I as IdGenerator } from './ports-Q8x0ODhs.js';
11
11
  import { z } from 'zod';
12
- import { a as ContentDisclosure, b as ContentFact } from './content-CoB7aNP1.js';
12
+ import { a as ContentDisclosure, b as ContentFact } from './content-M9xIKG7h.js';
13
13
  import './primitives-CJ8-rn-f.js';
14
- import './policy-D1CrlYn3.js';
14
+ import './policy-CimmCfRp.js';
15
15
  import './errors.js';
16
16
  import './taxonomy-DwhTtuWd.js';
17
17
 
package/dist/testing.js CHANGED
@@ -838,6 +838,17 @@ var createPrivacyService = (policyInput) => {
838
838
  hash,
839
839
  deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
840
840
  describeContent: describeText,
841
+ describeUnavailableContent: (input) => ({
842
+ kind: input.kind,
843
+ ...input.role === void 0 ? {} : { role: input.role },
844
+ characterLength: 0,
845
+ byteLength: 0,
846
+ contentHash: hash(""),
847
+ disclosure: "omitted",
848
+ truncated: false,
849
+ secretsRedacted: 0,
850
+ ...input.label === void 0 ? {} : { label: input.label }
851
+ }),
841
852
  describeStructured: (input) => {
842
853
  const serialized = stableStringify(input.value);
843
854
  const sanitized = sanitizeStructured(input.value);
@@ -1105,6 +1116,7 @@ var contentFactSchema = z8.strictObject({
1105
1116
  });
1106
1117
  var contentFactsSchema = z8.array(contentFactSchema).max(64);
1107
1118
  var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
1119
+ var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
1108
1120
 
1109
1121
  // src/model/usage.ts
1110
1122
  import { z as z9 } from "zod";
@@ -2033,7 +2045,14 @@ var postCompactPayloadSchema = z14.object({
2033
2045
  var stopPayloadSchema = z14.object({
2034
2046
  ...commonFields,
2035
2047
  hook_event_name: z14.literal("Stop"),
2048
+ /**
2049
+ * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
2050
+ * result messages use `result` instead; `events.ts` reads both (and camelCase
2051
+ * `lastAssistantMessage`) through `extractClaudeAssistantText`.
2052
+ */
2036
2053
  last_assistant_message: z14.string().optional(),
2054
+ /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
2055
+ result: z14.string().optional(),
2037
2056
  /**
2038
2057
  * True when this stop fired because a hook continued the turn.
2039
2058
  *
@@ -2097,6 +2116,229 @@ var claudeIdentityFieldsSchema = z14.object({
2097
2116
  stop_hook_active: z14.boolean().optional()
2098
2117
  });
2099
2118
 
2119
+ // src/providers/claude/usage.ts
2120
+ var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
2121
+ total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
2122
+ reasoning_output_tokens: "usage.reasoning_output_tokens is outside Claude Code's usage contract (capability reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate counter, so it is not read and reasoningOutputTokens stays 0"
2123
+ });
2124
+ var ITERATION_COUNTERS = [
2125
+ "input_tokens",
2126
+ "output_tokens",
2127
+ "cache_read_input_tokens",
2128
+ "cache_creation_input_tokens"
2129
+ ];
2130
+ var ttlSplitTotal = (raw) => {
2131
+ const split = raw.cache_creation;
2132
+ if (split === void 0) {
2133
+ return void 0;
2134
+ }
2135
+ return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
2136
+ };
2137
+ var resolveCacheCreationTokens = (raw, warnings) => {
2138
+ const declared = raw.cache_creation_input_tokens;
2139
+ const split = ttlSplitTotal(raw);
2140
+ if (declared === void 0) {
2141
+ return split ?? 0;
2142
+ }
2143
+ if (split !== void 0 && split !== declared) {
2144
+ warnings.push(
2145
+ `usage.cache_creation TTL buckets sum to ${String(split)} but usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the buckets are never added to it`
2146
+ );
2147
+ }
2148
+ return declared;
2149
+ };
2150
+ var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
2151
+ const iterations = raw.iterations;
2152
+ if (iterations === void 0 || iterations.length === 0) {
2153
+ return;
2154
+ }
2155
+ const outer = {
2156
+ input_tokens: raw.input_tokens,
2157
+ output_tokens: raw.output_tokens,
2158
+ cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
2159
+ cache_creation_input_tokens: cacheCreationInputTokens
2160
+ };
2161
+ for (const counter of ITERATION_COUNTERS) {
2162
+ const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
2163
+ if (summed !== outer[counter]) {
2164
+ warnings.push(
2165
+ `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`
2166
+ );
2167
+ }
2168
+ }
2169
+ };
2170
+ var auditExcludedCounters = (raw, warnings) => {
2171
+ if (raw.total_tokens !== void 0) {
2172
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
2173
+ }
2174
+ if (raw.reasoning_output_tokens !== void 0) {
2175
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
2176
+ }
2177
+ };
2178
+ var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
2179
+ var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
2180
+ var asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2181
+ var asNonNegativeInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2182
+ var coerceClaudeUsage = (value) => {
2183
+ const record = asRecord(value);
2184
+ if (record === void 0) {
2185
+ return void 0;
2186
+ }
2187
+ const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);
2188
+ const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);
2189
+ if (inputTokens === void 0 || outputTokens === void 0) {
2190
+ return void 0;
2191
+ }
2192
+ const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);
2193
+ const parsed = claudeUsageSchema.safeParse({
2194
+ input_tokens: inputTokens,
2195
+ output_tokens: outputTokens,
2196
+ ...asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) === void 0 ? {} : {
2197
+ cache_creation_input_tokens: asNonNegativeInt(
2198
+ record.cache_creation_input_tokens ?? record.cacheCreationInputTokens
2199
+ )
2200
+ },
2201
+ ...asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === void 0 ? {} : {
2202
+ cache_read_input_tokens: asNonNegativeInt(
2203
+ record.cache_read_input_tokens ?? record.cacheReadInputTokens
2204
+ )
2205
+ },
2206
+ ...cacheCreation === void 0 ? {} : {
2207
+ cache_creation: {
2208
+ ...asNonNegativeInt(
2209
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
2210
+ ) === void 0 ? {} : {
2211
+ ephemeral_5m_input_tokens: asNonNegativeInt(
2212
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
2213
+ )
2214
+ },
2215
+ ...asNonNegativeInt(
2216
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
2217
+ ) === void 0 ? {} : {
2218
+ ephemeral_1h_input_tokens: asNonNegativeInt(
2219
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
2220
+ )
2221
+ }
2222
+ }
2223
+ },
2224
+ ...Array.isArray(record.iterations) ? { iterations: record.iterations } : {},
2225
+ ...asNonNegativeInt(record.total_tokens ?? record.totalTokens) === void 0 ? {} : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) },
2226
+ ...asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) === void 0 ? {} : {
2227
+ reasoning_output_tokens: asNonNegativeInt(
2228
+ record.reasoning_output_tokens ?? record.reasoningOutputTokens
2229
+ )
2230
+ }
2231
+ });
2232
+ return parsed.success ? parsed.data : void 0;
2233
+ };
2234
+ var extractClaudeUsage = (payload) => {
2235
+ const record = asRecord(payload);
2236
+ if (record === void 0) {
2237
+ return void 0;
2238
+ }
2239
+ const message = asRecord(record.message);
2240
+ const candidates = [
2241
+ record.usage,
2242
+ record.token_usage,
2243
+ record.tokenUsage,
2244
+ message?.usage,
2245
+ record
2246
+ ];
2247
+ for (const candidate of candidates) {
2248
+ const usage = coerceClaudeUsage(candidate);
2249
+ if (usage !== void 0) {
2250
+ return usage;
2251
+ }
2252
+ }
2253
+ return void 0;
2254
+ };
2255
+ var normalizeClaudeUsage = (raw) => {
2256
+ if (raw === void 0) {
2257
+ return { warnings: [] };
2258
+ }
2259
+ const warnings = [];
2260
+ const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
2261
+ const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
2262
+ auditIterations(raw, cacheCreationInputTokens, warnings);
2263
+ auditExcludedCounters(raw, warnings);
2264
+ const result = normalizeUsage({
2265
+ temporality: "delta",
2266
+ inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
2267
+ cachedInputTokens,
2268
+ cacheCreationInputTokens,
2269
+ cacheCreationAccounting: "included-in-input",
2270
+ outputTokens: raw.output_tokens
2271
+ });
2272
+ if (result.status === "invalid") {
2273
+ return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
2274
+ }
2275
+ return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
2276
+ };
2277
+
2278
+ // src/providers/claude/payload-normalize.ts
2279
+ var FIELD_ALIASES = Object.freeze({
2280
+ hookEventName: "hook_event_name",
2281
+ sessionId: "session_id",
2282
+ lastAssistantMessage: "last_assistant_message",
2283
+ transcriptPath: "transcript_path",
2284
+ promptId: "prompt_id",
2285
+ toolUseId: "tool_use_id",
2286
+ toolName: "tool_name",
2287
+ toolInput: "tool_input",
2288
+ toolResponse: "tool_response",
2289
+ toolError: "tool_error",
2290
+ stopHookActive: "stop_hook_active",
2291
+ agentId: "agent_id",
2292
+ agentType: "agent_type",
2293
+ errorType: "error_type",
2294
+ errorMessage: "error_message",
2295
+ tokenUsage: "token_usage"
2296
+ });
2297
+ var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2298
+ var applyFieldAliases = (record) => {
2299
+ const normalized = { ...record };
2300
+ for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {
2301
+ if (normalized[canonical] === void 0 && normalized[alias] !== void 0) {
2302
+ normalized[canonical] = normalized[alias];
2303
+ }
2304
+ }
2305
+ return normalized;
2306
+ };
2307
+ var applyPrintResultShape = (record) => {
2308
+ if (record.hook_event_name !== void 0 || record.type !== "result") {
2309
+ return record;
2310
+ }
2311
+ if (typeof record.session_id !== "string" || record.session_id.length === 0) {
2312
+ return record;
2313
+ }
2314
+ const isError = record.subtype === "error" || record.is_error === true;
2315
+ const normalized = {
2316
+ ...record,
2317
+ hook_event_name: isError ? "StopFailure" : "Stop"
2318
+ };
2319
+ if (normalized.last_assistant_message === void 0 && typeof record.result === "string" && record.result.length > 0) {
2320
+ normalized.last_assistant_message = record.result;
2321
+ }
2322
+ if (isError && (typeof normalized.error_type !== "string" || normalized.error_type.length === 0)) {
2323
+ normalized.error_type = "unknown";
2324
+ }
2325
+ return normalized;
2326
+ };
2327
+ var normalizeClaudeHookPayload = (payload) => {
2328
+ const record = asRecord2(payload);
2329
+ if (record === void 0) {
2330
+ return payload;
2331
+ }
2332
+ return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
2333
+ };
2334
+ var applyUsageShape = (record) => {
2335
+ const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
2336
+ if (usage === void 0) {
2337
+ return record;
2338
+ }
2339
+ return { ...record, usage };
2340
+ };
2341
+
2100
2342
  // src/providers/claude/delivery.ts
2101
2343
  var TOOL_SCOPED_EVENTS = [
2102
2344
  "PreToolUse",
@@ -2105,7 +2347,7 @@ var TOOL_SCOPED_EVENTS = [
2105
2347
  "PermissionRequest"
2106
2348
  ];
2107
2349
  var claudeDeliveryIdentity = (input) => {
2108
- const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
2350
+ const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));
2109
2351
  if (!parsed.success) {
2110
2352
  return void 0;
2111
2353
  }
@@ -2181,7 +2423,7 @@ var none = (reason) => providerDetectionSchema.parse({
2181
2423
  reasons: [reason]
2182
2424
  });
2183
2425
  var detectClaudeCode = (input) => {
2184
- const { payload } = input;
2426
+ const payload = normalizeClaudeHookPayload(input.payload);
2185
2427
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
2186
2428
  return none("payload is not a JSON object");
2187
2429
  }
@@ -2195,14 +2437,16 @@ var detectClaudeCode = (input) => {
2195
2437
  return none("session_id is missing");
2196
2438
  }
2197
2439
  const hasTranscriptPath = typeof record.transcript_path === "string" && record.transcript_path.length > 0;
2440
+ const isPrintResult = record.type === "result";
2198
2441
  const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;
2199
2442
  return providerDetectionSchema.parse({
2200
2443
  providerId: CLAUDE_CODE_PROVIDER_ID,
2201
- confidence: hinted ? "exact" : hasTranscriptPath ? "strong" : "weak",
2444
+ confidence: hinted ? "exact" : hasTranscriptPath || isPrintResult ? "strong" : "weak",
2202
2445
  reasons: [
2203
2446
  `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,
2204
2447
  "session_id present",
2205
2448
  ...hasTranscriptPath ? ["transcript_path present"] : [],
2449
+ ...isPrintResult ? ["type=result print/SDK result message"] : [],
2206
2450
  ...hinted ? ["caller asserted providerHint=claude-code"] : []
2207
2451
  ],
2208
2452
  sourceEventName: hookEventName
@@ -2259,7 +2503,7 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
2259
2503
  // src/providers/claude/identity.ts
2260
2504
  var subagentInvocationIdFor = (context, sessionId, agentId) => invocationIdSchema.parse(`subagent_${context.ids.newOpaqueId(["claude-subagent", sessionId, agentId])}`);
2261
2505
  var identifyClaudeCode = (input, context) => {
2262
- const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
2506
+ const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));
2263
2507
  if (!parsed.success) {
2264
2508
  return [];
2265
2509
  }
@@ -2291,6 +2535,62 @@ var identifyClaudeCode = (input, context) => {
2291
2535
  return [claim];
2292
2536
  };
2293
2537
 
2538
+ // src/providers/claude/stop-content.ts
2539
+ var TOP_LEVEL_TEXT_FIELDS = [
2540
+ "last_assistant_message",
2541
+ "lastAssistantMessage",
2542
+ "result",
2543
+ "assistant_message",
2544
+ "final_message"
2545
+ ];
2546
+ var MESSAGE_TEXT_FIELDS = ["content", "text", "result"];
2547
+ var asRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2548
+ var nonEmptyString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
2549
+ var textFromContentBlocks = (value) => {
2550
+ if (!Array.isArray(value)) {
2551
+ return void 0;
2552
+ }
2553
+ const parts = [];
2554
+ for (const block of value) {
2555
+ const record = asRecord3(block);
2556
+ if (record === void 0) {
2557
+ continue;
2558
+ }
2559
+ const text = nonEmptyString(record.text);
2560
+ if (text !== void 0 && (record.type === void 0 || record.type === "text")) {
2561
+ parts.push(text);
2562
+ }
2563
+ }
2564
+ return parts.length === 0 ? void 0 : parts.join("");
2565
+ };
2566
+ var extractClaudeAssistantText = (payload) => {
2567
+ const record = asRecord3(payload);
2568
+ if (record === void 0) {
2569
+ return void 0;
2570
+ }
2571
+ for (const field of TOP_LEVEL_TEXT_FIELDS) {
2572
+ const text = nonEmptyString(record[field]);
2573
+ if (text !== void 0) {
2574
+ return text;
2575
+ }
2576
+ }
2577
+ const messageText2 = nonEmptyString(record.message);
2578
+ if (messageText2 !== void 0) {
2579
+ return messageText2;
2580
+ }
2581
+ const message = asRecord3(record.message);
2582
+ if (message === void 0) {
2583
+ return void 0;
2584
+ }
2585
+ for (const field of MESSAGE_TEXT_FIELDS) {
2586
+ const text = nonEmptyString(message[field]) ?? textFromContentBlocks(message[field]);
2587
+ if (text !== void 0) {
2588
+ return text;
2589
+ }
2590
+ }
2591
+ return void 0;
2592
+ };
2593
+
2294
2594
  // src/providers/claude/tool-kind.ts
2295
2595
  var BUILT_IN_TOOL_KIND = Object.freeze({
2296
2596
  Bash: "execute",
@@ -2319,90 +2619,6 @@ var inferToolKind = (toolName) => {
2319
2619
  return BUILT_IN_TOOL_KIND[toolName] ?? "unknown";
2320
2620
  };
2321
2621
 
2322
- // src/providers/claude/usage.ts
2323
- var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
2324
- total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
2325
- reasoning_output_tokens: "usage.reasoning_output_tokens is outside Claude Code's usage contract (capability reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate counter, so it is not read and reasoningOutputTokens stays 0"
2326
- });
2327
- var ITERATION_COUNTERS = [
2328
- "input_tokens",
2329
- "output_tokens",
2330
- "cache_read_input_tokens",
2331
- "cache_creation_input_tokens"
2332
- ];
2333
- var ttlSplitTotal = (raw) => {
2334
- const split = raw.cache_creation;
2335
- if (split === void 0) {
2336
- return void 0;
2337
- }
2338
- return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
2339
- };
2340
- var resolveCacheCreationTokens = (raw, warnings) => {
2341
- const declared = raw.cache_creation_input_tokens;
2342
- const split = ttlSplitTotal(raw);
2343
- if (declared === void 0) {
2344
- return split ?? 0;
2345
- }
2346
- if (split !== void 0 && split !== declared) {
2347
- warnings.push(
2348
- `usage.cache_creation TTL buckets sum to ${String(split)} but usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the buckets are never added to it`
2349
- );
2350
- }
2351
- return declared;
2352
- };
2353
- var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
2354
- const iterations = raw.iterations;
2355
- if (iterations === void 0 || iterations.length === 0) {
2356
- return;
2357
- }
2358
- const outer = {
2359
- input_tokens: raw.input_tokens,
2360
- output_tokens: raw.output_tokens,
2361
- cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
2362
- cache_creation_input_tokens: cacheCreationInputTokens
2363
- };
2364
- for (const counter of ITERATION_COUNTERS) {
2365
- const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
2366
- if (summed !== outer[counter]) {
2367
- warnings.push(
2368
- `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`
2369
- );
2370
- }
2371
- }
2372
- };
2373
- var auditExcludedCounters = (raw, warnings) => {
2374
- if (raw.total_tokens !== void 0) {
2375
- warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
2376
- }
2377
- if (raw.reasoning_output_tokens !== void 0) {
2378
- warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
2379
- }
2380
- };
2381
- var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
2382
- var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
2383
- var normalizeClaudeUsage = (raw) => {
2384
- if (raw === void 0) {
2385
- return { warnings: [] };
2386
- }
2387
- const warnings = [];
2388
- const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
2389
- const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
2390
- auditIterations(raw, cacheCreationInputTokens, warnings);
2391
- auditExcludedCounters(raw, warnings);
2392
- const result = normalizeUsage({
2393
- temporality: "delta",
2394
- inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
2395
- cachedInputTokens,
2396
- cacheCreationInputTokens,
2397
- cacheCreationAccounting: "included-in-input",
2398
- outputTokens: raw.output_tokens
2399
- });
2400
- if (result.status === "invalid") {
2401
- return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
2402
- }
2403
- return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
2404
- };
2405
-
2406
2622
  // src/providers/claude/events.ts
2407
2623
  var UNKNOWN_MODEL = { modelId: "unknown" };
2408
2624
  var SESSION_END_REASON = Object.freeze({
@@ -2435,7 +2651,8 @@ var DENIED_STOP_FAILURE_TYPES = /* @__PURE__ */ new Set([
2435
2651
  var mapStopFailureOutcome = (errorType) => DENIED_STOP_FAILURE_TYPES.has(errorType) ? "denied" : "error";
2436
2652
  var applyUsage = (normalized) => normalized.usage === void 0 ? {} : { usage: normalized.usage };
2437
2653
  var parseClaudeCode = (input, context) => {
2438
- const parsed = claudeHookPayloadSchema.safeParse(input.payload);
2654
+ const normalizedPayload = normalizeClaudeHookPayload(input.payload);
2655
+ const parsed = claudeHookPayloadSchema.safeParse(normalizedPayload);
2439
2656
  if (!parsed.success) {
2440
2657
  const rawEventName = typeof input.payload === "object" && input.payload !== null ? input.payload.hook_event_name : void 0;
2441
2658
  return {
@@ -2449,6 +2666,7 @@ var parseClaudeCode = (input, context) => {
2449
2666
  };
2450
2667
  }
2451
2668
  const payload = parsed.data;
2669
+ const extractedUsage = extractClaudeUsage(normalizedPayload);
2452
2670
  const factory = createEventFactory({
2453
2671
  identity: input.identity,
2454
2672
  sequenceBase: input.sequenceBase,
@@ -2472,7 +2690,8 @@ var parseClaudeCode = (input, context) => {
2472
2690
  case "SessionEnd":
2473
2691
  factory.build({
2474
2692
  type: "session.end",
2475
- reason: mapSessionEndReason(payload.reason ?? payload.end_reason)
2693
+ reason: mapSessionEndReason(payload.reason ?? payload.end_reason),
2694
+ ...withUsage(extractedUsage)
2476
2695
  });
2477
2696
  break;
2478
2697
  case "UserPromptSubmit":
@@ -2565,22 +2784,24 @@ var parseClaudeCode = (input, context) => {
2565
2784
  payload.session_id,
2566
2785
  payload.prompt_id ?? String(input.sequenceBase)
2567
2786
  ]);
2787
+ const assistantText = extractClaudeAssistantText(normalizedPayload);
2568
2788
  factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
2569
2789
  factory.build({
2570
2790
  type: "generation.end",
2571
2791
  generationId,
2572
2792
  model: UNKNOWN_MODEL,
2573
2793
  outcome: "ok",
2574
- ...payload.last_assistant_message === void 0 || payload.last_assistant_message === "" ? {} : {
2575
- outputContent: [
2576
- context.privacy.describeContent({
2577
- kind: "response",
2578
- role: "assistant",
2579
- text: payload.last_assistant_message
2580
- })
2581
- ]
2582
- },
2583
- ...withUsage(payload.usage)
2794
+ // Always a response fact: a body when Claude sent text, otherwise a
2795
+ // zero-length omitted fact so the log mapping can emit metadata_only
2796
+ // instead of a generation.end with no content.kind.
2797
+ outputContent: [
2798
+ assistantText === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
2799
+ kind: "response",
2800
+ role: "assistant",
2801
+ text: assistantText
2802
+ })
2803
+ ],
2804
+ ...withUsage(extractedUsage ?? payload.usage)
2584
2805
  });
2585
2806
  break;
2586
2807
  }
@@ -2590,6 +2811,7 @@ var parseClaudeCode = (input, context) => {
2590
2811
  payload.session_id,
2591
2812
  payload.prompt_id ?? String(input.sequenceBase)
2592
2813
  ]);
2814
+ const assistantText = extractClaudeAssistantText(normalizedPayload);
2593
2815
  factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
2594
2816
  factory.build({
2595
2817
  type: "generation.end",
@@ -2597,7 +2819,16 @@ var parseClaudeCode = (input, context) => {
2597
2819
  model: UNKNOWN_MODEL,
2598
2820
  outcome: mapStopFailureOutcome(payload.error_type),
2599
2821
  stopReason: payload.error_type,
2600
- ...withUsage(payload.usage)
2822
+ ...assistantText === void 0 ? {} : {
2823
+ outputContent: [
2824
+ context.privacy.describeContent({
2825
+ kind: "response",
2826
+ role: "assistant",
2827
+ text: assistantText
2828
+ })
2829
+ ]
2830
+ },
2831
+ ...withUsage(extractedUsage ?? payload.usage)
2601
2832
  });
2602
2833
  break;
2603
2834
  }
@@ -3773,7 +4004,7 @@ var CODEX_CAPABILITIES = Object.freeze({
3773
4004
  // compaction callbacks do not. See `./delivery.ts` for which and why.
3774
4005
  deliveryIdentifier: "partial"
3775
4006
  });
3776
- var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4007
+ var asRecord4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3777
4008
  var hasExactMarker = (payload) => {
3778
4009
  if (payload.codex_version !== void 0) {
3779
4010
  return true;
@@ -3866,7 +4097,7 @@ var outcomeFromToolResponse = (toolResponse) => {
3866
4097
  if (toolResponse === void 0) {
3867
4098
  return "unknown";
3868
4099
  }
3869
- const record = asRecord(toolResponse);
4100
+ const record = asRecord4(toolResponse);
3870
4101
  if (record === void 0) {
3871
4102
  return "ok";
3872
4103
  }
@@ -5493,7 +5724,7 @@ var createOtelHook = (deps) => {
5493
5724
  }
5494
5725
  const facts = collectContentFacts(event3);
5495
5726
  const offending = facts.find(
5496
- (fact) => fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact)
5727
+ (fact) => !isUnavailableContentFact(fact) && (fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact))
5497
5728
  );
5498
5729
  if (offending !== void 0) {
5499
5730
  reject(
@@ -6445,6 +6676,9 @@ var findDisclosureViolations = (events, expected = "omitted") => {
6445
6676
  const violations = [];
6446
6677
  for (const event3 of events) {
6447
6678
  for (const fact of collectEventContentFacts(event3)) {
6679
+ if (isUnavailableContentFact(fact)) {
6680
+ continue;
6681
+ }
6448
6682
  if (fact.disclosure !== expected) {
6449
6683
  violations.push({
6450
6684
  eventId: event3.eventId,