@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
@@ -1,5 +1,5 @@
1
- import { C as Clock, I as IdGenerator, e as StateStore, S as StateRecord, c as LogLevel, d as Logger, g as TelemetrySink } from './ports-n7KFOpKo.js';
2
- import { b as CanonicalEvent } from './events-B3MHoJTD.js';
1
+ import { C as Clock, I as IdGenerator, g as StateStore, S as StateRecord, c as LogLevel, d as Logger, i as TelemetrySink } from './ports-CeqLq31i.js';
2
+ import { b as CanonicalEvent } from './events-CSD_YiJ2.js';
3
3
  import { b as Attributes } from './primitives-CJ8-rn-f.js';
4
4
 
5
5
  /** Clock backed by the host process. */
@@ -2,7 +2,7 @@ import { Attributes } from '@opentelemetry/api';
2
2
  import { InstrumentationScope } from '@opentelemetry/core';
3
3
  import { Resource } from '@opentelemetry/resources';
4
4
  import { ReadableSpan } from '@opentelemetry/sdk-trace';
5
- import { b as CanonicalEvent } from './events-B3MHoJTD.js';
5
+ import { b as CanonicalEvent, f as CanonicalUsage } from './events-CSD_YiJ2.js';
6
6
 
7
7
  declare const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope;
8
8
  /** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */
@@ -186,4 +186,156 @@ declare const canonicalEventTraceIdentities: (events: readonly CanonicalEvent[],
186
186
  /** Maps one invocation's canonical event batch into OTLP-ready spans. */
187
187
  declare const canonicalEventsToReadableSpans: (events: readonly CanonicalEvent[], options: SemanticMappingOptions) => readonly ReadableSpan[];
188
188
 
189
- export { DEFAULT_INSTRUMENTATION_SCOPE as D, type EventTraceIdentity as E, MAX_RECOVERED_START_ATTRIBUTES as M, type SemanticMappingOptions as S, type SpanCorrelation as a, type SpanCorrelationResolver as b, type SpanDisposition as c, type SpanFamily as d, type SpanOrphanClassification as e, type SpanPairing as f, type SpanScopeRef as g, canonicalEventTraceIdentities as h, canonicalEventsToReadableSpans as i, startOnlySpanAttributes as j, parentScopeRefOf as p, spanScopeRefOf as s };
189
+ /**
190
+ * Metrics derived from hook events (issue #69).
191
+ *
192
+ * otel-hook already normalizes every provider's hook callbacks into canonical
193
+ * events; this module turns one batch of those events into *observations* — a
194
+ * value recorded against an instrument, with attributes. It is pure: it reads no
195
+ * state and sends nothing. Aggregating observations into OTLP data points
196
+ * (cumulative across processes, or delta per batch) and exporting them are the
197
+ * jobs of `lifecycle/metric-series.ts` and `otlp-metric-sink.ts`.
198
+ *
199
+ * ## Why observations come from the runtime's accounting, not from the events alone
200
+ *
201
+ * Token usage is taken from the orchestrator's `UsageObservation` deltas rather than
202
+ * from `generation.end.usage` directly. A provider that reports a session-wide
203
+ * running total (Codex) stamps the *cumulative* figure on every turn; summing those
204
+ * into a histogram would bill a three-turn session several times over. The
205
+ * orchestrator already diffs them against a persisted baseline, exactly once per
206
+ * delivery, so the metric reuses that answer.
207
+ *
208
+ * ## What is never on a metric
209
+ *
210
+ * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no
211
+ * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):
212
+ * an id per data point is a new series per data point. `session.id` is the one
213
+ * high-cardinality attribute, and it can be switched off.
214
+ */
215
+ /** Recommended bucket boundaries from the GenAI semantic conventions. */
216
+ declare const TOKEN_USAGE_BUCKETS: readonly number[];
217
+ declare const OPERATION_DURATION_BUCKETS: readonly number[];
218
+ declare const METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
219
+ declare const METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
220
+ declare const METRIC_SESSIONS = "otelhook.sessions";
221
+ declare const METRIC_TOOL_CALLS = "otelhook.tool.calls";
222
+ declare const METRIC_COST_USAGE = "otelhook.cost.usage";
223
+ type MetricInstrumentName = typeof METRIC_TOKEN_USAGE | typeof METRIC_OPERATION_DURATION | typeof METRIC_SESSIONS | typeof METRIC_TOOL_CALLS | typeof METRIC_COST_USAGE;
224
+ type MetricInstrument = {
225
+ readonly name: MetricInstrumentName;
226
+ readonly kind: "histogram" | "counter";
227
+ readonly unit: string;
228
+ readonly description: string;
229
+ /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */
230
+ readonly valueType: "int" | "double";
231
+ /** Histograms only. */
232
+ readonly boundaries?: readonly number[];
233
+ };
234
+ declare const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>>;
235
+ /**
236
+ * Token types on `gen_ai.client.token.usage`.
237
+ *
238
+ * `input` is inclusive of cache reads, as the GenAI conventions define
239
+ * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series
240
+ * describing parts of the input; summing every token type double-counts.
241
+ */
242
+ type TokenType = "input" | "output" | "cache_read" | "cache_creation";
243
+ type MetricsTemporality = "cumulative" | "delta";
244
+ /** One recorded value. */
245
+ type MetricObservation = {
246
+ readonly instrument: MetricInstrumentName;
247
+ readonly value: number;
248
+ /** Data-point attributes. Primitives only. */
249
+ readonly attributes: Readonly<Record<string, string | number | boolean>>;
250
+ /** When the observed thing happened, in epoch milliseconds. */
251
+ readonly timeMillis: number;
252
+ /** Provider session the observation belongs to; scopes cumulative state. */
253
+ readonly sessionId: string;
254
+ };
255
+ /** A start time recovered for a generation, by generation id. */
256
+ type GenerationStart = {
257
+ readonly startMillis: number;
258
+ readonly requestModel?: string;
259
+ };
260
+ /** The usage delta the orchestrator derived for one usage-bearing event. */
261
+ type MetricUsageInput = {
262
+ readonly eventId: string;
263
+ readonly scope: string;
264
+ readonly delta: CanonicalUsage;
265
+ };
266
+ type DeriveMetricObservationsInput = {
267
+ readonly events: readonly CanonicalEvent[];
268
+ readonly usage: readonly MetricUsageInput[];
269
+ /** The exported resource; supplies the launcher's `session.id` when it sets one. */
270
+ readonly resource: Resource;
271
+ /** Put `session.id` on every data point. Default true. */
272
+ readonly includeSessionId?: boolean;
273
+ /**
274
+ * Start times for generations whose start edge is not in this batch (it was
275
+ * recorded by an earlier hook process). Looked up by generation id.
276
+ */
277
+ readonly generationStarts?: (generationId: string) => GenerationStart | undefined;
278
+ /**
279
+ * When the session's current turn began: the last `prompt.submitted` recorded,
280
+ * by an earlier callback or this one. The fallback duration source for
281
+ * providers whose generation is a turn (Claude Code, Codex).
282
+ */
283
+ readonly turnStart?: (sessionId: string) => number | undefined;
284
+ };
285
+ /**
286
+ * Observations for one batch.
287
+ *
288
+ * - `otelhook.sessions`: one per `session.start`.
289
+ * - `otelhook.tool.calls`: one per `tool.end`.
290
+ * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is
291
+ * known, from the first source that has it:
292
+ * 1. the duration the provider stated (`durationMillis`);
293
+ * 2. a `generation.start` recorded by an *earlier* callback;
294
+ * 3. the turn's start: the last `prompt.submitted` of the session, no later than
295
+ * the end. For Claude Code and Codex a generation is a turn, so this is the
296
+ * turn's wall-clock time, tool calls included.
297
+ * A `generation.start` in the *same* batch as its end is not a start: an
298
+ * adapter that emits both from one callback (Claude Code's `Stop`) synthesized
299
+ * it, and measuring from it would record a zero.
300
+ * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token
301
+ * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that
302
+ * never reports cache tokens would otherwise fill the low bucket with zeros.
303
+ * `input` and `output` are always recorded, zero included, so the count of a
304
+ * token histogram is the number of generations with usage.
305
+ * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.
306
+ */
307
+ declare const deriveMetricObservations: (input: DeriveMetricObservationsInput) => readonly MetricObservation[];
308
+ /** Accumulated histogram state for one series. */
309
+ type HistogramState = {
310
+ readonly count: number;
311
+ readonly sum: number;
312
+ readonly min: number;
313
+ readonly max: number;
314
+ /** One more entry than the instrument's boundaries. */
315
+ readonly bucketCounts: readonly number[];
316
+ };
317
+ /**
318
+ * One OTLP data point, as plain JSON so it can be spooled.
319
+ *
320
+ * A point is self-describing: the instrument, its temporality, and its interval.
321
+ * A cumulative point is a snapshot of a running total, so resending one (from a
322
+ * spool) restates a value rather than adding to it.
323
+ */
324
+ type MetricPoint = {
325
+ readonly instrument: MetricInstrumentName;
326
+ readonly temporality: MetricsTemporality;
327
+ readonly attributes: Readonly<Record<string, string | number | boolean>>;
328
+ readonly startTimeMillis: number;
329
+ readonly timeMillis: number;
330
+ /** Counters. */
331
+ readonly value?: number;
332
+ /** Histograms. */
333
+ readonly histogram?: HistogramState;
334
+ };
335
+ /**
336
+ * Delta points for one batch: observations of the same series folded together,
337
+ * over the interval from the earliest observation to `nowMillis`.
338
+ */
339
+ declare const aggregateDeltaPoints: (observations: readonly MetricObservation[], nowMillis: number) => readonly MetricPoint[];
340
+
341
+ export { startOnlySpanAttributes as A, DEFAULT_INSTRUMENTATION_SCOPE as D, type EventTraceIdentity as E, MAX_RECOVERED_START_ATTRIBUTES as M, OPERATION_DURATION_BUCKETS as O, type SemanticMappingOptions as S, TOKEN_USAGE_BUCKETS as T, type DeriveMetricObservationsInput as a, METRIC_COST_USAGE as b, METRIC_INSTRUMENTS as c, METRIC_OPERATION_DURATION as d, METRIC_SESSIONS as e, METRIC_TOKEN_USAGE as f, METRIC_TOOL_CALLS as g, type MetricInstrument as h, type MetricInstrumentName as i, type MetricObservation as j, type MetricPoint as k, type MetricsTemporality as l, type SpanCorrelation as m, type SpanCorrelationResolver as n, type SpanDisposition as o, type SpanFamily as p, type SpanOrphanClassification as q, type SpanPairing as r, type SpanScopeRef as s, type TokenType as t, aggregateDeltaPoints as u, canonicalEventTraceIdentities as v, canonicalEventsToReadableSpans as w, deriveMetricObservations as x, parentScopeRefOf as y, spanScopeRefOf as z };
package/dist/model.d.ts CHANGED
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { a as AttributeValue } from './primitives-CJ8-rn-f.js';
3
3
  export { A as AttributePrimitive, b as Attributes, D as DETECTION_CONFIDENCE_RANK, c as DetectionConfidence, E as EpochMillis, d as EventId, I as InvocationId, M as MAX_ATTRIBUTE_ARRAY_LENGTH, e as MAX_ATTRIBUTE_STRING_LENGTH, f as MAX_IDENTIFIER_LENGTH, P as PROVIDER_ID_PATTERN, g as ProviderId, R as ResolvedProviderId, S as SessionId, h as SourceTransport, U as UNKNOWN_PROVIDER_ID, i as UnknownProviderId, W as WORKSPACE_ID_PATTERN, j as WorkspaceId, k as attributePrimitiveSchema, l as attributeValueSchema, m as attributesSchema, n as compareDetectionConfidence, o as detectionConfidenceSchema, p as durationMillisSchema, q as epochMillisSchema, r as eventIdSchema, s as invocationIdSchema, t as isUnknownProvider, u as nonEmptyStringSchema, v as providerIdSchema, w as resolvedProviderIdSchema, x as sequenceNumberSchema, y as sessionIdSchema, z as sourceTransportSchema, B as tokenCountSchema, C as workspaceIdSchema } from './primitives-CJ8-rn-f.js';
4
4
  export { C as CONTENT_HASH_PATTERN, a as ContentDisclosure, b as ContentFact, c as ContentKind, d as ContentRole, e as contentDisclosureSchema, f as contentFactSchema, g as contentFactsSchema, h as contentKindSchema, i as contentRoleSchema, j as isContentFactConsistent, k as isUnavailableContentFact } from './content-M9xIKG7h.js';
5
- export { C as CANONICAL_EVENT_TYPES, a as CacheCreationAccounting, b as CanonicalEvent, c as CanonicalEventInput, d as CanonicalEventOfType, e as CanonicalEventType, f as CanonicalUsage, g as CompactionPerformedEvent, h as CostFacts, E as EMPTY_DELTA_USAGE, i as ErrorRaisedEvent, j as EventOutcome, k as EventValidationResult, G as GenerationEndEvent, l as GenerationStartEvent, M as MAX_TARGET_HINT_PATHS, m as MAX_TARGET_PATH_LENGTH, n as ModelDescriptor, P as PromptSubmittedEvent, o as ProviderTotalAgreement, S as SUBAGENT_ID_PATTERN, p as SessionEndEvent, q as SessionStartEvent, r as SubagentEndEvent, s as SubagentId, t as SubagentStartEvent, T as TARGETED_EVENT_TYPES, u as TargetHint, v as TargetSource, w as TargetedEvent, x as TargetedEventType, y as ToolEndEvent, z as ToolKind, A as ToolStartEvent, U as UsageDeltaResult, B as UsageNormalizationError, D as UsageNormalizationIssue, F as UsageNormalizationResult, H as UsageReport, I as UsageTemporality, W as WorkspaceTarget, J as WorktreeKind, K as addUsage, L as cacheCreationAccountingSchema, N as canonicalEventSchema, O as canonicalEventTypeSchema, Q as canonicalUsageSchema, R as compactionPerformedEventSchema, V as compareEvents, X as costFactsSchema, Y as cumulativeToDelta, Z as errorRaisedEventSchema, _ as eventUsage, $ as generationEndEventSchema, a0 as generationStartEventSchema, a1 as isTargetedEvent, a2 as modelDescriptorSchema, a3 as normalizeUsage, a4 as normalizeUsageOrThrow, a5 as parseCanonicalEvent, a6 as promptSubmittedEventSchema, a7 as providerTotalAgreementSchema, a8 as sessionCwdHint, a9 as sessionEndEventSchema, aa as sessionStartEventSchema, ab as subagentEndEventSchema, ac as subagentIdSchema, ad as subagentStartEventSchema, ae as targetHintSchema, af as targetSourceSchema, ag as toReport, ah as toolEndEventSchema, ai as toolKindSchema, aj as toolStartEventSchema, ak as usageReportSchema, al as usageTemporalitySchema, am as validateCanonicalEvent, an as workspaceTargetSchema, ao as worktreeKindSchema } from './events-B3MHoJTD.js';
5
+ export { C as CANONICAL_EVENT_TYPES, a as CacheCreationAccounting, b as CanonicalEvent, c as CanonicalEventInput, d as CanonicalEventOfType, e as CanonicalEventType, f as CanonicalUsage, g as CompactionPerformedEvent, h as CostFacts, E as EMPTY_DELTA_USAGE, i as ErrorRaisedEvent, j as EventOutcome, k as EventValidationResult, G as GenerationEndEvent, l as GenerationStartEvent, M as MAX_TARGET_HINT_PATHS, m as MAX_TARGET_PATH_LENGTH, n as ModelDescriptor, P as PromptSubmittedEvent, o as ProviderTotalAgreement, S as SUBAGENT_ID_PATTERN, p as SessionEndEvent, q as SessionStartEvent, r as SubagentEndEvent, s as SubagentId, t as SubagentStartEvent, T as TARGETED_EVENT_TYPES, u as TargetHint, v as TargetSource, w as TargetedEvent, x as TargetedEventType, y as ToolEndEvent, z as ToolKind, A as ToolStartEvent, U as UsageDeltaResult, B as UsageNormalizationError, D as UsageNormalizationIssue, F as UsageNormalizationResult, H as UsageReport, I as UsageTemporality, W as WorkspaceTarget, J as WorktreeKind, K as addUsage, L as cacheCreationAccountingSchema, N as canonicalEventSchema, O as canonicalEventTypeSchema, Q as canonicalUsageSchema, R as compactionPerformedEventSchema, V as compareEvents, X as costFactsSchema, Y as cumulativeToDelta, Z as errorRaisedEventSchema, _ as eventUsage, $ as generationEndEventSchema, a0 as generationStartEventSchema, a1 as isTargetedEvent, a2 as modelDescriptorSchema, a3 as normalizeUsage, a4 as normalizeUsageOrThrow, a5 as parseCanonicalEvent, a6 as promptSubmittedEventSchema, a7 as providerTotalAgreementSchema, a8 as sessionCwdHint, a9 as sessionEndEventSchema, aa as sessionStartEventSchema, ab as subagentEndEventSchema, ac as subagentIdSchema, ad as subagentStartEventSchema, ae as targetHintSchema, af as targetSourceSchema, ag as toReport, ah as toolEndEventSchema, ai as toolKindSchema, aj as toolStartEventSchema, ak as usageReportSchema, al as usageTemporalitySchema, am as validateCanonicalEvent, an as workspaceTargetSchema, ao as worktreeKindSchema } from './events-CSD_YiJ2.js';
6
6
  export { C as ConsumerAttributes, I as IdentityClaim, a as IdentityClaimFields, b as IdentityConflict, c as IdentityResolution, d as InvocationIdentity, R as ResolveIdentityInput, S as SourceProvenance, U as UNKNOWN_WORKSPACE_ID, W as WorkspaceIdentity, e as WorkspaceKeySource, f as consumerAttributesSchema, i as identityClaimFieldsSchema, g as identityClaimSchema, h as invocationIdentitySchema, r as resolveInvocationIdentity, s as sourceProvenanceSchema, u as unknownWorkspaceIdentity, w as workspaceIdentitySchema, j as workspaceKeySourceSchema } from './identity-BrVBs901.js';
7
7
 
8
8
  /**
package/dist/model.js CHANGED
@@ -875,6 +875,13 @@ var generationEndEventSchema = event({
875
875
  stopReason: nonEmptyStringSchema.optional(),
876
876
  durationMillis: durationMillisSchema.optional(),
877
877
  usage: canonicalUsageSchema.optional(),
878
+ /**
879
+ * True when `usage` is known to cover only part of the generation (for
880
+ * example the last model request of a multi-request turn); false when the
881
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
882
+ * without `usage`.
883
+ */
884
+ usagePartial: z9.boolean().optional(),
878
885
  cost: costFactsSchema.optional(),
879
886
  outputContent: contentFactsSchema.optional()
880
887
  });