@osfactory/otel-hook 0.9.0 → 0.11.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 (51) hide show
  1. package/README.md +124 -4
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-DiLknaTF.d.ts} +14 -2
  3. package/dist/cli.js +2272 -730
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +13 -4
  6. package/dist/config.js +128 -23
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C6Bm89W6.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  12. package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-QWKGGEjk.d.ts} +131 -6
  13. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  14. package/dist/{hook-zA1b4cWd.d.ts → hook-BOecWGSz.d.ts} +10 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1808 -251
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +31 -2
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +37 -12
  22. package/dist/integration.js +3271 -1551
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +277 -4
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-Bl9ANVff.d.ts → memory-Cs51jyRk.d.ts} +2 -2
  28. package/dist/{semconv-fPRb-dpU.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-ChtrEX6A.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-CeqLq31i.d.ts} +87 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-B8ZHc2bc.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1404 -1219
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-BxiVsU-d.d.ts → schema-DMnoU1V_.d.ts} +93 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +630 -39
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +872 -19
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +264 -34
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +3 -1
package/README.md CHANGED
@@ -581,6 +581,79 @@ signal, because a collector with no logs receiver leaves traces perfectly health
581
581
  The full mapping table, attribute vocabulary, bounds, and durability matrix are in
582
582
  [docs/canonical-log-mapping.md](docs/canonical-log-mapping.md).
583
583
 
584
+ ## Metrics
585
+
586
+ otel-hook can also send OpenTelemetry **metrics**, derived from the hook events it
587
+ already normalizes. They work for every supported provider, not only the ones with
588
+ native telemetry, and they go through the same destinations and spools as traces.
589
+
590
+ **Off by default.** Turn them on for the `default` destination with `--metrics`
591
+ (or `exporter.metrics.enabled` in a config file, or `OTEL_HOOK_METRICS_ENABLED=1`).
592
+ A `destinations[]` entry receives them only when its `signals` list names
593
+ `metrics`. A destination that lists only `traces` never receives a metric.
594
+
595
+ ```bash
596
+ otel-hook run --provider codex --endpoint http://localhost:4318/v1/traces --metrics
597
+ # metrics go to http://localhost:4318/v1/metrics
598
+ ```
599
+
600
+ | Metric | Type | Unit | Recorded |
601
+ | --- | --- | --- | --- |
602
+ | `gen_ai.client.token.usage` | histogram | `{token}` | Once per generation with usage, per `gen_ai.token.type`: `input`, `output`, `cache_read`, `cache_creation` |
603
+ | `gen_ai.client.operation.duration` | histogram | `s` | Once per generation whose duration is known (see below) |
604
+ | `otelhook.sessions` | counter | `{session}` | Once per `session.start` |
605
+ | `otelhook.tool.calls` | counter | `{call}` | Once per completed tool call, by `gen_ai.tool.name` and `otelhook.outcome` |
606
+ | `otelhook.cost.usage` | counter | `USD` | Only when the provider reports a cost. Never estimated |
607
+
608
+ Data-point attributes: `otelhook.provider.id` (the agent), `gen_ai.operation.name`,
609
+ `gen_ai.provider.name` (the model vendor, when known), `gen_ai.request.model`,
610
+ `gen_ai.response.model`, and `session.id` (the launcher's key when it sets one, like
611
+ spans). The resource is the same as for traces. Metrics carry **no** account
612
+ identity (`user.*`, `enduser.*` and `organization.*` keys are stripped, even from the
613
+ resource), no content, and no per-event ids.
614
+
615
+ - **Tokens.** `input` includes cache reads, as in the GenAI conventions, and
616
+ `cache_read` and `cache_creation` describe parts of it. Do not add the token types
617
+ together. A provider that reports a running total (Codex) is diffed against the
618
+ previous turn first, exactly as usage accounting does, so a session is never
619
+ counted twice.
620
+ - **Duration.** The first source that has it: the duration the provider states, a
621
+ `generation.start` recorded by an earlier hook, or the time the turn's prompt was
622
+ submitted. For Claude Code and Codex a generation is a turn, so this is the
623
+ turn's wall-clock time, tool calls included. A start the adapter made in the same
624
+ callback as the end is not used: it would record zero.
625
+ - **Temporality.** `cumulative` by default: each series' running total is kept in
626
+ the state directory, so a later hook process continues it, and receivers that
627
+ merge counters by keeping the largest value stay correct. Set
628
+ `exporter.metrics.temporality` to `delta` (or `--metrics-temporality delta`, or
629
+ `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta`) to send what each
630
+ callback observed and keep no state.
631
+ - **Cardinality.** `session.id` makes one series per session. Leave it off with
632
+ `exporter.metrics.includeSessionId: false` or `--no-metrics-session-id`.
633
+ - **Delivery.** Points are sent once, right after the callback's traces and logs,
634
+ inside the same bounded flush. There is no periodic reader, because a hook process
635
+ lives for one callback. What a destination refuses is kept in that destination's
636
+ `spool-metrics` queue and replayed by the next hook. Replaying a cumulative point
637
+ restates a total; it does not add to it.
638
+ - **Exactly once.** A redelivered callback, or one whose traces were lost and will be
639
+ retried, records nothing. A callback replayed after a crash restates its series'
640
+ totals instead of adding to them.
641
+
642
+ These numbers are **hook-derived**. They can differ from a provider's own
643
+ telemetry: for example, Claude Code's native `claude_code.token.usage` counts
644
+ subagent spend that hooks do not see yet (#68). A harness that already books Claude
645
+ Code usage from native telemetry should not add both.
646
+
647
+ | Field | Default | Flag | Variable |
648
+ | --- | --- | --- | --- |
649
+ | `exporter.metrics.enabled` | `false` | `--metrics` / `--no-metrics` | `OTEL_HOOK_METRICS_ENABLED` |
650
+ | `exporter.metrics.endpoint` | derived from `endpoint` (`/v1/traces` → `/v1/metrics`) | `--metrics-endpoint` | `OTEL_HOOK_METRICS_ENDPOINT`, then `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, then `OTEL_EXPORTER_OTLP_ENDPOINT` |
651
+ | `exporter.metrics.temporality` | `cumulative` | `--metrics-temporality` | `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` (`lowmemory` reads as `delta`) |
652
+ | `exporter.metrics.includeSessionId` | `true` | `--no-metrics-session-id` | — |
653
+
654
+ Claude Code does not pass `OTEL_*` variables to hook processes, so under Claude Code
655
+ use the flags or a config file.
656
+
584
657
  ## Privacy
585
658
 
586
659
  Content is omitted by default; only lengths and a stable salted hash are
@@ -696,6 +769,12 @@ set (and not blank) wins:
696
769
  | logs | `OTEL_EXPORTER_OTLP_ENDPOINT` | base URL; `/v1/logs` is appended (see below) |
697
770
  | logs | `exporter.logs.endpoint` in a config file | full logs URL |
698
771
  | logs | derived from the resolved traces endpoint | `/v1/traces` swapped for `/v1/logs`, or `/v1/logs` appended |
772
+ | metrics | `--metrics-endpoint` | full metrics URL |
773
+ | metrics | `OTEL_HOOK_METRICS_ENDPOINT` | full metrics URL |
774
+ | metrics | `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | full metrics URL, used as-is |
775
+ | metrics | `OTEL_EXPORTER_OTLP_ENDPOINT` | base URL; `/v1/metrics` is appended (same rule as logs) |
776
+ | metrics | `exporter.metrics.endpoint` in a config file | full metrics URL |
777
+ | metrics | derived from the resolved traces endpoint | `/v1/traces` swapped for `/v1/metrics`, or `/v1/metrics` appended |
699
778
 
700
779
  `OTEL_EXPORTER_OTLP_ENDPOINT` follows the OpenTelemetry exporter
701
780
  specification: it is a **base** URL, and the signal path is appended to it.
@@ -822,6 +901,43 @@ export OTEL_RESOURCE_ATTRIBUTES="session.id=run-2041,factory.work_unit.id=wu-42,
822
901
  - Langfuse filters on span attributes, which is why `factory.*` and `vcs.*` are
823
902
  [copied onto every span](#on-records-too); `factory.local.*` is not.
824
903
 
904
+ #### Claude Code: model and token usage
905
+
906
+ Claude Code's `Stop` hook names no model and carries no tokens. Out of the box,
907
+ each generation span carries the session's model, which `SessionStart` reports
908
+ and the state store remembers (so `--state-dir`, or the default durable store,
909
+ matters).
910
+
911
+ For the exact per-turn model and the turn's summed token usage, turn on the
912
+ opt-in setting. otel-hook then reads the session transcript the payload names,
913
+ from where the previous turn ended, and sums every model request of the turn:
914
+
915
+ ```bash
916
+ otel-hook run --provider claude-code --claude-transcript-usage
917
+ # or: OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
918
+ # or, in --config-file: { "providers": { "claudeCode": { "readTranscriptUsage": true } } }
919
+ ```
920
+
921
+ This is the one sanctioned exception to "no transcript reads in the hook": off by
922
+ default, done by the hook runtime and never by the adapter (ADR 0003), limited to
923
+ the one `.jsonl` file the payload names, capped at 8 MiB per turn and 500 ms, and
924
+ fail-open. When a turn cannot be summed exactly (no `SessionStart` was seen, the
925
+ state was lost, the turn wrote more than the cap), the last request is reported
926
+ instead and the span says so with `otelhook.usage.partial=true`.
927
+
928
+ A harness that wants to attach usage itself can call the library helper, which
929
+ reports the last request only (`usage_partial: true`):
930
+
931
+ ```ts
932
+ import { attachClaudeTranscriptTurn } from "@osfactory/otel-hook";
933
+
934
+ // Bounded: last 1 MiB of transcript_path, 250 ms, never throws, never
935
+ // overwrites a field the payload already has. Non-stop payloads pass through.
936
+ const enriched = await attachClaudeTranscriptTurn(hookPayload);
937
+ ```
938
+
939
+ See [finding 8](docs/claude-code-usage-contract.md#finding-8-the-model-is-on-sessionstart-and-in-the-transcript-never-on-stop).
940
+
825
941
  ### Multiple destinations
826
942
 
827
943
  `exporter.destinations` sends every batch to several OTLP endpoints at once — a
@@ -867,10 +983,10 @@ Each destination takes:
867
983
  | --- | --- | --- |
868
984
  | `name` | — | Unique; lowercase letters, digits, `_` and `-`. Also its spool directory. `default` is reserved. |
869
985
  | `endpoint` | — | Traces URL, as `exporter.endpoint`. The logs URL is derived from it (`/v1/traces` → `/v1/logs`). |
870
- | `tracesEndpoint`, `logsEndpoint` | — | Per-signal URLs, overriding `endpoint`. At least one of the three is required. |
986
+ | `tracesEndpoint`, `logsEndpoint`, `metricsEndpoint` | — | Per-signal URLs, overriding `endpoint`. At least one of the four is required. |
871
987
  | `protocol` | `exporter.protocol` | `http/protobuf` is the protocol this build sends. |
872
988
  | `headers` | `{}` | Header name → value. `"env:NAME"` reads the value from that environment variable when sending. |
873
- | `signals` | `["traces", "logs"]` | Which signals it receives. Logs still need `exporter.logs.enabled`. |
989
+ | `signals` | `["traces", "logs"]` | Which signals it receives: `traces`, `logs`, `metrics`. Logs still need `exporter.logs.enabled`. Metrics are sent only when listed (see [Metrics](#metrics)). |
874
990
  | `enabled` | `true` | `false` keeps the entry but neither sends to it nor drains its spool. |
875
991
 
876
992
  Everything else — timeout, batch sizes, service identity, resource attributes,
@@ -913,7 +1029,7 @@ committed — retrying it would duplicate spans at the destinations that accepte
913
1029
 
914
1030
  **Spools are per destination and bounded.** Every destination queues under
915
1031
  `<state-dir>/<provider>/<installation>/destinations/<name>/` (`default` keeps the
916
- original `spool` and `spool-logs` directories), and each spool is drained at the
1032
+ original `spool`, `spool-logs` and `spool-metrics` directories), and each spool is drained at the
917
1033
  end of the next hook event. Bounds apply per destination and per signal, and can
918
1034
  be set under `exporter.spool`:
919
1035
 
@@ -1166,7 +1282,11 @@ fixing one means updating that test rather than discovering a silent change.
1166
1282
  `usage.cache_read_input_tokens` and `usage.cache_creation_input_tokens` (whose
1167
1283
  TTL split is a breakdown, reconciled and never added). No hook callback carries
1168
1284
  a token counter at all, so `usage` is read only when a wrapping harness
1169
- attaches it. A harness that attaches an excluded counter anyway is told which
1285
+ attaches it, or the host turns on `providers.claudeCode.readTranscriptUsage`
1286
+ (`--claude-transcript-usage`), which makes the hook runtime sum each turn from
1287
+ `transcript_path`; the adapter itself never reads the transcript. Without it, generations
1288
+ still carry the session's model from `SessionStart`, remembered in the state
1289
+ store. A harness that attaches an excluded counter anyway is told which
1170
1290
  field was declined. `ADAPTER-NOTE-001`; see
1171
1291
  [docs/claude-code-usage-contract.md](docs/claude-code-usage-contract.md).
1172
1292
  6. **`contextTokensBefore` is an explicit exclusion for Claude Code.** Neither
@@ -1,11 +1,11 @@
1
1
  import { z } from 'zod';
2
2
  import { OtelHookErrorInfo } from './errors.js';
3
- import { I as UsageTemporality, b as CanonicalEvent, u as TargetHint, e as CanonicalEventType } from './events-B3MHoJTD.js';
3
+ import { I as UsageTemporality, n as ModelDescriptor, b as CanonicalEvent, u as TargetHint, e as CanonicalEventType } from './events-CSD_YiJ2.js';
4
4
  import { I as IdentityClaim, d as InvocationIdentity } from './identity-BrVBs901.js';
5
5
  import { R as ResolvedProviderId, g as ProviderId, h as SourceTransport, d as EventId } from './primitives-CJ8-rn-f.js';
6
6
  import { e as PrivacyLimits } from './policy-CimmCfRp.js';
7
7
  import { P as PrivacyService } from './service-CbI9CObT.js';
8
- import { C as Clock, I as IdGenerator, d as Logger } from './ports-n7KFOpKo.js';
8
+ import { C as Clock, I as IdGenerator, d as Logger } from './ports-CeqLq31i.js';
9
9
  import { A as AttributionOutcome, a as AttributionReason } from './taxonomy-DwhTtuWd.js';
10
10
 
11
11
  /** Raw input offered to adapters. `payload` is `unknown` on purpose. */
@@ -185,6 +185,18 @@ type ProviderParseInput = ProviderDetectionInput & {
185
185
  * consecutively from here so event ids stay stable across replays.
186
186
  */
187
187
  readonly sequenceBase: number;
188
+ /**
189
+ * The model this session last reported, as the core remembers it across
190
+ * invocations (`session.start` or a `generation.*` edge with a known model).
191
+ *
192
+ * Read from the state store by the core and handed in, because an adapter must
193
+ * not hold cross-invocation state itself (ADR 0006). Absent when no earlier
194
+ * invocation of this session named a model, or when the store is unreadable.
195
+ * An adapter whose generation callbacks carry no model id (Claude Code's
196
+ * `Stop`) uses it instead of the `unknown` sentinel; one whose callbacks carry
197
+ * their own model can ignore it.
198
+ */
199
+ readonly sessionModel?: ModelDescriptor;
188
200
  };
189
201
  type ProviderParseResult = {
190
202
  readonly status: "parsed";