@osfactory/otel-hook 0.10.0 → 0.12.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 +108 -4
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
  3. package/dist/cli.js +1495 -135
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +116 -21
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-DvqsPulb.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  12. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-CI7z4n3i.d.ts} +136 -6
  13. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
  14. package/dist/{hook-BAxXoKsp.d.ts → hook-vM_cgqS2.d.ts} +11 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1496 -183
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +9 -1
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +36 -12
  22. package/dist/integration.js +1464 -231
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +279 -5
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-aJilVG4R.d.ts → memory-DdU1U91y.d.ts} +2 -2
  28. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-C9lLqqpI.d.ts} +157 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +9 -1
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-D7gc0-WQ.d.ts → payload-BT19hiVZ.d.ts} +1 -1
  33. package/dist/{ports-plO5MKrY.d.ts → ports-C3k_5eOQ.d.ts} +57 -2
  34. package/dist/providers.d.ts +10 -10
  35. package/dist/providers.js +10 -1
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-C7XO4DzD.d.ts → registry-gyJqaWmp.d.ts} +2 -2
  38. package/dist/runtime.d.ts +97 -9
  39. package/dist/runtime.js +312 -33
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-CHb3GU1r.d.ts → schema-SpFM6YQY.d.ts} +87 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +32 -1
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +929 -31
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +164 -33
  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, g as StateStore, S as StateRecord, c as LogLevel, d as Logger, i as TelemetrySink } from './ports-plO5MKrY.js';
2
- import { b as CanonicalEvent } from './events-CSD_YiJ2.js';
1
+ import { C as Clock, I as IdGenerator, j as StateStore, i as StateRecord, c as LogLevel, d as Logger, l as TelemetrySink } from './ports-C3k_5eOQ.js';
2
+ import { b as CanonicalEvent } from './events-fcomX6d5.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-CSD_YiJ2.js';
5
+ import { b as CanonicalEvent, f as CanonicalUsage } from './events-fcomX6d5.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,159 @@ 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
+ * Session context attributes (`docs/session-context.md`) are on every data point
211
+ * of an event that has them, so a new context starts a new series.
212
+ *
213
+ * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no
214
+ * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):
215
+ * an id per data point is a new series per data point. `session.id` is the one
216
+ * high-cardinality attribute, and it can be switched off.
217
+ */
218
+ /** Recommended bucket boundaries from the GenAI semantic conventions. */
219
+ declare const TOKEN_USAGE_BUCKETS: readonly number[];
220
+ declare const OPERATION_DURATION_BUCKETS: readonly number[];
221
+ declare const METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
222
+ declare const METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
223
+ declare const METRIC_SESSIONS = "otelhook.sessions";
224
+ declare const METRIC_TOOL_CALLS = "otelhook.tool.calls";
225
+ declare const METRIC_COST_USAGE = "otelhook.cost.usage";
226
+ type MetricInstrumentName = typeof METRIC_TOKEN_USAGE | typeof METRIC_OPERATION_DURATION | typeof METRIC_SESSIONS | typeof METRIC_TOOL_CALLS | typeof METRIC_COST_USAGE;
227
+ type MetricInstrument = {
228
+ readonly name: MetricInstrumentName;
229
+ readonly kind: "histogram" | "counter";
230
+ readonly unit: string;
231
+ readonly description: string;
232
+ /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */
233
+ readonly valueType: "int" | "double";
234
+ /** Histograms only. */
235
+ readonly boundaries?: readonly number[];
236
+ };
237
+ declare const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>>;
238
+ /**
239
+ * Token types on `gen_ai.client.token.usage`.
240
+ *
241
+ * `input` is inclusive of cache reads, as the GenAI conventions define
242
+ * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series
243
+ * describing parts of the input; summing every token type double-counts.
244
+ */
245
+ type TokenType = "input" | "output" | "cache_read" | "cache_creation";
246
+ type MetricsTemporality = "cumulative" | "delta";
247
+ /** One recorded value. */
248
+ type MetricObservation = {
249
+ readonly instrument: MetricInstrumentName;
250
+ readonly value: number;
251
+ /** Data-point attributes. Primitives only. */
252
+ readonly attributes: Readonly<Record<string, string | number | boolean>>;
253
+ /** When the observed thing happened, in epoch milliseconds. */
254
+ readonly timeMillis: number;
255
+ /** Provider session the observation belongs to; scopes cumulative state. */
256
+ readonly sessionId: string;
257
+ };
258
+ /** A start time recovered for a generation, by generation id. */
259
+ type GenerationStart = {
260
+ readonly startMillis: number;
261
+ readonly requestModel?: string;
262
+ };
263
+ /** The usage delta the orchestrator derived for one usage-bearing event. */
264
+ type MetricUsageInput = {
265
+ readonly eventId: string;
266
+ readonly scope: string;
267
+ readonly delta: CanonicalUsage;
268
+ };
269
+ type DeriveMetricObservationsInput = {
270
+ readonly events: readonly CanonicalEvent[];
271
+ readonly usage: readonly MetricUsageInput[];
272
+ /** The exported resource; supplies the launcher's `session.id` when it sets one. */
273
+ readonly resource: Resource;
274
+ /** Put `session.id` on every data point. Default true. */
275
+ readonly includeSessionId?: boolean;
276
+ /**
277
+ * Start times for generations whose start edge is not in this batch (it was
278
+ * recorded by an earlier hook process). Looked up by generation id.
279
+ */
280
+ readonly generationStarts?: (generationId: string) => GenerationStart | undefined;
281
+ /**
282
+ * When the session's current turn began: the last `prompt.submitted` recorded,
283
+ * by an earlier callback or this one. The fallback duration source for
284
+ * providers whose generation is a turn (Claude Code, Codex).
285
+ */
286
+ readonly turnStart?: (sessionId: string) => number | undefined;
287
+ };
288
+ /**
289
+ * Observations for one batch.
290
+ *
291
+ * - `otelhook.sessions`: one per `session.start`.
292
+ * - `otelhook.tool.calls`: one per `tool.end`.
293
+ * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is
294
+ * known, from the first source that has it:
295
+ * 1. the duration the provider stated (`durationMillis`);
296
+ * 2. a `generation.start` recorded by an *earlier* callback;
297
+ * 3. the turn's start: the last `prompt.submitted` of the session, no later than
298
+ * the end. For Claude Code and Codex a generation is a turn, so this is the
299
+ * turn's wall-clock time, tool calls included.
300
+ * A `generation.start` in the *same* batch as its end is not a start: an
301
+ * adapter that emits both from one callback (Claude Code's `Stop`) synthesized
302
+ * it, and measuring from it would record a zero.
303
+ * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token
304
+ * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that
305
+ * never reports cache tokens would otherwise fill the low bucket with zeros.
306
+ * `input` and `output` are always recorded, zero included, so the count of a
307
+ * token histogram is the number of generations with usage.
308
+ * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.
309
+ */
310
+ declare const deriveMetricObservations: (input: DeriveMetricObservationsInput) => readonly MetricObservation[];
311
+ /** Accumulated histogram state for one series. */
312
+ type HistogramState = {
313
+ readonly count: number;
314
+ readonly sum: number;
315
+ readonly min: number;
316
+ readonly max: number;
317
+ /** One more entry than the instrument's boundaries. */
318
+ readonly bucketCounts: readonly number[];
319
+ };
320
+ /**
321
+ * One OTLP data point, as plain JSON so it can be spooled.
322
+ *
323
+ * A point is self-describing: the instrument, its temporality, and its interval.
324
+ * A cumulative point is a snapshot of a running total, so resending one (from a
325
+ * spool) restates a value rather than adding to it.
326
+ */
327
+ type MetricPoint = {
328
+ readonly instrument: MetricInstrumentName;
329
+ readonly temporality: MetricsTemporality;
330
+ readonly attributes: Readonly<Record<string, string | number | boolean>>;
331
+ readonly startTimeMillis: number;
332
+ readonly timeMillis: number;
333
+ /** Counters. */
334
+ readonly value?: number;
335
+ /** Histograms. */
336
+ readonly histogram?: HistogramState;
337
+ };
338
+ /**
339
+ * Delta points for one batch: observations of the same series folded together,
340
+ * over the interval from the earliest observation to `nowMillis`.
341
+ */
342
+ declare const aggregateDeltaPoints: (observations: readonly MetricObservation[], nowMillis: number) => readonly MetricPoint[];
343
+
344
+ 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-CSD_YiJ2.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-fcomX6d5.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
@@ -832,7 +832,15 @@ var baseEventFields = {
832
832
  * factory, never by hand.
833
833
  */
834
834
  subagentId: subagentIdSchema.optional(),
835
- extensions: extensionsSchema.default(emptyExtensions)
835
+ extensions: extensionsSchema.default(emptyExtensions),
836
+ /**
837
+ * Attributes of the session context segment in force when the event
838
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
839
+ * harness wrote. Exported on every record of the event, over the same keys
840
+ * from the Resource. Absent when no context applies. Set by the core only,
841
+ * never by an adapter.
842
+ */
843
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
836
844
  };
837
845
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
838
846
  var sessionStartEventSchema = event({