@osfactory/otel-hook 0.10.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 (43) hide show
  1. package/README.md +82 -3
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DiLknaTF.d.ts} +1 -1
  3. package/dist/cli.js +1131 -77
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +100 -18
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.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/{export-destinations-lORbe25J.d.ts → export-destinations-QWKGGEjk.d.ts} +130 -5
  12. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  13. package/dist/{hook-BAxXoKsp.d.ts → hook-BOecWGSz.d.ts} +4 -4
  14. package/dist/index.d.ts +14 -14
  15. package/dist/index.js +1114 -90
  16. package/dist/index.js.map +1 -1
  17. package/dist/install.d.ts +3 -3
  18. package/dist/integration.d.ts +29 -11
  19. package/dist/integration.js +1117 -154
  20. package/dist/integration.js.map +1 -1
  21. package/dist/lifecycle.d.ts +54 -3
  22. package/dist/lifecycle.js +270 -4
  23. package/dist/lifecycle.js.map +1 -1
  24. package/dist/{memory-aJilVG4R.d.ts → memory-Cs51jyRk.d.ts} +1 -1
  25. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  26. package/dist/{payload-D7gc0-WQ.d.ts → payload-ChtrEX6A.d.ts} +1 -1
  27. package/dist/{ports-plO5MKrY.d.ts → ports-CeqLq31i.d.ts} +24 -0
  28. package/dist/providers.d.ts +8 -8
  29. package/dist/{registry-C7XO4DzD.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  30. package/dist/runtime.d.ts +7 -7
  31. package/dist/runtime.js +55 -9
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-CHb3GU1r.d.ts → schema-DMnoU1V_.d.ts} +64 -1
  34. package/dist/state.d.ts +3 -3
  35. package/dist/state.js +23 -0
  36. package/dist/state.js.map +1 -1
  37. package/dist/telemetry.d.ts +5 -5
  38. package/dist/telemetry.js +860 -17
  39. package/dist/telemetry.js.map +1 -1
  40. package/dist/testing.d.ts +8 -8
  41. package/dist/testing.js +55 -9
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +3 -1
@@ -1,4 +1,4 @@
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';
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
2
  import { b as CanonicalEvent } from './events-CSD_YiJ2.js';
3
3
  import { b as Attributes } from './primitives-CJ8-rn-f.js';
4
4
 
@@ -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-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 };
@@ -1,7 +1,7 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
3
  import { g as ProviderId } from './primitives-CJ8-rn-f.js';
4
- import { d as ProviderCapabilities, P as ProviderAdapter } from './adapter-B9RwW6TO.js';
4
+ import { d as ProviderCapabilities, P as ProviderAdapter } from './adapter-DiLknaTF.js';
5
5
 
6
6
  /** Stable, hyphenated provider id for Claude Code. */
7
7
  declare const CLAUDE_CODE_PROVIDER_ID: string & zod.$brand<"ProviderId">;
@@ -107,6 +107,18 @@ declare const stateValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
107
107
  vendor: z.ZodOptional<z.ZodString>;
108
108
  family: z.ZodOptional<z.ZodString>;
109
109
  }, z.core.$strict>;
110
+ }, z.core.$strict>, z.ZodObject<{
111
+ kind: z.ZodLiteral<"metric-series">;
112
+ startTimeMillis: z.ZodNumber;
113
+ value: z.ZodOptional<z.ZodNumber>;
114
+ histogram: z.ZodOptional<z.ZodObject<{
115
+ count: z.ZodNumber;
116
+ sum: z.ZodNumber;
117
+ min: z.ZodNumber;
118
+ max: z.ZodNumber;
119
+ bucketCounts: z.ZodArray<z.ZodNumber>;
120
+ }, z.core.$strict>>;
121
+ appliedDelivery: z.ZodOptional<z.ZodString>;
110
122
  }, z.core.$strict>, z.ZodObject<{
111
123
  kind: z.ZodLiteral<"read-cursor">;
112
124
  source: z.ZodString;
@@ -159,6 +171,18 @@ declare const stateRecordSchema: z.ZodObject<{
159
171
  vendor: z.ZodOptional<z.ZodString>;
160
172
  family: z.ZodOptional<z.ZodString>;
161
173
  }, z.core.$strict>;
174
+ }, z.core.$strict>, z.ZodObject<{
175
+ kind: z.ZodLiteral<"metric-series">;
176
+ startTimeMillis: z.ZodNumber;
177
+ value: z.ZodOptional<z.ZodNumber>;
178
+ histogram: z.ZodOptional<z.ZodObject<{
179
+ count: z.ZodNumber;
180
+ sum: z.ZodNumber;
181
+ min: z.ZodNumber;
182
+ max: z.ZodNumber;
183
+ bucketCounts: z.ZodArray<z.ZodNumber>;
184
+ }, z.core.$strict>>;
185
+ appliedDelivery: z.ZodOptional<z.ZodString>;
162
186
  }, z.core.$strict>, z.ZodObject<{
163
187
  kind: z.ZodLiteral<"read-cursor">;
164
188
  source: z.ZodString;
@@ -1,20 +1,20 @@
1
- import { e as ProviderContext, P as ProviderAdapter, d as ProviderCapabilities, b as DeliveryIdentifierSupport, A as AdapterDescription } from './adapter-B9RwW6TO.js';
2
- export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as MAX_DELIVERY_COMPONENTS, c as MAX_DELIVERY_GAPS, f as ProviderDeliveryClaim, g as ProviderDeliveryGaps, h as ProviderDetection, i as ProviderDetectionInput, j as ProviderHookResponse, k as ProviderHookResponseInput, l as ProviderIdentityInput, m as ProviderParseInput, n as ProviderParseResult, S as SILENT_HOOK_RESPONSE, o as adapterSupports, p as asProviderId, q as deliveryComponentSchema, r as deliveryGapReasonSchema, s as deliveryIdentifierSupportSchema, t as describeAdapter, u as providerCapabilitiesSchema, v as providerDeliveryClaimSchema, w as providerDeliveryGapsSchema, x as providerDetectionSchema, y as providerHookResponseSchema, z as readDeliveryClaim, B as readDeliveryGap, C as unknownDetection } from './adapter-B9RwW6TO.js';
1
+ import { e as ProviderContext, P as ProviderAdapter, d as ProviderCapabilities, b as DeliveryIdentifierSupport, A as AdapterDescription } from './adapter-DiLknaTF.js';
2
+ export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as MAX_DELIVERY_COMPONENTS, c as MAX_DELIVERY_GAPS, f as ProviderDeliveryClaim, g as ProviderDeliveryGaps, h as ProviderDetection, i as ProviderDetectionInput, j as ProviderHookResponse, k as ProviderHookResponseInput, l as ProviderIdentityInput, m as ProviderParseInput, n as ProviderParseResult, S as SILENT_HOOK_RESPONSE, o as adapterSupports, p as asProviderId, q as deliveryComponentSchema, r as deliveryGapReasonSchema, s as deliveryIdentifierSupportSchema, t as describeAdapter, u as providerCapabilitiesSchema, v as providerDeliveryClaimSchema, w as providerDeliveryGapsSchema, x as providerDetectionSchema, y as providerHookResponseSchema, z as readDeliveryClaim, B as readDeliveryGap, C as unknownDetection } from './adapter-DiLknaTF.js';
3
3
  import { b as CanonicalEvent, u as TargetHint, q as SessionStartEvent, p as SessionEndEvent, P as PromptSubmittedEvent, l as GenerationStartEvent, G as GenerationEndEvent, A as ToolStartEvent, y as ToolEndEvent, t as SubagentStartEvent, r as SubagentEndEvent, g as CompactionPerformedEvent, i as ErrorRaisedEvent } from './events-CSD_YiJ2.js';
4
4
  import { d as InvocationIdentity } from './identity-BrVBs901.js';
5
5
  import { d as EventId } from './primitives-CJ8-rn-f.js';
6
- import { P as ProviderRegistry } from './registry-C7XO4DzD.js';
7
- export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-C7XO4DzD.js';
8
- import { v as ClaudeUsage } from './payload-D7gc0-WQ.js';
9
- export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-D7gc0-WQ.js';
10
- import { P as PayloadEnricher } from './ports-plO5MKrY.js';
6
+ import { P as ProviderRegistry } from './registry-CcJNF3WY.js';
7
+ export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-CcJNF3WY.js';
8
+ import { v as ClaudeUsage } from './payload-ChtrEX6A.js';
9
+ export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-ChtrEX6A.js';
10
+ import { P as PayloadEnricher } from './ports-CeqLq31i.js';
11
11
  import 'zod';
12
12
  import './errors.js';
13
13
  import './taxonomy-DwhTtuWd.js';
14
14
  import './policy-CimmCfRp.js';
15
15
  import './content-M9xIKG7h.js';
16
16
  import './service-CbI9CObT.js';
17
- import './schema-CHb3GU1r.js';
17
+ import './schema-DMnoU1V_.js';
18
18
 
19
19
  /** Fields the factory supplies; an adapter never sets them itself. */
20
20
  type ManagedFields = "schemaVersion" | "eventId" | "invocationId" | "sessionId" | "sequence" | "provenance" | "workspace" | "extensions" | "subagentId" | "target" | "occurredAt";
@@ -1,6 +1,6 @@
1
- import { f as DetectionPolicy } from './schema-CHb3GU1r.js';
1
+ import { g as DetectionPolicy } from './schema-DMnoU1V_.js';
2
2
  import { OtelHookErrorInfo } from './errors.js';
3
- import { P as ProviderAdapter, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext } from './adapter-B9RwW6TO.js';
3
+ import { P as ProviderAdapter, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext } from './adapter-DiLknaTF.js';
4
4
 
5
5
  type DetectionCandidate = {
6
6
  readonly adapter: ProviderAdapter;
package/dist/runtime.d.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { c as LogLevel, d as Logger, W as WorktreeLocator } from './ports-plO5MKrY.js';
2
- export { A as AppliedDelivery, C as Clock, E as EventIdSeed, I as IdGenerator, a as InvocationIdSeed, L as LOG_LEVEL_RANK, b as LocatedWorktree, P as PayloadEnricher, e as PayloadEnrichment, f as PayloadEnrichmentInput, R as ReadCursor, S as StateRecord, g as StateStore, h as StateValue, T as TelemetryEmitResult, i as TelemetrySink, j as appliedDeliverySchema, l as logLevelSchema, s as stateRecordSchema, k as stateValueSchema } from './ports-plO5MKrY.js';
3
- export { D as DeterministicIdOptions, F as FixedClock, a as FixedClockOptions, I as InMemoryStateStore, b as InMemoryStateStoreOptions, L as LogRecord, R as RecordingLogger, c as RecordingTelemetrySink, d as RecordingTelemetrySinkOptions, e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, h as createNullTelemetrySink, i as createRandomIdGenerator, j as createRecordingLogger, k as createRecordingTelemetrySink, l as createSystemClock } from './memory-aJilVG4R.js';
4
- export { C as CumulativeUsageSeries, D as DeliveryDurability, a as DeliveryOrigin, b as DeliveryResolution, c as DeliveryUnavailableReason, H as HookIngestInput, d as HookIngestOptions, e as HookIngestOutcome, O as OtelHook, f as OtelHookDependencies, R as ResolvedDeliveryIdentity, U as UsageObservation, g as UsageScope, h as classifyDurability, i as createOtelHook, j as hostDeliveryIdentity, k as isCommittable, r as resolveDeliveryIdentity, u as usageScopeSchema } from './hook-BAxXoKsp.js';
1
+ import { c as LogLevel, d as Logger, W as WorktreeLocator } from './ports-CeqLq31i.js';
2
+ export { A as AppliedDelivery, C as Clock, E as EventIdSeed, I as IdGenerator, a as InvocationIdSeed, L as LOG_LEVEL_RANK, b as LocatedWorktree, P as PayloadEnricher, e as PayloadEnrichment, f as PayloadEnrichmentInput, R as ReadCursor, S as StateRecord, g as StateStore, h as StateValue, T as TelemetryEmitResult, i as TelemetrySink, j as appliedDeliverySchema, l as logLevelSchema, s as stateRecordSchema, k as stateValueSchema } from './ports-CeqLq31i.js';
3
+ export { D as DeterministicIdOptions, F as FixedClock, a as FixedClockOptions, I as InMemoryStateStore, b as InMemoryStateStoreOptions, L as LogRecord, R as RecordingLogger, c as RecordingTelemetrySink, d as RecordingTelemetrySinkOptions, e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, h as createNullTelemetrySink, i as createRandomIdGenerator, j as createRecordingLogger, k as createRecordingTelemetrySink, l as createSystemClock } from './memory-Cs51jyRk.js';
4
+ export { C as CumulativeUsageSeries, D as DeliveryDurability, a as DeliveryOrigin, b as DeliveryResolution, c as DeliveryUnavailableReason, H as HookIngestInput, d as HookIngestOptions, e as HookIngestOutcome, O as OtelHook, f as OtelHookDependencies, R as ResolvedDeliveryIdentity, U as UsageObservation, g as UsageScope, h as classifyDurability, i as createOtelHook, j as hostDeliveryIdentity, k as isCommittable, r as resolveDeliveryIdentity, u as usageScopeSchema } from './hook-BOecWGSz.js';
5
5
  import { b as CanonicalEvent, u as TargetHint } from './events-CSD_YiJ2.js';
6
6
  import { d as EventId } from './primitives-CJ8-rn-f.js';
7
7
  import { P as PrivacyService } from './service-CbI9CObT.js';
8
8
  import 'zod';
9
9
  import './errors.js';
10
10
  import './taxonomy-DwhTtuWd.js';
11
- import './schema-CHb3GU1r.js';
11
+ import './schema-DMnoU1V_.js';
12
12
  import './identity-BrVBs901.js';
13
- import './adapter-B9RwW6TO.js';
13
+ import './adapter-DiLknaTF.js';
14
14
  import './policy-CimmCfRp.js';
15
15
  import './content-M9xIKG7h.js';
16
- import './registry-C7XO4DzD.js';
16
+ import './registry-CcJNF3WY.js';
17
17
 
18
18
  declare const createNullLogger: () => Logger;
19
19
  type StderrLoggerOptions = {
package/dist/runtime.js CHANGED
@@ -985,6 +985,29 @@ var stateValueSchema = z10.discriminatedUnion("kind", [
985
985
  * (Claude Code's transcript), so the next read starts where the last ended.
986
986
  * `source` is an opaque digest of what was read, never a path.
987
987
  */
988
+ /**
989
+ * Running state of one metric series (issue #69), so a cumulative data point
990
+ * exported by a later hook process continues the same total. Holds numbers and
991
+ * a series digest only; the series' attributes are re-supplied by the caller
992
+ * and never read back from disk.
993
+ */
994
+ z10.strictObject({
995
+ kind: z10.literal("metric-series"),
996
+ /** Start of the cumulative interval. */
997
+ startTimeMillis: epochMillisSchema,
998
+ /** Counters: the running total. */
999
+ value: z10.number().finite().min(0).optional(),
1000
+ /** Histograms: the running aggregation. */
1001
+ histogram: z10.strictObject({
1002
+ count: z10.number().int().min(0),
1003
+ sum: z10.number().finite().min(0),
1004
+ min: z10.number().finite(),
1005
+ max: z10.number().finite(),
1006
+ bucketCounts: z10.array(z10.number().int().min(0)).max(64)
1007
+ }).optional(),
1008
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
1009
+ appliedDelivery: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
1010
+ }),
988
1011
  z10.strictObject({
989
1012
  kind: z10.literal("read-cursor"),
990
1013
  source: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -1448,7 +1471,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1448
1471
  var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1449
1472
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1450
1473
  var MAX_HEADER_VALUE_LENGTH = 8192;
1451
- var exportSignalSchema = z13.enum(["traces", "logs"]);
1474
+ var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
1452
1475
  var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1453
1476
  (value) => !isUnsafeHeaderValue(value),
1454
1477
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -1471,6 +1494,8 @@ var exportDestinationSchema = z13.strictObject({
1471
1494
  tracesEndpoint: endpointSchema.optional(),
1472
1495
  /** Per-signal override of the derived logs URL. */
1473
1496
  logsEndpoint: endpointSchema.optional(),
1497
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
1498
+ metricsEndpoint: endpointSchema.optional(),
1474
1499
  /** Defaults to `exporter.protocol`. */
1475
1500
  protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1476
1501
  /**
@@ -1483,15 +1508,17 @@ var exportDestinationSchema = z13.strictObject({
1483
1508
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1484
1509
  ).optional(),
1485
1510
  /**
1486
- * Which signals this destination receives. Default: both. The logs signal is
1487
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1488
- * second stream leaving the host.
1511
+ * Which signals this destination receives. Default: traces and logs. The logs
1512
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
1513
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
1514
+ * default: a destination receives hook-derived metrics only when it lists them.
1489
1515
  */
1490
- signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
1516
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1491
1517
  }).refine(
1492
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1493
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1518
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1519
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
1494
1520
  );
1521
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
1495
1522
  var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1496
1523
  const seen = /* @__PURE__ */ new Set();
1497
1524
  destinations.forEach((destination, index) => {
@@ -1616,6 +1643,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
1616
1643
  includeContent: false,
1617
1644
  maxBatchSize: 128
1618
1645
  });
1646
+ var metricsPolicySchema = z15.strictObject({
1647
+ enabled: z15.boolean(),
1648
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
1649
+ endpoint: z15.string().url().max(2048).optional(),
1650
+ temporality: z15.enum(["cumulative", "delta"]),
1651
+ includeSessionId: z15.boolean()
1652
+ });
1653
+ var DEFAULT_METRICS_POLICY = Object.freeze({
1654
+ enabled: false,
1655
+ temporality: "cumulative",
1656
+ includeSessionId: true
1657
+ });
1619
1658
  var exporterPolicySchema = z15.strictObject({
1620
1659
  enabled: z15.boolean(),
1621
1660
  protocol: z15.enum(["http/protobuf", "http/json", "none"]),
@@ -1646,6 +1685,11 @@ var exporterPolicySchema = z15.strictObject({
1646
1685
  * a second top-level section would invite two of each to drift apart.
1647
1686
  */
1648
1687
  logs: logsPolicySchema,
1688
+ /**
1689
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
1690
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
1691
+ */
1692
+ metrics: metricsPolicySchema.optional(),
1649
1693
  /**
1650
1694
  * Additional OTLP destinations, each sent every batch in parallel.
1651
1695
  *
@@ -1694,8 +1738,9 @@ var otelHookConfigPatchSchema = z15.strictObject({
1694
1738
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1695
1739
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1696
1740
  // without also restating the endpoint and the batch size.
1697
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
1741
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
1698
1742
  logs: logsPolicySchema.partial().optional(),
1743
+ metrics: metricsPolicySchema.partial().optional(),
1699
1744
  spool: spoolPolicySchema.partial().optional()
1700
1745
  }).optional(),
1701
1746
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -1715,7 +1760,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
1715
1760
  maxRetryAttempts: 2,
1716
1761
  serviceName: "coding-agent",
1717
1762
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1718
- logs: DEFAULT_LOGS_POLICY
1763
+ logs: DEFAULT_LOGS_POLICY,
1764
+ metrics: DEFAULT_METRICS_POLICY
1719
1765
  });
1720
1766
  var DEFAULT_DETECTION_POLICY = Object.freeze({
1721
1767
  minimumConfidence: "strong",