@osfactory/otel-hook 0.1.3 → 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 -134
  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 -134
  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 -94
  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 -95
  44. package/dist/testing.js.map +1 -1
  45. package/package.json +1 -1
package/dist/providers.js CHANGED
@@ -1281,7 +1281,14 @@ var postCompactPayloadSchema = z11.object({
1281
1281
  var stopPayloadSchema = z11.object({
1282
1282
  ...commonFields,
1283
1283
  hook_event_name: z11.literal("Stop"),
1284
+ /**
1285
+ * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
1286
+ * result messages use `result` instead; `events.ts` reads both (and camelCase
1287
+ * `lastAssistantMessage`) through `extractClaudeAssistantText`.
1288
+ */
1284
1289
  last_assistant_message: z11.string().optional(),
1290
+ /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
1291
+ result: z11.string().optional(),
1285
1292
  /**
1286
1293
  * True when this stop fired because a hook continued the turn.
1287
1294
  *
@@ -1345,6 +1352,229 @@ var claudeIdentityFieldsSchema = z11.object({
1345
1352
  stop_hook_active: z11.boolean().optional()
1346
1353
  });
1347
1354
 
1355
+ // src/providers/claude/usage.ts
1356
+ var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
1357
+ total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
1358
+ 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"
1359
+ });
1360
+ var ITERATION_COUNTERS = [
1361
+ "input_tokens",
1362
+ "output_tokens",
1363
+ "cache_read_input_tokens",
1364
+ "cache_creation_input_tokens"
1365
+ ];
1366
+ var ttlSplitTotal = (raw) => {
1367
+ const split = raw.cache_creation;
1368
+ if (split === void 0) {
1369
+ return void 0;
1370
+ }
1371
+ return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
1372
+ };
1373
+ var resolveCacheCreationTokens = (raw, warnings) => {
1374
+ const declared = raw.cache_creation_input_tokens;
1375
+ const split = ttlSplitTotal(raw);
1376
+ if (declared === void 0) {
1377
+ return split ?? 0;
1378
+ }
1379
+ if (split !== void 0 && split !== declared) {
1380
+ warnings.push(
1381
+ `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`
1382
+ );
1383
+ }
1384
+ return declared;
1385
+ };
1386
+ var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
1387
+ const iterations = raw.iterations;
1388
+ if (iterations === void 0 || iterations.length === 0) {
1389
+ return;
1390
+ }
1391
+ const outer = {
1392
+ input_tokens: raw.input_tokens,
1393
+ output_tokens: raw.output_tokens,
1394
+ cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
1395
+ cache_creation_input_tokens: cacheCreationInputTokens
1396
+ };
1397
+ for (const counter of ITERATION_COUNTERS) {
1398
+ const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
1399
+ if (summed !== outer[counter]) {
1400
+ warnings.push(
1401
+ `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`
1402
+ );
1403
+ }
1404
+ }
1405
+ };
1406
+ var auditExcludedCounters = (raw, warnings) => {
1407
+ if (raw.total_tokens !== void 0) {
1408
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
1409
+ }
1410
+ if (raw.reasoning_output_tokens !== void 0) {
1411
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
1412
+ }
1413
+ };
1414
+ var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
1415
+ var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
1416
+ var asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1417
+ var asNonNegativeInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1418
+ var coerceClaudeUsage = (value) => {
1419
+ const record = asRecord(value);
1420
+ if (record === void 0) {
1421
+ return void 0;
1422
+ }
1423
+ const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);
1424
+ const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);
1425
+ if (inputTokens === void 0 || outputTokens === void 0) {
1426
+ return void 0;
1427
+ }
1428
+ const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);
1429
+ const parsed = claudeUsageSchema.safeParse({
1430
+ input_tokens: inputTokens,
1431
+ output_tokens: outputTokens,
1432
+ ...asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) === void 0 ? {} : {
1433
+ cache_creation_input_tokens: asNonNegativeInt(
1434
+ record.cache_creation_input_tokens ?? record.cacheCreationInputTokens
1435
+ )
1436
+ },
1437
+ ...asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === void 0 ? {} : {
1438
+ cache_read_input_tokens: asNonNegativeInt(
1439
+ record.cache_read_input_tokens ?? record.cacheReadInputTokens
1440
+ )
1441
+ },
1442
+ ...cacheCreation === void 0 ? {} : {
1443
+ cache_creation: {
1444
+ ...asNonNegativeInt(
1445
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
1446
+ ) === void 0 ? {} : {
1447
+ ephemeral_5m_input_tokens: asNonNegativeInt(
1448
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
1449
+ )
1450
+ },
1451
+ ...asNonNegativeInt(
1452
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
1453
+ ) === void 0 ? {} : {
1454
+ ephemeral_1h_input_tokens: asNonNegativeInt(
1455
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
1456
+ )
1457
+ }
1458
+ }
1459
+ },
1460
+ ...Array.isArray(record.iterations) ? { iterations: record.iterations } : {},
1461
+ ...asNonNegativeInt(record.total_tokens ?? record.totalTokens) === void 0 ? {} : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) },
1462
+ ...asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) === void 0 ? {} : {
1463
+ reasoning_output_tokens: asNonNegativeInt(
1464
+ record.reasoning_output_tokens ?? record.reasoningOutputTokens
1465
+ )
1466
+ }
1467
+ });
1468
+ return parsed.success ? parsed.data : void 0;
1469
+ };
1470
+ var extractClaudeUsage = (payload) => {
1471
+ const record = asRecord(payload);
1472
+ if (record === void 0) {
1473
+ return void 0;
1474
+ }
1475
+ const message = asRecord(record.message);
1476
+ const candidates = [
1477
+ record.usage,
1478
+ record.token_usage,
1479
+ record.tokenUsage,
1480
+ message?.usage,
1481
+ record
1482
+ ];
1483
+ for (const candidate of candidates) {
1484
+ const usage = coerceClaudeUsage(candidate);
1485
+ if (usage !== void 0) {
1486
+ return usage;
1487
+ }
1488
+ }
1489
+ return void 0;
1490
+ };
1491
+ var normalizeClaudeUsage = (raw) => {
1492
+ if (raw === void 0) {
1493
+ return { warnings: [] };
1494
+ }
1495
+ const warnings = [];
1496
+ const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
1497
+ const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
1498
+ auditIterations(raw, cacheCreationInputTokens, warnings);
1499
+ auditExcludedCounters(raw, warnings);
1500
+ const result = normalizeUsage({
1501
+ temporality: "delta",
1502
+ inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
1503
+ cachedInputTokens,
1504
+ cacheCreationInputTokens,
1505
+ cacheCreationAccounting: "included-in-input",
1506
+ outputTokens: raw.output_tokens
1507
+ });
1508
+ if (result.status === "invalid") {
1509
+ return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
1510
+ }
1511
+ return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
1512
+ };
1513
+
1514
+ // src/providers/claude/payload-normalize.ts
1515
+ var FIELD_ALIASES = Object.freeze({
1516
+ hookEventName: "hook_event_name",
1517
+ sessionId: "session_id",
1518
+ lastAssistantMessage: "last_assistant_message",
1519
+ transcriptPath: "transcript_path",
1520
+ promptId: "prompt_id",
1521
+ toolUseId: "tool_use_id",
1522
+ toolName: "tool_name",
1523
+ toolInput: "tool_input",
1524
+ toolResponse: "tool_response",
1525
+ toolError: "tool_error",
1526
+ stopHookActive: "stop_hook_active",
1527
+ agentId: "agent_id",
1528
+ agentType: "agent_type",
1529
+ errorType: "error_type",
1530
+ errorMessage: "error_message",
1531
+ tokenUsage: "token_usage"
1532
+ });
1533
+ var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1534
+ var applyFieldAliases = (record) => {
1535
+ const normalized = { ...record };
1536
+ for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {
1537
+ if (normalized[canonical] === void 0 && normalized[alias] !== void 0) {
1538
+ normalized[canonical] = normalized[alias];
1539
+ }
1540
+ }
1541
+ return normalized;
1542
+ };
1543
+ var applyPrintResultShape = (record) => {
1544
+ if (record.hook_event_name !== void 0 || record.type !== "result") {
1545
+ return record;
1546
+ }
1547
+ if (typeof record.session_id !== "string" || record.session_id.length === 0) {
1548
+ return record;
1549
+ }
1550
+ const isError = record.subtype === "error" || record.is_error === true;
1551
+ const normalized = {
1552
+ ...record,
1553
+ hook_event_name: isError ? "StopFailure" : "Stop"
1554
+ };
1555
+ if (normalized.last_assistant_message === void 0 && typeof record.result === "string" && record.result.length > 0) {
1556
+ normalized.last_assistant_message = record.result;
1557
+ }
1558
+ if (isError && (typeof normalized.error_type !== "string" || normalized.error_type.length === 0)) {
1559
+ normalized.error_type = "unknown";
1560
+ }
1561
+ return normalized;
1562
+ };
1563
+ var normalizeClaudeHookPayload = (payload) => {
1564
+ const record = asRecord2(payload);
1565
+ if (record === void 0) {
1566
+ return payload;
1567
+ }
1568
+ return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
1569
+ };
1570
+ var applyUsageShape = (record) => {
1571
+ const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
1572
+ if (usage === void 0) {
1573
+ return record;
1574
+ }
1575
+ return { ...record, usage };
1576
+ };
1577
+
1348
1578
  // src/providers/claude/delivery.ts
1349
1579
  var TOOL_SCOPED_EVENTS = [
1350
1580
  "PreToolUse",
@@ -1353,7 +1583,7 @@ var TOOL_SCOPED_EVENTS = [
1353
1583
  "PermissionRequest"
1354
1584
  ];
1355
1585
  var claudeDeliveryIdentity = (input) => {
1356
- const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
1586
+ const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));
1357
1587
  if (!parsed.success) {
1358
1588
  return void 0;
1359
1589
  }
@@ -1429,7 +1659,7 @@ var none = (reason) => providerDetectionSchema.parse({
1429
1659
  reasons: [reason]
1430
1660
  });
1431
1661
  var detectClaudeCode = (input) => {
1432
- const { payload } = input;
1662
+ const payload = normalizeClaudeHookPayload(input.payload);
1433
1663
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
1434
1664
  return none("payload is not a JSON object");
1435
1665
  }
@@ -1443,14 +1673,16 @@ var detectClaudeCode = (input) => {
1443
1673
  return none("session_id is missing");
1444
1674
  }
1445
1675
  const hasTranscriptPath = typeof record.transcript_path === "string" && record.transcript_path.length > 0;
1676
+ const isPrintResult = record.type === "result";
1446
1677
  const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;
1447
1678
  return providerDetectionSchema.parse({
1448
1679
  providerId: CLAUDE_CODE_PROVIDER_ID,
1449
- confidence: hinted ? "exact" : hasTranscriptPath ? "strong" : "weak",
1680
+ confidence: hinted ? "exact" : hasTranscriptPath || isPrintResult ? "strong" : "weak",
1450
1681
  reasons: [
1451
1682
  `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,
1452
1683
  "session_id present",
1453
1684
  ...hasTranscriptPath ? ["transcript_path present"] : [],
1685
+ ...isPrintResult ? ["type=result print/SDK result message"] : [],
1454
1686
  ...hinted ? ["caller asserted providerHint=claude-code"] : []
1455
1687
  ],
1456
1688
  sourceEventName: hookEventName
@@ -1507,7 +1739,7 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
1507
1739
  // src/providers/claude/identity.ts
1508
1740
  var subagentInvocationIdFor = (context, sessionId, agentId) => invocationIdSchema.parse(`subagent_${context.ids.newOpaqueId(["claude-subagent", sessionId, agentId])}`);
1509
1741
  var identifyClaudeCode = (input, context) => {
1510
- const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
1742
+ const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));
1511
1743
  if (!parsed.success) {
1512
1744
  return [];
1513
1745
  }
@@ -1539,6 +1771,62 @@ var identifyClaudeCode = (input, context) => {
1539
1771
  return [claim];
1540
1772
  };
1541
1773
 
1774
+ // src/providers/claude/stop-content.ts
1775
+ var TOP_LEVEL_TEXT_FIELDS = [
1776
+ "last_assistant_message",
1777
+ "lastAssistantMessage",
1778
+ "result",
1779
+ "assistant_message",
1780
+ "final_message"
1781
+ ];
1782
+ var MESSAGE_TEXT_FIELDS = ["content", "text", "result"];
1783
+ var asRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1784
+ var nonEmptyString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
1785
+ var textFromContentBlocks = (value) => {
1786
+ if (!Array.isArray(value)) {
1787
+ return void 0;
1788
+ }
1789
+ const parts = [];
1790
+ for (const block of value) {
1791
+ const record = asRecord3(block);
1792
+ if (record === void 0) {
1793
+ continue;
1794
+ }
1795
+ const text = nonEmptyString(record.text);
1796
+ if (text !== void 0 && (record.type === void 0 || record.type === "text")) {
1797
+ parts.push(text);
1798
+ }
1799
+ }
1800
+ return parts.length === 0 ? void 0 : parts.join("");
1801
+ };
1802
+ var extractClaudeAssistantText = (payload) => {
1803
+ const record = asRecord3(payload);
1804
+ if (record === void 0) {
1805
+ return void 0;
1806
+ }
1807
+ for (const field of TOP_LEVEL_TEXT_FIELDS) {
1808
+ const text = nonEmptyString(record[field]);
1809
+ if (text !== void 0) {
1810
+ return text;
1811
+ }
1812
+ }
1813
+ const messageText2 = nonEmptyString(record.message);
1814
+ if (messageText2 !== void 0) {
1815
+ return messageText2;
1816
+ }
1817
+ const message = asRecord3(record.message);
1818
+ if (message === void 0) {
1819
+ return void 0;
1820
+ }
1821
+ for (const field of MESSAGE_TEXT_FIELDS) {
1822
+ const text = nonEmptyString(message[field]) ?? textFromContentBlocks(message[field]);
1823
+ if (text !== void 0) {
1824
+ return text;
1825
+ }
1826
+ }
1827
+ return void 0;
1828
+ };
1829
+
1542
1830
  // src/providers/claude/tool-kind.ts
1543
1831
  var BUILT_IN_TOOL_KIND = Object.freeze({
1544
1832
  Bash: "execute",
@@ -1567,90 +1855,6 @@ var inferToolKind = (toolName) => {
1567
1855
  return BUILT_IN_TOOL_KIND[toolName] ?? "unknown";
1568
1856
  };
1569
1857
 
1570
- // src/providers/claude/usage.ts
1571
- var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
1572
- total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
1573
- 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"
1574
- });
1575
- var ITERATION_COUNTERS = [
1576
- "input_tokens",
1577
- "output_tokens",
1578
- "cache_read_input_tokens",
1579
- "cache_creation_input_tokens"
1580
- ];
1581
- var ttlSplitTotal = (raw) => {
1582
- const split = raw.cache_creation;
1583
- if (split === void 0) {
1584
- return void 0;
1585
- }
1586
- return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
1587
- };
1588
- var resolveCacheCreationTokens = (raw, warnings) => {
1589
- const declared = raw.cache_creation_input_tokens;
1590
- const split = ttlSplitTotal(raw);
1591
- if (declared === void 0) {
1592
- return split ?? 0;
1593
- }
1594
- if (split !== void 0 && split !== declared) {
1595
- warnings.push(
1596
- `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`
1597
- );
1598
- }
1599
- return declared;
1600
- };
1601
- var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
1602
- const iterations = raw.iterations;
1603
- if (iterations === void 0 || iterations.length === 0) {
1604
- return;
1605
- }
1606
- const outer = {
1607
- input_tokens: raw.input_tokens,
1608
- output_tokens: raw.output_tokens,
1609
- cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
1610
- cache_creation_input_tokens: cacheCreationInputTokens
1611
- };
1612
- for (const counter of ITERATION_COUNTERS) {
1613
- const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
1614
- if (summed !== outer[counter]) {
1615
- warnings.push(
1616
- `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`
1617
- );
1618
- }
1619
- }
1620
- };
1621
- var auditExcludedCounters = (raw, warnings) => {
1622
- if (raw.total_tokens !== void 0) {
1623
- warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
1624
- }
1625
- if (raw.reasoning_output_tokens !== void 0) {
1626
- warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
1627
- }
1628
- };
1629
- var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
1630
- var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
1631
- var normalizeClaudeUsage = (raw) => {
1632
- if (raw === void 0) {
1633
- return { warnings: [] };
1634
- }
1635
- const warnings = [];
1636
- const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
1637
- const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
1638
- auditIterations(raw, cacheCreationInputTokens, warnings);
1639
- auditExcludedCounters(raw, warnings);
1640
- const result = normalizeUsage({
1641
- temporality: "delta",
1642
- inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
1643
- cachedInputTokens,
1644
- cacheCreationInputTokens,
1645
- cacheCreationAccounting: "included-in-input",
1646
- outputTokens: raw.output_tokens
1647
- });
1648
- if (result.status === "invalid") {
1649
- return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
1650
- }
1651
- return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
1652
- };
1653
-
1654
1858
  // src/providers/claude/events.ts
1655
1859
  var UNKNOWN_MODEL = { modelId: "unknown" };
1656
1860
  var SESSION_END_REASON = Object.freeze({
@@ -1683,7 +1887,8 @@ var DENIED_STOP_FAILURE_TYPES = /* @__PURE__ */ new Set([
1683
1887
  var mapStopFailureOutcome = (errorType) => DENIED_STOP_FAILURE_TYPES.has(errorType) ? "denied" : "error";
1684
1888
  var applyUsage = (normalized) => normalized.usage === void 0 ? {} : { usage: normalized.usage };
1685
1889
  var parseClaudeCode = (input, context) => {
1686
- const parsed = claudeHookPayloadSchema.safeParse(input.payload);
1890
+ const normalizedPayload = normalizeClaudeHookPayload(input.payload);
1891
+ const parsed = claudeHookPayloadSchema.safeParse(normalizedPayload);
1687
1892
  if (!parsed.success) {
1688
1893
  const rawEventName = typeof input.payload === "object" && input.payload !== null ? input.payload.hook_event_name : void 0;
1689
1894
  return {
@@ -1697,6 +1902,7 @@ var parseClaudeCode = (input, context) => {
1697
1902
  };
1698
1903
  }
1699
1904
  const payload = parsed.data;
1905
+ const extractedUsage = extractClaudeUsage(normalizedPayload);
1700
1906
  const factory = createEventFactory({
1701
1907
  identity: input.identity,
1702
1908
  sequenceBase: input.sequenceBase,
@@ -1720,7 +1926,8 @@ var parseClaudeCode = (input, context) => {
1720
1926
  case "SessionEnd":
1721
1927
  factory.build({
1722
1928
  type: "session.end",
1723
- reason: mapSessionEndReason(payload.reason ?? payload.end_reason)
1929
+ reason: mapSessionEndReason(payload.reason ?? payload.end_reason),
1930
+ ...withUsage(extractedUsage)
1724
1931
  });
1725
1932
  break;
1726
1933
  case "UserPromptSubmit":
@@ -1813,13 +2020,24 @@ var parseClaudeCode = (input, context) => {
1813
2020
  payload.session_id,
1814
2021
  payload.prompt_id ?? String(input.sequenceBase)
1815
2022
  ]);
2023
+ const assistantText = extractClaudeAssistantText(normalizedPayload);
1816
2024
  factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
1817
2025
  factory.build({
1818
2026
  type: "generation.end",
1819
2027
  generationId,
1820
2028
  model: UNKNOWN_MODEL,
1821
2029
  outcome: "ok",
1822
- ...withUsage(payload.usage)
2030
+ // Always a response fact: a body when Claude sent text, otherwise a
2031
+ // zero-length omitted fact so the log mapping can emit metadata_only
2032
+ // instead of a generation.end with no content.kind.
2033
+ outputContent: [
2034
+ assistantText === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
2035
+ kind: "response",
2036
+ role: "assistant",
2037
+ text: assistantText
2038
+ })
2039
+ ],
2040
+ ...withUsage(extractedUsage ?? payload.usage)
1823
2041
  });
1824
2042
  break;
1825
2043
  }
@@ -1829,6 +2047,7 @@ var parseClaudeCode = (input, context) => {
1829
2047
  payload.session_id,
1830
2048
  payload.prompt_id ?? String(input.sequenceBase)
1831
2049
  ]);
2050
+ const assistantText = extractClaudeAssistantText(normalizedPayload);
1832
2051
  factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
1833
2052
  factory.build({
1834
2053
  type: "generation.end",
@@ -1836,7 +2055,16 @@ var parseClaudeCode = (input, context) => {
1836
2055
  model: UNKNOWN_MODEL,
1837
2056
  outcome: mapStopFailureOutcome(payload.error_type),
1838
2057
  stopReason: payload.error_type,
1839
- ...withUsage(payload.usage)
2058
+ ...assistantText === void 0 ? {} : {
2059
+ outputContent: [
2060
+ context.privacy.describeContent({
2061
+ kind: "response",
2062
+ role: "assistant",
2063
+ text: assistantText
2064
+ })
2065
+ ]
2066
+ },
2067
+ ...withUsage(extractedUsage ?? payload.usage)
1840
2068
  });
1841
2069
  break;
1842
2070
  }
@@ -3012,7 +3240,7 @@ var CODEX_CAPABILITIES = Object.freeze({
3012
3240
  // compaction callbacks do not. See `./delivery.ts` for which and why.
3013
3241
  deliveryIdentifier: "partial"
3014
3242
  });
3015
- var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3243
+ var asRecord4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3016
3244
  var hasExactMarker = (payload) => {
3017
3245
  if (payload.codex_version !== void 0) {
3018
3246
  return true;
@@ -3105,7 +3333,7 @@ var outcomeFromToolResponse = (toolResponse) => {
3105
3333
  if (toolResponse === void 0) {
3106
3334
  return "unknown";
3107
3335
  }
3108
- const record = asRecord(toolResponse);
3336
+ const record = asRecord4(toolResponse);
3109
3337
  if (record === void 0) {
3110
3338
  return "ok";
3111
3339
  }