@osfactory/otel-hook 0.4.1 → 0.6.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 (43) hide show
  1. package/dist/{adapter-BgqtlADe.d.ts → adapter-BJiz6lqM.d.ts} +2 -3
  2. package/dist/cli.js +100 -35
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{events-C3h3GvHj.d.ts → events-B3MHoJTD.d.ts} +190 -1
  5. package/dist/{filesystem-store-BAq3VGVv.d.ts → filesystem-store-r-nNA3BA.d.ts} +1 -1
  6. package/dist/{hook-CQiNa88Q.d.ts → hook-Dh8OO4Wa.d.ts} +4 -4
  7. package/dist/index.d.ts +12 -13
  8. package/dist/index.js +105 -35
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.d.ts +4 -5
  11. package/dist/install.js +13 -3
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +8 -9
  14. package/dist/integration.js +2299 -2246
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +3 -3
  17. package/dist/lifecycle.js +762 -213
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-kflYgZbg.d.ts → memory-Bl9ANVff.d.ts} +2 -2
  20. package/dist/model.d.ts +1 -2
  21. package/dist/model.js +20 -4
  22. package/dist/model.js.map +1 -1
  23. package/dist/{otlp-log-sink-BZIgYPKN.d.ts → otlp-log-sink-eUEjaLhk.d.ts} +3 -3
  24. package/dist/{payload-DpyU8F-z.d.ts → payload-Ci8_ERm6.d.ts} +1 -1
  25. package/dist/{ports-B_iwJQPQ.d.ts → ports-n7KFOpKo.d.ts} +9 -1
  26. package/dist/providers.d.ts +10 -11
  27. package/dist/providers.js +37 -14
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-BSBS8t7S.d.ts → registry-CIVvRlVK.d.ts} +1 -1
  30. package/dist/runtime.d.ts +32 -16
  31. package/dist/runtime.js +57 -15
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{semconv-BeUPQ7_q.d.ts → semconv-fPRb-dpU.d.ts} +1 -1
  34. package/dist/state.d.ts +4 -4
  35. package/dist/state.js.map +1 -1
  36. package/dist/telemetry.d.ts +6 -6
  37. package/dist/telemetry.js +953 -414
  38. package/dist/telemetry.js.map +1 -1
  39. package/dist/testing.d.ts +14 -9
  40. package/dist/testing.js +45 -20
  41. package/dist/testing.js.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/target-8RfaVxp8.d.ts +0 -83
package/dist/lifecycle.js CHANGED
@@ -268,22 +268,748 @@ import {
268
268
  } from "@opentelemetry/semantic-conventions/incubating";
269
269
 
270
270
  // src/version.ts
271
- var VERSION = "0.4.1";
271
+ var VERSION = "0.6.0";
272
272
 
273
273
  // src/telemetry/export-identity.ts
274
274
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
275
+
276
+ // src/model/events.ts
277
+ import { z as z9 } from "zod";
278
+
279
+ // src/errors/taxonomy.ts
280
+ import { z as z2 } from "zod";
281
+ var otelHookErrorCodeSchema = z2.enum([
282
+ /** Input was not usable at all (empty stdin, unparsable JSON). */
283
+ "invalid-input",
284
+ /** Input parsed but failed canonical schema validation. */
285
+ "schema-validation-failed",
286
+ /** No adapter claimed the input with sufficient confidence. */
287
+ "provider-unknown",
288
+ /** Several adapters claimed the input at the same confidence. */
289
+ "provider-detection-ambiguous",
290
+ /** An adapter threw or returned a malformed result. */
291
+ "provider-adapter-failure",
292
+ /** Two identity claims disagreed at equal confidence. */
293
+ "identity-conflict",
294
+ /** Required identity fields were absent. */
295
+ "identity-incomplete",
296
+ /** A usage report violated the canonical usage invariants. */
297
+ "usage-invalid",
298
+ /** The state store could not be read or written. */
299
+ "state-store-failure",
300
+ /** The telemetry sink rejected or could not deliver a batch. */
301
+ "telemetry-export-failure",
302
+ /** Content reached the sink boundary in a state the policy forbids. */
303
+ "privacy-policy-violation",
304
+ /** Configuration could not be resolved. */
305
+ "configuration-invalid",
306
+ /** A configured bound (events, batch size) dropped data. */
307
+ "limit-exceeded",
308
+ /**
309
+ * No replay-stable delivery identifier was available for a callback while
310
+ * deduplication was required.
311
+ */
312
+ "delivery-identifier-unavailable",
313
+ "delivery-claim-superseded",
314
+ /** Anything unanticipated. Always reported, never fatal to the host. */
315
+ "internal-error"
316
+ ]);
317
+ var errorSeveritySchema = z2.enum(["warning", "error"]);
318
+ var errorPhaseSchema = z2.enum([
319
+ "configuration",
320
+ "detection",
321
+ "identity",
322
+ "parsing",
323
+ "normalization",
324
+ "privacy",
325
+ "state",
326
+ "export",
327
+ "shutdown"
328
+ ]);
329
+ var failurePostureSchema = z2.enum(["fail-open", "fail-closed-attribution"]);
330
+ var ERROR_TAXONOMY = Object.freeze({
331
+ "invalid-input": {
332
+ code: "invalid-input",
333
+ severity: "warning",
334
+ posture: "fail-open",
335
+ retryable: false,
336
+ summary: "Input could not be read or decoded."
337
+ },
338
+ "schema-validation-failed": {
339
+ code: "schema-validation-failed",
340
+ severity: "error",
341
+ posture: "fail-closed-attribution",
342
+ retryable: false,
343
+ summary: "A canonical event failed schema validation and was dropped."
344
+ },
345
+ "provider-unknown": {
346
+ code: "provider-unknown",
347
+ severity: "warning",
348
+ posture: "fail-closed-attribution",
349
+ retryable: false,
350
+ summary: "No adapter recognized the source provider; the input stays unattributed."
351
+ },
352
+ "provider-detection-ambiguous": {
353
+ code: "provider-detection-ambiguous",
354
+ severity: "warning",
355
+ posture: "fail-closed-attribution",
356
+ retryable: false,
357
+ summary: "Multiple adapters claimed the input at equal confidence."
358
+ },
359
+ "provider-adapter-failure": {
360
+ code: "provider-adapter-failure",
361
+ severity: "error",
362
+ posture: "fail-open",
363
+ retryable: false,
364
+ summary: "A provider adapter failed while parsing."
365
+ },
366
+ "identity-conflict": {
367
+ code: "identity-conflict",
368
+ severity: "error",
369
+ posture: "fail-closed-attribution",
370
+ retryable: false,
371
+ summary: "Identity claims disagreed; attribution was declined."
372
+ },
373
+ "identity-incomplete": {
374
+ code: "identity-incomplete",
375
+ severity: "warning",
376
+ posture: "fail-closed-attribution",
377
+ retryable: false,
378
+ summary: "Required identity fields were missing; attribution was declined."
379
+ },
380
+ "usage-invalid": {
381
+ code: "usage-invalid",
382
+ severity: "error",
383
+ posture: "fail-open",
384
+ retryable: false,
385
+ summary: "A usage report violated the canonical usage invariants."
386
+ },
387
+ "state-store-failure": {
388
+ code: "state-store-failure",
389
+ severity: "warning",
390
+ posture: "fail-open",
391
+ retryable: true,
392
+ summary: "State could not be read or written; derived values may be incomplete."
393
+ },
394
+ "telemetry-export-failure": {
395
+ code: "telemetry-export-failure",
396
+ severity: "warning",
397
+ posture: "fail-open",
398
+ retryable: true,
399
+ summary: "The telemetry sink could not accept a batch."
400
+ },
401
+ "privacy-policy-violation": {
402
+ code: "privacy-policy-violation",
403
+ severity: "error",
404
+ posture: "fail-closed-attribution",
405
+ retryable: false,
406
+ summary: "Content violated the resolved privacy policy and was dropped."
407
+ },
408
+ "configuration-invalid": {
409
+ code: "configuration-invalid",
410
+ severity: "error",
411
+ posture: "fail-open",
412
+ retryable: false,
413
+ summary: "Configuration could not be resolved; defaults apply."
414
+ },
415
+ "limit-exceeded": {
416
+ code: "limit-exceeded",
417
+ severity: "warning",
418
+ posture: "fail-open",
419
+ retryable: false,
420
+ summary: "A configured bound was reached and data was dropped."
421
+ },
422
+ "delivery-identifier-unavailable": {
423
+ code: "delivery-identifier-unavailable",
424
+ severity: "warning",
425
+ // Fail-open: the observation is still attributed and exported. Only the
426
+ // at-most-once guarantee is missing, and refusing the telemetry to protect
427
+ // a duplicate count would trade a certain loss for a possible one.
428
+ posture: "fail-open",
429
+ retryable: false,
430
+ summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
431
+ },
432
+ "delivery-claim-superseded": {
433
+ code: "delivery-claim-superseded",
434
+ severity: "warning",
435
+ // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
436
+ // claim while this process was still working on it, which means the
437
+ // configured stale window is shorter than this installation's real worst
438
+ // case. Both processes may now have exported the callback, so the
439
+ // at-most-once guarantee did not hold for it — the only honest response is
440
+ // to say so and let the operator raise the window.
441
+ posture: "fail-open",
442
+ retryable: false,
443
+ summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
444
+ },
445
+ "internal-error": {
446
+ code: "internal-error",
447
+ severity: "error",
448
+ posture: "fail-open",
449
+ retryable: false,
450
+ summary: "An unexpected failure was contained."
451
+ }
452
+ });
453
+ var attributionOutcomeSchema = z2.enum([
454
+ /** Identity resolved; events carry provider and session identity. */
455
+ "attributed",
456
+ /** Identity could not be established safely; nothing was attributed. */
457
+ "declined",
458
+ /** Attribution was attempted and failed unexpectedly. */
459
+ "failed",
460
+ /** Input was recognized but intentionally carried no telemetry. */
461
+ "not-applicable"
462
+ ]);
463
+ var attributionReasonSchema = z2.enum([
464
+ "provider-unknown",
465
+ "provider-detection-ambiguous",
466
+ "identity-conflict",
467
+ "identity-incomplete",
468
+ "adapter-ignored-input",
469
+ "adapter-failure",
470
+ "invalid-input",
471
+ "internal-error"
472
+ ]);
473
+
474
+ // src/model/content.ts
475
+ import { z as z3 } from "zod";
476
+ var contentKindSchema = z3.enum([
477
+ "prompt",
478
+ "response",
479
+ "reasoning",
480
+ "tool-input",
481
+ "tool-output",
482
+ "error-message",
483
+ "system-instruction",
484
+ "attachment"
485
+ ]);
486
+ var contentRoleSchema = z3.enum(["user", "assistant", "system", "tool", "unknown"]);
487
+ var contentDisclosureSchema = z3.enum(["omitted", "masked", "redacted", "raw"]);
488
+ var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
489
+ var contentFactSchema = z3.strictObject({
490
+ kind: contentKindSchema,
491
+ role: contentRoleSchema.optional(),
492
+ /** Unicode code point count of the original content. */
493
+ characterLength: z3.number().int().min(0),
494
+ /** UTF-8 byte length of the original content. */
495
+ byteLength: z3.number().int().min(0),
496
+ /** Stable salted digest of the original content. */
497
+ contentHash: z3.string().regex(CONTENT_HASH_PATTERN),
498
+ disclosure: contentDisclosureSchema,
499
+ /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
500
+ text: z3.string().optional(),
501
+ /** True when `text` was cut short by the configured string bound. */
502
+ truncated: z3.boolean(),
503
+ /** Number of secret-looking spans replaced while producing `text`. */
504
+ secretsRedacted: z3.number().int().min(0),
505
+ /** Optional non-sensitive label, e.g. a MIME type or tool name. */
506
+ label: nonEmptyStringSchema.optional()
507
+ });
508
+ var contentFactsSchema = z3.array(contentFactSchema).max(64);
509
+
510
+ // src/model/extensions.ts
511
+ import { z as z4 } from "zod";
512
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
513
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
514
+ "otelhook",
515
+ "otel",
516
+ "telemetry"
517
+ ]);
518
+ var MAX_EXTENSION_ENTRIES = 64;
519
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
520
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
521
+ var extensionsSchema = z4.record(z4.string(), attributeValueSchema).check((ctx) => {
522
+ const keys = Object.keys(ctx.value);
523
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
524
+ ctx.issues.push({
525
+ code: "custom",
526
+ input: ctx.value,
527
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
528
+ });
529
+ }
530
+ for (const key of keys) {
531
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
532
+ ctx.issues.push({
533
+ code: "custom",
534
+ input: ctx.value,
535
+ path: [key],
536
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
537
+ });
538
+ continue;
539
+ }
540
+ if (isReservedExtensionNamespace(key)) {
541
+ ctx.issues.push({
542
+ code: "custom",
543
+ input: ctx.value,
544
+ path: [key],
545
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
546
+ });
547
+ }
548
+ }
549
+ });
550
+ var EMPTY_EXTENSIONS = Object.freeze({});
551
+ var emptyExtensions = () => ({});
552
+
553
+ // src/model/identity.ts
554
+ import { z as z5 } from "zod";
555
+ var workspaceKeySourceSchema = z5.enum([
556
+ "git-remote",
557
+ "git-root",
558
+ "working-directory",
559
+ "explicit",
560
+ "unknown"
561
+ ]);
562
+ var workspaceIdentitySchema = z5.strictObject({
563
+ workspaceId: workspaceIdSchema,
564
+ keySource: workspaceKeySourceSchema,
565
+ /** Repository name only; never an owner path or URL with credentials. */
566
+ repositoryName: nonEmptyStringSchema.optional(),
567
+ vcsBranchName: nonEmptyStringSchema.optional(),
568
+ /** Opaque handle for the checked-out revision. */
569
+ vcsRevisionId: nonEmptyStringSchema.optional()
570
+ }).readonly();
571
+ var sourceProvenanceSchema = z5.strictObject({
572
+ providerId: resolvedProviderIdSchema,
573
+ providerVersion: nonEmptyStringSchema.optional(),
574
+ adapterId: nonEmptyStringSchema,
575
+ adapterVersion: nonEmptyStringSchema,
576
+ detectionConfidence: detectionConfidenceSchema,
577
+ /** The provider's own name for the source event, e.g. a hook event name. */
578
+ sourceEventName: nonEmptyStringSchema.optional(),
579
+ transport: sourceTransportSchema
580
+ }).readonly();
581
+ var consumerAttributesSchema = attributesSchema.readonly();
582
+ var invocationIdentitySchema = z5.strictObject({
583
+ invocationId: invocationIdSchema,
584
+ sessionId: sessionIdSchema,
585
+ /** Set when this invocation runs beneath another agent invocation. */
586
+ parentInvocationId: invocationIdSchema.optional(),
587
+ /** Root of the session tree when the provider exposes one. */
588
+ rootSessionId: sessionIdSchema.optional(),
589
+ /** Stable handle for the agent process/instance, when available. */
590
+ agentInstanceId: nonEmptyStringSchema.optional(),
591
+ provenance: sourceProvenanceSchema,
592
+ workspace: workspaceIdentitySchema,
593
+ startedAt: epochMillisSchema,
594
+ consumerAttributes: consumerAttributesSchema
595
+ }).readonly();
596
+ var identityClaimFieldsSchema = z5.strictObject({
597
+ invocationId: invocationIdSchema.optional(),
598
+ sessionId: sessionIdSchema.optional(),
599
+ parentInvocationId: invocationIdSchema.optional(),
600
+ rootSessionId: sessionIdSchema.optional(),
601
+ agentInstanceId: nonEmptyStringSchema.optional(),
602
+ workspace: workspaceIdentitySchema.optional(),
603
+ startedAt: epochMillisSchema.optional()
604
+ });
605
+ var identityClaimSchema = z5.strictObject({
606
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
607
+ source: nonEmptyStringSchema,
608
+ confidence: detectionConfidenceSchema,
609
+ fields: identityClaimFieldsSchema
610
+ });
611
+
612
+ // src/model/target.ts
613
+ import { z as z6 } from "zod";
614
+ var targetSourceSchema = z6.enum(["tool-path", "shell-cwd", "session-cwd"]);
615
+ var MAX_TARGET_HINT_PATHS = 8;
616
+ var MAX_TARGET_PATH_LENGTH = 4096;
617
+ var localPathSchema = z6.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
618
+ var targetHintSchema = z6.strictObject({
619
+ source: targetSourceSchema,
620
+ paths: z6.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
621
+ /** Absolute directory that relative `paths` resolve against. */
622
+ baseDirectory: localPathSchema.optional()
623
+ }).readonly();
624
+ var worktreeKindSchema = z6.enum(["main", "linked"]);
625
+ var workspaceTargetSchema = z6.strictObject({
626
+ workspaceId: workspaceIdSchema,
627
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
628
+ vcsBranchName: nonEmptyStringSchema.optional(),
629
+ source: targetSourceSchema,
630
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
631
+ repositoryId: workspaceIdSchema.optional(),
632
+ worktreeKind: worktreeKindSchema.optional()
633
+ }).readonly();
634
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
635
+ var subagentIdSchema = z6.string().regex(SUBAGENT_ID_PATTERN);
636
+
637
+ // src/model/usage.ts
638
+ import { z as z7 } from "zod";
639
+ var usageTemporalitySchema = z7.enum(["delta", "cumulative"]);
640
+ var cacheCreationAccountingSchema = z7.enum([
641
+ "included-in-input",
642
+ "disjoint-from-input",
643
+ "not-reported"
644
+ ]);
645
+ var providerTotalAgreementSchema = z7.enum(["unreported", "agrees", "disagrees"]);
646
+ var usageReportSchema = z7.strictObject({
647
+ temporality: usageTemporalitySchema,
648
+ /** Inclusive input tokens. */
649
+ inputTokens: tokenCountSchema.optional(),
650
+ /** Subset of `inputTokens` served from a prompt cache. */
651
+ cachedInputTokens: tokenCountSchema.optional(),
652
+ /** Tokens written to a prompt cache. */
653
+ cacheCreationInputTokens: tokenCountSchema.optional(),
654
+ /** Required when `cacheCreationInputTokens` is present and non-zero. */
655
+ cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
656
+ /** Inclusive output tokens. */
657
+ outputTokens: tokenCountSchema.optional(),
658
+ /** Subset of `outputTokens` spent on reasoning. */
659
+ reasoningOutputTokens: tokenCountSchema.optional(),
660
+ /** Total exactly as the provider reported it, if it reported one. */
661
+ providerTotalTokens: tokenCountSchema.optional()
662
+ });
663
+ var canonicalUsageSchema = z7.strictObject({
664
+ temporality: usageTemporalitySchema,
665
+ inputTokens: tokenCountSchema,
666
+ cachedInputTokens: tokenCountSchema,
667
+ cacheCreationInputTokens: tokenCountSchema,
668
+ cacheCreationAccounting: cacheCreationAccountingSchema,
669
+ outputTokens: tokenCountSchema,
670
+ reasoningOutputTokens: tokenCountSchema,
671
+ /** Derived: input tokens that were neither cache reads nor cache writes. */
672
+ uncachedInputTokens: tokenCountSchema,
673
+ /** Derived: canonical billable total. */
674
+ totalTokens: tokenCountSchema,
675
+ providerTotalTokens: tokenCountSchema.optional(),
676
+ providerTotalAgreement: providerTotalAgreementSchema
677
+ }).check((ctx) => {
678
+ const usage = ctx.value;
679
+ const push = (message) => {
680
+ ctx.issues.push({ code: "custom", input: usage, message });
681
+ };
682
+ if (usage.cachedInputTokens > usage.inputTokens) {
683
+ push("cachedInputTokens must not exceed inputTokens (it is a subset)");
684
+ }
685
+ if (usage.reasoningOutputTokens > usage.outputTokens) {
686
+ push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
687
+ }
688
+ if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
689
+ push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
690
+ }
691
+ const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
692
+ if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
693
+ push(
694
+ "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
695
+ );
696
+ }
697
+ const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
698
+ if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
699
+ push(`uncachedInputTokens must equal ${expectedUncached}`);
700
+ }
701
+ const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
702
+ const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
703
+ if (usage.totalTokens !== expectedTotal) {
704
+ push(`totalTokens must equal ${expectedTotal}`);
705
+ }
706
+ const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
707
+ if (usage.providerTotalAgreement !== expectedAgreement) {
708
+ push(`providerTotalAgreement must be ${expectedAgreement}`);
709
+ }
710
+ });
711
+ var normalizeUsage = (report) => {
712
+ const parsed = usageReportSchema.safeParse(report);
713
+ if (!parsed.success) {
714
+ return {
715
+ status: "invalid",
716
+ issues: parsed.error.issues.map((issue) => ({
717
+ code: "invalid-report",
718
+ message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
719
+ }))
720
+ };
721
+ }
722
+ const input = parsed.data;
723
+ const issues = [];
724
+ const notes = [];
725
+ const inputTokens = input.inputTokens ?? 0;
726
+ const cachedInputTokens = input.cachedInputTokens ?? 0;
727
+ const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
728
+ const outputTokens = input.outputTokens ?? 0;
729
+ const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
730
+ let accounting;
731
+ if (cacheCreationInputTokens === 0) {
732
+ accounting = input.cacheCreationAccounting ?? "not-reported";
733
+ if (accounting !== "not-reported") {
734
+ notes.push(
735
+ `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
736
+ );
737
+ }
738
+ } else if (input.cacheCreationAccounting === void 0) {
739
+ issues.push({
740
+ code: "cache-creation-accounting-missing",
741
+ message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
742
+ });
743
+ accounting = "not-reported";
744
+ } else if (input.cacheCreationAccounting === "not-reported") {
745
+ issues.push({
746
+ code: "cache-creation-accounting-missing",
747
+ message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
748
+ });
749
+ accounting = "not-reported";
750
+ } else {
751
+ accounting = input.cacheCreationAccounting;
752
+ }
753
+ if (cachedInputTokens > inputTokens) {
754
+ issues.push({
755
+ code: "cached-exceeds-input",
756
+ message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
757
+ });
758
+ }
759
+ if (reasoningOutputTokens > outputTokens) {
760
+ issues.push({
761
+ code: "reasoning-exceeds-output",
762
+ message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
763
+ });
764
+ }
765
+ const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
766
+ if (cachedInputTokens + creationInsideInput > inputTokens) {
767
+ issues.push({
768
+ code: "cache-creation-exceeds-input",
769
+ message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
770
+ });
771
+ }
772
+ if (issues.length > 0) {
773
+ return { status: "invalid", issues };
774
+ }
775
+ const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
776
+ const totalTokens = inputTokens + creationOutsideInput + outputTokens;
777
+ const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
778
+ if (providerTotalAgreement === "disagrees") {
779
+ notes.push(
780
+ `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
781
+ );
782
+ }
783
+ const usage = {
784
+ temporality: input.temporality,
785
+ inputTokens,
786
+ cachedInputTokens,
787
+ cacheCreationInputTokens,
788
+ cacheCreationAccounting: accounting,
789
+ outputTokens,
790
+ reasoningOutputTokens,
791
+ uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
792
+ totalTokens,
793
+ ...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
794
+ providerTotalAgreement
795
+ };
796
+ return { status: "ok", usage, notes };
797
+ };
798
+ var UsageNormalizationError = class extends Error {
799
+ issues;
800
+ constructor(issues) {
801
+ super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
802
+ this.name = "UsageNormalizationError";
803
+ this.issues = issues;
804
+ }
805
+ };
806
+ var normalizeUsageOrThrow = (report) => {
807
+ const result = normalizeUsage(report);
808
+ if (result.status === "invalid") {
809
+ throw new UsageNormalizationError(result.issues);
810
+ }
811
+ return result.usage;
812
+ };
813
+ var EMPTY_DELTA_USAGE = Object.freeze(
814
+ normalizeUsageOrThrow({ temporality: "delta" })
815
+ );
816
+
817
+ // src/model/version.ts
818
+ import { z as z8 } from "zod";
819
+ var CANONICAL_SCHEMA_VERSION = 1;
820
+ var canonicalSchemaVersionSchema = z8.literal(CANONICAL_SCHEMA_VERSION);
821
+
822
+ // src/model/events.ts
823
+ var modelDescriptorSchema = z9.strictObject({
824
+ modelId: nonEmptyStringSchema,
825
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
826
+ vendor: nonEmptyStringSchema.optional(),
827
+ family: nonEmptyStringSchema.optional()
828
+ });
829
+ var costFactsSchema = z9.strictObject({
830
+ /** ISO 4217 code. */
831
+ currency: z9.string().length(3),
832
+ amount: z9.number().min(0).finite(),
833
+ source: z9.enum(["provider-reported", "computed"])
834
+ });
835
+ var canonicalEventTypeSchema = z9.enum([
836
+ "session.start",
837
+ "session.end",
838
+ "prompt.submitted",
839
+ "generation.start",
840
+ "generation.end",
841
+ "tool.start",
842
+ "tool.end",
843
+ "subagent.start",
844
+ "subagent.end",
845
+ "compaction.performed",
846
+ "error.raised"
847
+ ]);
848
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
849
+ var outcomeSchema = z9.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
850
+ var baseEventFields = {
851
+ schemaVersion: canonicalSchemaVersionSchema,
852
+ eventId: eventIdSchema,
853
+ invocationId: invocationIdSchema,
854
+ sessionId: sessionIdSchema,
855
+ /** Per-invocation ordering key. Stable across replays of the same input. */
856
+ sequence: sequenceNumberSchema,
857
+ occurredAt: epochMillisSchema,
858
+ provenance: sourceProvenanceSchema,
859
+ workspace: workspaceIdentitySchema,
860
+ /**
861
+ * The provider's own id for the subagent this event was emitted inside (e.g.
862
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
863
+ * factory, never by hand.
864
+ */
865
+ subagentId: subagentIdSchema.optional(),
866
+ extensions: extensionsSchema.default(emptyExtensions)
867
+ };
868
+ var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
869
+ var sessionStartEventSchema = event({
870
+ type: z9.literal("session.start"),
871
+ sessionKind: z9.enum(["interactive", "non-interactive", "unknown"]),
872
+ agentName: nonEmptyStringSchema.optional(),
873
+ agentVersion: nonEmptyStringSchema.optional(),
874
+ model: modelDescriptorSchema.optional(),
875
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
876
+ target: workspaceTargetSchema.optional()
877
+ });
878
+ var sessionEndEventSchema = event({
879
+ type: z9.literal("session.end"),
880
+ reason: z9.enum(["completed", "aborted", "error", "timeout", "unknown"]),
881
+ durationMillis: durationMillisSchema.optional(),
882
+ /** Session totals, typically cumulative. */
883
+ usage: canonicalUsageSchema.optional(),
884
+ cost: costFactsSchema.optional()
885
+ });
886
+ var promptSubmittedEventSchema = event({
887
+ type: z9.literal("prompt.submitted"),
888
+ promptSource: z9.enum(["user", "automation", "resumed", "unknown"]),
889
+ content: contentFactSchema.optional(),
890
+ turnIndex: z9.number().int().min(0).optional(),
891
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
892
+ target: workspaceTargetSchema.optional()
893
+ });
894
+ var generationStartEventSchema = event({
895
+ type: z9.literal("generation.start"),
896
+ generationId: nonEmptyStringSchema,
897
+ model: modelDescriptorSchema,
898
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
899
+ inputContent: contentFactsSchema.optional()
900
+ });
901
+ var generationEndEventSchema = event({
902
+ type: z9.literal("generation.end"),
903
+ generationId: nonEmptyStringSchema,
904
+ model: modelDescriptorSchema,
905
+ outcome: outcomeSchema,
906
+ stopReason: nonEmptyStringSchema.optional(),
907
+ durationMillis: durationMillisSchema.optional(),
908
+ usage: canonicalUsageSchema.optional(),
909
+ cost: costFactsSchema.optional(),
910
+ outputContent: contentFactsSchema.optional()
911
+ });
912
+ var toolKindSchema = z9.enum([
913
+ "read",
914
+ "write",
915
+ "execute",
916
+ "search",
917
+ "network",
918
+ "delegate",
919
+ "other",
920
+ "unknown"
921
+ ]);
922
+ var toolStartEventSchema = event({
923
+ type: z9.literal("tool.start"),
924
+ toolCallId: nonEmptyStringSchema,
925
+ toolName: nonEmptyStringSchema,
926
+ toolKind: toolKindSchema,
927
+ generationId: nonEmptyStringSchema.optional(),
928
+ input: contentFactSchema.optional(),
929
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
930
+ target: workspaceTargetSchema.optional()
931
+ });
932
+ var toolEndEventSchema = event({
933
+ type: z9.literal("tool.end"),
934
+ toolCallId: nonEmptyStringSchema,
935
+ toolName: nonEmptyStringSchema,
936
+ outcome: outcomeSchema,
937
+ durationMillis: durationMillisSchema.optional(),
938
+ /** Present when the host asked for or recorded a permission decision. */
939
+ permissionDecision: z9.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
940
+ output: contentFactSchema.optional(),
941
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
942
+ target: workspaceTargetSchema.optional()
943
+ });
944
+ var subagentStartEventSchema = event({
945
+ type: z9.literal("subagent.start"),
946
+ subagentInvocationId: invocationIdSchema,
947
+ subagentType: nonEmptyStringSchema.optional(),
948
+ /** 0 for the top-level agent; 1 for its direct children. */
949
+ delegationDepth: z9.number().int().min(0).max(64),
950
+ model: modelDescriptorSchema.optional()
951
+ });
952
+ var subagentEndEventSchema = event({
953
+ type: z9.literal("subagent.end"),
954
+ subagentInvocationId: invocationIdSchema,
955
+ outcome: outcomeSchema,
956
+ durationMillis: durationMillisSchema.optional(),
957
+ usage: canonicalUsageSchema.optional()
958
+ });
959
+ var compactionPerformedEventSchema = event({
960
+ type: z9.literal("compaction.performed"),
961
+ trigger: z9.enum(["automatic", "manual", "unknown"]),
962
+ /** Provider-reported context size before and after compaction, if known. */
963
+ contextTokensBefore: tokenCountSchema.optional(),
964
+ contextTokensAfter: tokenCountSchema.optional(),
965
+ droppedMessageCount: z9.number().int().min(0).optional(),
966
+ usage: canonicalUsageSchema.optional()
967
+ });
968
+ var errorRaisedEventSchema = event({
969
+ type: z9.literal("error.raised"),
970
+ errorCode: otelHookErrorCodeSchema,
971
+ severity: errorSeveritySchema,
972
+ phase: errorPhaseSchema,
973
+ retryable: z9.boolean(),
974
+ /** Error text is content: it is described, never embedded verbatim by default. */
975
+ message: contentFactSchema.optional(),
976
+ /** Non-sensitive, provider-agnostic short label. */
977
+ detail: nonEmptyStringSchema.optional()
978
+ });
979
+ var canonicalEventSchema = z9.discriminatedUnion("type", [
980
+ sessionStartEventSchema,
981
+ sessionEndEventSchema,
982
+ promptSubmittedEventSchema,
983
+ generationStartEventSchema,
984
+ generationEndEventSchema,
985
+ toolStartEventSchema,
986
+ toolEndEventSchema,
987
+ subagentStartEventSchema,
988
+ subagentEndEventSchema,
989
+ compactionPerformedEventSchema,
990
+ errorRaisedEventSchema
991
+ ]);
992
+ var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
993
+ var TARGETED = new Set(TARGETED_EVENT_TYPES);
994
+ var isTargetedEvent = (event2) => TARGETED.has(event2.type);
995
+
996
+ // src/telemetry/export-identity.ts
275
997
  var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
276
998
  var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
277
999
  var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
278
- var targetAttributes = (event) => {
279
- if (event.type !== "tool.start" && event.type !== "tool.end" || event.target === void 0) {
1000
+ var ATTR_OTELHOOK_TARGET_REPOSITORY_ID = "otelhook.target.repository.id";
1001
+ var ATTR_OTELHOOK_TARGET_WORKTREE_KIND = "otelhook.target.worktree.kind";
1002
+ var targetAttributes = (event2) => {
1003
+ if (!isTargetedEvent(event2) || event2.target === void 0) {
280
1004
  return {};
281
1005
  }
282
- const { target } = event;
1006
+ const { target } = event2;
283
1007
  return {
284
1008
  [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
285
1009
  [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
286
- ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }
1010
+ ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName },
1011
+ ...target.repositoryId === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId },
1012
+ ...target.worktreeKind === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }
287
1013
  };
288
1014
  };
289
1015
 
@@ -316,57 +1042,60 @@ var familyOf = (type) => {
316
1042
  return void 0;
317
1043
  }
318
1044
  };
319
- var spanScopeRefOf = (event) => {
320
- const family = familyOf(event.type);
1045
+ var spanScopeRefOf = (event2) => {
1046
+ const family = familyOf(event2.type);
321
1047
  if (family === void 0) {
322
1048
  return void 0;
323
1049
  }
324
- switch (event.type) {
1050
+ switch (event2.type) {
325
1051
  case "session.start":
326
1052
  case "session.end":
327
- return { family, scopeKey: event.sessionId };
1053
+ return { family, scopeKey: event2.sessionId };
328
1054
  case "generation.start":
329
1055
  case "generation.end":
330
- return { family, scopeKey: event.generationId };
1056
+ return { family, scopeKey: event2.generationId };
331
1057
  case "tool.start":
332
1058
  case "tool.end":
333
- return { family, scopeKey: event.toolCallId };
1059
+ return { family, scopeKey: event2.toolCallId };
334
1060
  case "subagent.start":
335
1061
  case "subagent.end":
336
- return { family, scopeKey: event.subagentInvocationId };
1062
+ return { family, scopeKey: event2.subagentInvocationId };
337
1063
  default:
338
1064
  return void 0;
339
1065
  }
340
1066
  };
341
- var parentScopeRefOf = (event) => {
342
- if (event.type === "session.start" || event.type === "session.end") {
1067
+ var parentScopeRefOf = (event2) => {
1068
+ if (event2.type === "session.start" || event2.type === "session.end") {
343
1069
  return void 0;
344
1070
  }
345
- if (event.type === "tool.start" && event.generationId !== void 0) {
346
- return { family: "generation", scopeKey: event.generationId };
1071
+ if (event2.type === "tool.start" && event2.generationId !== void 0) {
1072
+ return { family: "generation", scopeKey: event2.generationId };
347
1073
  }
348
- return { family: "session", scopeKey: event.sessionId };
1074
+ return { family: "session", scopeKey: event2.sessionId };
349
1075
  };
350
- var startOnlySpanAttributes = (event) => {
351
- switch (event.type) {
1076
+ var startOnlySpanAttributes = (event2) => {
1077
+ switch (event2.type) {
1078
+ // The session's own worktree is carried forward like a tool's target, so
1079
+ // the session span a later `session.end` process exports still names it.
352
1080
  case "session.start":
353
1081
  return {
354
- ...event.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName },
355
- ...event.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }
1082
+ ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event2.agentName },
1083
+ ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event2.agentVersion },
1084
+ ...targetAttributes(event2)
356
1085
  };
357
1086
  case "generation.start":
358
1087
  return {
359
- [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,
360
- ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }
1088
+ [ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
1089
+ ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
361
1090
  };
362
1091
  // `toolName` and `toolCallId` are on both tool edges, so they are not
363
1092
  // start-only and persisting them would just pad every record.
364
1093
  // The target is carried forward too: an end-only process may see a payload
365
1094
  // with less to go on (no tool input), and the start's evidence still holds.
366
1095
  case "tool.start":
367
- return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };
1096
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind, ...targetAttributes(event2) };
368
1097
  case "subagent.start":
369
- return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };
1098
+ return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event2.delegationDepth };
370
1099
  default:
371
1100
  return {};
372
1101
  }
@@ -696,22 +1425,22 @@ var createSpanCorrelator = (deps) => {
696
1425
  };
697
1426
  const correlateBatch = async (events) => {
698
1427
  const groups = /* @__PURE__ */ new Map();
699
- for (const event of events) {
700
- const ref = spanScopeRefOf(event);
1428
+ for (const event2 of events) {
1429
+ const ref = spanScopeRefOf(event2);
701
1430
  if (ref === void 0) {
702
1431
  continue;
703
1432
  }
704
- const providerId = event.provenance.providerId;
705
- const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join("\0");
1433
+ const providerId = event2.provenance.providerId;
1434
+ const groupKey = [providerId, event2.sessionId, ref.family, ref.scopeKey].join("\0");
706
1435
  const group = groups.get(groupKey) ?? {
707
1436
  providerId,
708
- sessionId: event.sessionId,
1437
+ sessionId: event2.sessionId,
709
1438
  ref
710
1439
  };
711
- if (event.type.endsWith(".start")) {
712
- group.start = event;
1440
+ if (event2.type.endsWith(".start")) {
1441
+ group.start = event2;
713
1442
  } else {
714
- group.end = event;
1443
+ group.end = event2;
715
1444
  }
716
1445
  groups.set(groupKey, group);
717
1446
  }
@@ -763,186 +1492,6 @@ var createSpanCorrelator = (deps) => {
763
1492
  return { recordStart, recordEnd, correlateBatch, cleanup };
764
1493
  };
765
1494
 
766
- // src/model/usage.ts
767
- import { z as z2 } from "zod";
768
- var usageTemporalitySchema = z2.enum(["delta", "cumulative"]);
769
- var cacheCreationAccountingSchema = z2.enum([
770
- "included-in-input",
771
- "disjoint-from-input",
772
- "not-reported"
773
- ]);
774
- var providerTotalAgreementSchema = z2.enum(["unreported", "agrees", "disagrees"]);
775
- var usageReportSchema = z2.strictObject({
776
- temporality: usageTemporalitySchema,
777
- /** Inclusive input tokens. */
778
- inputTokens: tokenCountSchema.optional(),
779
- /** Subset of `inputTokens` served from a prompt cache. */
780
- cachedInputTokens: tokenCountSchema.optional(),
781
- /** Tokens written to a prompt cache. */
782
- cacheCreationInputTokens: tokenCountSchema.optional(),
783
- /** Required when `cacheCreationInputTokens` is present and non-zero. */
784
- cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
785
- /** Inclusive output tokens. */
786
- outputTokens: tokenCountSchema.optional(),
787
- /** Subset of `outputTokens` spent on reasoning. */
788
- reasoningOutputTokens: tokenCountSchema.optional(),
789
- /** Total exactly as the provider reported it, if it reported one. */
790
- providerTotalTokens: tokenCountSchema.optional()
791
- });
792
- var canonicalUsageSchema = z2.strictObject({
793
- temporality: usageTemporalitySchema,
794
- inputTokens: tokenCountSchema,
795
- cachedInputTokens: tokenCountSchema,
796
- cacheCreationInputTokens: tokenCountSchema,
797
- cacheCreationAccounting: cacheCreationAccountingSchema,
798
- outputTokens: tokenCountSchema,
799
- reasoningOutputTokens: tokenCountSchema,
800
- /** Derived: input tokens that were neither cache reads nor cache writes. */
801
- uncachedInputTokens: tokenCountSchema,
802
- /** Derived: canonical billable total. */
803
- totalTokens: tokenCountSchema,
804
- providerTotalTokens: tokenCountSchema.optional(),
805
- providerTotalAgreement: providerTotalAgreementSchema
806
- }).check((ctx) => {
807
- const usage = ctx.value;
808
- const push = (message) => {
809
- ctx.issues.push({ code: "custom", input: usage, message });
810
- };
811
- if (usage.cachedInputTokens > usage.inputTokens) {
812
- push("cachedInputTokens must not exceed inputTokens (it is a subset)");
813
- }
814
- if (usage.reasoningOutputTokens > usage.outputTokens) {
815
- push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
816
- }
817
- if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
818
- push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
819
- }
820
- const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
821
- if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
822
- push(
823
- "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
824
- );
825
- }
826
- const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
827
- if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
828
- push(`uncachedInputTokens must equal ${expectedUncached}`);
829
- }
830
- const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
831
- const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
832
- if (usage.totalTokens !== expectedTotal) {
833
- push(`totalTokens must equal ${expectedTotal}`);
834
- }
835
- const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
836
- if (usage.providerTotalAgreement !== expectedAgreement) {
837
- push(`providerTotalAgreement must be ${expectedAgreement}`);
838
- }
839
- });
840
- var normalizeUsage = (report) => {
841
- const parsed = usageReportSchema.safeParse(report);
842
- if (!parsed.success) {
843
- return {
844
- status: "invalid",
845
- issues: parsed.error.issues.map((issue) => ({
846
- code: "invalid-report",
847
- message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
848
- }))
849
- };
850
- }
851
- const input = parsed.data;
852
- const issues = [];
853
- const notes = [];
854
- const inputTokens = input.inputTokens ?? 0;
855
- const cachedInputTokens = input.cachedInputTokens ?? 0;
856
- const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
857
- const outputTokens = input.outputTokens ?? 0;
858
- const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
859
- let accounting;
860
- if (cacheCreationInputTokens === 0) {
861
- accounting = input.cacheCreationAccounting ?? "not-reported";
862
- if (accounting !== "not-reported") {
863
- notes.push(
864
- `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
865
- );
866
- }
867
- } else if (input.cacheCreationAccounting === void 0) {
868
- issues.push({
869
- code: "cache-creation-accounting-missing",
870
- message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
871
- });
872
- accounting = "not-reported";
873
- } else if (input.cacheCreationAccounting === "not-reported") {
874
- issues.push({
875
- code: "cache-creation-accounting-missing",
876
- message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
877
- });
878
- accounting = "not-reported";
879
- } else {
880
- accounting = input.cacheCreationAccounting;
881
- }
882
- if (cachedInputTokens > inputTokens) {
883
- issues.push({
884
- code: "cached-exceeds-input",
885
- message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
886
- });
887
- }
888
- if (reasoningOutputTokens > outputTokens) {
889
- issues.push({
890
- code: "reasoning-exceeds-output",
891
- message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
892
- });
893
- }
894
- const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
895
- if (cachedInputTokens + creationInsideInput > inputTokens) {
896
- issues.push({
897
- code: "cache-creation-exceeds-input",
898
- message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
899
- });
900
- }
901
- if (issues.length > 0) {
902
- return { status: "invalid", issues };
903
- }
904
- const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
905
- const totalTokens = inputTokens + creationOutsideInput + outputTokens;
906
- const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
907
- if (providerTotalAgreement === "disagrees") {
908
- notes.push(
909
- `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
910
- );
911
- }
912
- const usage = {
913
- temporality: input.temporality,
914
- inputTokens,
915
- cachedInputTokens,
916
- cacheCreationInputTokens,
917
- cacheCreationAccounting: accounting,
918
- outputTokens,
919
- reasoningOutputTokens,
920
- uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
921
- totalTokens,
922
- ...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
923
- providerTotalAgreement
924
- };
925
- return { status: "ok", usage, notes };
926
- };
927
- var UsageNormalizationError = class extends Error {
928
- issues;
929
- constructor(issues) {
930
- super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
931
- this.name = "UsageNormalizationError";
932
- this.issues = issues;
933
- }
934
- };
935
- var normalizeUsageOrThrow = (report) => {
936
- const result = normalizeUsage(report);
937
- if (result.status === "invalid") {
938
- throw new UsageNormalizationError(result.issues);
939
- }
940
- return result.usage;
941
- };
942
- var EMPTY_DELTA_USAGE = Object.freeze(
943
- normalizeUsageOrThrow({ temporality: "delta" })
944
- );
945
-
946
1495
  // src/lifecycle/usage-accumulator.ts
947
1496
  var EMPTY_CUMULATIVE_USAGE = normalizeUsageOrThrow({ temporality: "cumulative" });
948
1497
  var combineCumulativeWithDelta = (total, delta) => {