@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/dist/testing.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- import { O as OtelHookConfig, g as OtelHookConfigPatch } from './schema-BxiVsU-d.js';
2
- import { b as CanonicalEvent } from './events-B3MHoJTD.js';
1
+ import { O as OtelHookConfig, i as OtelHookConfigPatch } from './schema-DMnoU1V_.js';
2
+ import { b as CanonicalEvent } from './events-CSD_YiJ2.js';
3
3
  import { I as IdentityClaim, d as InvocationIdentity, S as SourceProvenance } from './identity-BrVBs901.js';
4
4
  import { P as PrivacyService } from './service-CbI9CObT.js';
5
- import { d as ProviderCapabilities, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext, l as ProviderIdentityInput, f as ProviderDeliveryClaim, k as ProviderHookResponseInput, j as ProviderHookResponse, P as ProviderAdapter } from './adapter-BJiz6lqM.js';
6
- import { P as ProviderRegistry } from './registry-B8ZHc2bc.js';
7
- import { c as RecordingTelemetrySink, I as InMemoryStateStore, F as FixedClock, R as RecordingLogger } from './memory-Bl9ANVff.js';
8
- export { e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, j as createRecordingLogger, k as createRecordingTelemetrySink } from './memory-Bl9ANVff.js';
9
- import { O as OtelHook } from './hook-zA1b4cWd.js';
10
- import { I as IdGenerator, W as WorktreeLocator } from './ports-n7KFOpKo.js';
5
+ import { d as ProviderCapabilities, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext, l as ProviderIdentityInput, f as ProviderDeliveryClaim, k as ProviderHookResponseInput, j as ProviderHookResponse, P as ProviderAdapter } from './adapter-DiLknaTF.js';
6
+ import { P as ProviderRegistry } from './registry-CcJNF3WY.js';
7
+ import { I as IdGenerator, W as WorktreeLocator, P as PayloadEnricher } from './ports-CeqLq31i.js';
8
+ import { c as RecordingTelemetrySink, I as InMemoryStateStore, F as FixedClock, R as RecordingLogger } from './memory-Cs51jyRk.js';
9
+ export { e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, j as createRecordingLogger, k as createRecordingTelemetrySink } from './memory-Cs51jyRk.js';
10
+ import { O as OtelHook } from './hook-BOecWGSz.js';
11
11
  import { z } from 'zod';
12
12
  import { a as ContentDisclosure, b as ContentFact } from './content-M9xIKG7h.js';
13
13
  import './primitives-CJ8-rn-f.js';
@@ -43,8 +43,8 @@ declare const syntheticPayloadSchema: z.ZodObject<{
43
43
  occurredAt: z.ZodOptional<z.ZodNumber>;
44
44
  usage: z.ZodOptional<z.ZodObject<{
45
45
  temporality: z.ZodEnum<{
46
- delta: "delta";
47
46
  cumulative: "cumulative";
47
+ delta: "delta";
48
48
  }>;
49
49
  inputTokens: z.ZodOptional<z.ZodNumber>;
50
50
  cachedInputTokens: z.ZodOptional<z.ZodNumber>;
@@ -144,6 +144,8 @@ type TestHarnessOptions = {
144
144
  * cannot turn the assertion into a timing race.
145
145
  */
146
146
  readonly targetResolutionBudgetMillis?: number;
147
+ /** Payload enrichers, as a host would configure them (none by default). */
148
+ readonly payloadEnrichers?: readonly PayloadEnricher[];
147
149
  };
148
150
  type TestHarness = {
149
151
  readonly hook: OtelHook;
package/dist/testing.js CHANGED
@@ -161,7 +161,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
161
161
  var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
162
162
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
163
163
  var MAX_HEADER_VALUE_LENGTH = 8192;
164
- var exportSignalSchema = z3.enum(["traces", "logs"]);
164
+ var exportSignalSchema = z3.enum(["traces", "logs", "metrics"]);
165
165
  var headerValueSchema = z3.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
166
166
  (value) => !isUnsafeHeaderValue(value),
167
167
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -184,6 +184,8 @@ var exportDestinationSchema = z3.strictObject({
184
184
  tracesEndpoint: endpointSchema.optional(),
185
185
  /** Per-signal override of the derived logs URL. */
186
186
  logsEndpoint: endpointSchema.optional(),
187
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
188
+ metricsEndpoint: endpointSchema.optional(),
187
189
  /** Defaults to `exporter.protocol`. */
188
190
  protocol: z3.enum(["http/protobuf", "http/json", "none"]).optional(),
189
191
  /**
@@ -196,15 +198,17 @@ var exportDestinationSchema = z3.strictObject({
196
198
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
197
199
  ).optional(),
198
200
  /**
199
- * Which signals this destination receives. Default: both. The logs signal is
200
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
201
- * second stream leaving the host.
201
+ * Which signals this destination receives. Default: traces and logs. The logs
202
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
203
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
204
+ * default: a destination receives hook-derived metrics only when it lists them.
202
205
  */
203
- signals: z3.array(exportSignalSchema).min(1).max(2).readonly().optional()
206
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional()
204
207
  }).refine(
205
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
206
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
208
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
209
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
207
210
  );
211
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
208
212
  var exportDestinationsSchema = z3.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
209
213
  const seen = /* @__PURE__ */ new Set();
210
214
  destinations.forEach((destination, index) => {
@@ -329,6 +333,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
329
333
  includeContent: false,
330
334
  maxBatchSize: 128
331
335
  });
336
+ var metricsPolicySchema = z5.strictObject({
337
+ enabled: z5.boolean(),
338
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
339
+ endpoint: z5.string().url().max(2048).optional(),
340
+ temporality: z5.enum(["cumulative", "delta"]),
341
+ includeSessionId: z5.boolean()
342
+ });
343
+ var DEFAULT_METRICS_POLICY = Object.freeze({
344
+ enabled: false,
345
+ temporality: "cumulative",
346
+ includeSessionId: true
347
+ });
332
348
  var exporterPolicySchema = z5.strictObject({
333
349
  enabled: z5.boolean(),
334
350
  protocol: z5.enum(["http/protobuf", "http/json", "none"]),
@@ -359,6 +375,11 @@ var exporterPolicySchema = z5.strictObject({
359
375
  * a second top-level section would invite two of each to drift apart.
360
376
  */
361
377
  logs: logsPolicySchema,
378
+ /**
379
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
380
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
381
+ */
382
+ metrics: metricsPolicySchema.optional(),
362
383
  /**
363
384
  * Additional OTLP destinations, each sent every batch in parallel.
364
385
  *
@@ -390,23 +411,34 @@ var diagnosticsPolicySchema = z5.strictObject({
390
411
  /** Emit `error.raised` events for contained failures. */
391
412
  emitErrorEvents: z5.boolean()
392
413
  });
414
+ var providersPolicySchema = z5.strictObject({
415
+ claudeCode: z5.strictObject({
416
+ readTranscriptUsage: z5.boolean()
417
+ }).optional()
418
+ });
393
419
  var otelHookConfigSchema = z5.strictObject({
394
420
  exporter: exporterPolicySchema,
395
421
  privacy: privacyPolicySchema,
396
422
  detection: detectionPolicySchema,
397
- diagnostics: diagnosticsPolicySchema
423
+ diagnostics: diagnosticsPolicySchema,
424
+ /** Optional so a hand-built configuration from before it existed stays valid. */
425
+ providers: providersPolicySchema.optional()
398
426
  });
399
427
  var otelHookConfigPatchSchema = z5.strictObject({
400
428
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
401
429
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
402
430
  // without also restating the endpoint and the batch size.
403
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
431
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
404
432
  logs: logsPolicySchema.partial().optional(),
433
+ metrics: metricsPolicySchema.partial().optional(),
405
434
  spool: spoolPolicySchema.partial().optional()
406
435
  }).optional(),
407
436
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
408
437
  detection: detectionPolicySchema.partial().optional(),
409
- diagnostics: diagnosticsPolicySchema.partial().optional()
438
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
439
+ providers: z5.strictObject({
440
+ claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
441
+ }).partial().optional()
410
442
  });
411
443
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
412
444
  enabled: true,
@@ -418,7 +450,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
418
450
  maxRetryAttempts: 2,
419
451
  serviceName: "coding-agent",
420
452
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
421
- logs: DEFAULT_LOGS_POLICY
453
+ logs: DEFAULT_LOGS_POLICY,
454
+ metrics: DEFAULT_METRICS_POLICY
422
455
  });
423
456
  var DEFAULT_DETECTION_POLICY = Object.freeze({
424
457
  minimumConfidence: "strong",
@@ -429,11 +462,15 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
429
462
  logLevel: "warn",
430
463
  emitErrorEvents: true
431
464
  });
465
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
466
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
467
+ });
432
468
  var DEFAULT_CONFIG = Object.freeze({
433
469
  exporter: DEFAULT_EXPORTER_POLICY,
434
470
  privacy: DEFAULT_PRIVACY_POLICY,
435
471
  detection: DEFAULT_DETECTION_POLICY,
436
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
472
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
473
+ providers: DEFAULT_PROVIDERS_POLICY
437
474
  });
438
475
 
439
476
  // src/model/identity.ts
@@ -878,11 +915,11 @@ var createPrivacyService = (policyInput) => {
878
915
  };
879
916
  const flattenToAttributes = (value, prefix) => {
880
917
  const attributes = {};
881
- const walk = (current, path2) => {
918
+ const walk = (current, path3) => {
882
919
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
883
920
  const primitive = toAttributePrimitive(current);
884
921
  if (primitive !== void 0) {
885
- attributes[path2] = primitive;
922
+ attributes[path3] = primitive;
886
923
  }
887
924
  return;
888
925
  }
@@ -901,16 +938,16 @@ var createPrivacyService = (policyInput) => {
901
938
  primitives.push(entryPrimitive);
902
939
  }
903
940
  if (uniform) {
904
- attributes[path2] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
941
+ attributes[path3] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
905
942
  return;
906
943
  }
907
944
  for (const [index, entry] of current.entries()) {
908
- walk(entry, `${path2}.${index}`);
945
+ walk(entry, `${path3}.${index}`);
909
946
  }
910
947
  return;
911
948
  }
912
949
  for (const [key, entry] of Object.entries(current)) {
913
- walk(entry, path2 === "" ? key : `${path2}.${key}`);
950
+ walk(entry, path3 === "" ? key : `${path3}.${key}`);
914
951
  }
915
952
  };
916
953
  walk(value, prefix);
@@ -1586,6 +1623,13 @@ var generationEndEventSchema = event({
1586
1623
  stopReason: nonEmptyStringSchema.optional(),
1587
1624
  durationMillis: durationMillisSchema.optional(),
1588
1625
  usage: canonicalUsageSchema.optional(),
1626
+ /**
1627
+ * True when `usage` is known to cover only part of the generation (for
1628
+ * example the last model request of a multi-request turn); false when the
1629
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
1630
+ * without `usage`.
1631
+ */
1632
+ usagePartial: z13.boolean().optional(),
1589
1633
  cost: costFactsSchema.optional(),
1590
1634
  outputContent: contentFactsSchema.optional()
1591
1635
  });
@@ -2241,7 +2285,25 @@ var stopPayloadSchema = z16.object({
2241
2285
  * the former without suppressing the latter.
2242
2286
  */
2243
2287
  stop_hook_active: z16.boolean().optional(),
2244
- usage: claudeUsageSchema.optional()
2288
+ usage: claudeUsageSchema.optional(),
2289
+ /**
2290
+ * The model that answered this turn — harness-supplied, never upstream.
2291
+ *
2292
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
2293
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
2294
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
2295
+ * with `usage`, and it becomes the generation's response model. An unusable
2296
+ * value (empty, over 256 characters, not a string) is dropped rather than
2297
+ * failing the whole payload: the turn is still worth reporting without it.
2298
+ */
2299
+ model: z16.string().min(1).max(256).optional().catch(void 0),
2300
+ /**
2301
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
2302
+ * turn. `true` when it is the last model request alone (the tail fallback),
2303
+ * `false` when it sums every request since the previous stop. Exported as
2304
+ * `otelhook.usage.partial`; absent means the attacher did not say.
2305
+ */
2306
+ usage_partial: z16.boolean().optional().catch(void 0)
2245
2307
  });
2246
2308
  var stopFailurePayloadSchema = z16.object({
2247
2309
  ...commonFields,
@@ -2253,7 +2315,11 @@ var stopFailurePayloadSchema = z16.object({
2253
2315
  */
2254
2316
  error_type: z16.string().min(1),
2255
2317
  error_message: z16.string().optional(),
2256
- usage: claudeUsageSchema.optional()
2318
+ usage: claudeUsageSchema.optional(),
2319
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
2320
+ model: z16.string().min(1).max(256).optional().catch(void 0),
2321
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
2322
+ usage_partial: z16.boolean().optional().catch(void 0)
2257
2323
  });
2258
2324
  var claudeHookPayloadSchema = z16.discriminatedUnion("hook_event_name", [
2259
2325
  sessionStartPayloadSchema,
@@ -2832,6 +2898,13 @@ var inferToolKind = (toolName) => {
2832
2898
 
2833
2899
  // src/providers/claude/events.ts
2834
2900
  var UNKNOWN_MODEL = { modelId: "unknown" };
2901
+ var generationModels = (attached, sessionModel) => {
2902
+ const turnModel = attached === void 0 ? void 0 : { modelId: attached };
2903
+ return {
2904
+ request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
2905
+ response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
2906
+ };
2907
+ };
2835
2908
  var SESSION_END_REASON = Object.freeze({
2836
2909
  completed: "completed",
2837
2910
  aborted: "aborted",
@@ -2898,6 +2971,10 @@ var parseClaudeCode = (input, context) => {
2898
2971
  warnings.push(...normalized.warnings);
2899
2972
  return applyUsage(normalized);
2900
2973
  };
2974
+ const withPartialUsage = (usage, partial) => {
2975
+ const applied = withUsage(usage);
2976
+ return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
2977
+ };
2901
2978
  switch (payload.hook_event_name) {
2902
2979
  case "SessionStart":
2903
2980
  factory.build({
@@ -3010,11 +3087,12 @@ var parseClaudeCode = (input, context) => {
3010
3087
  payload.prompt_id ?? String(input.sequenceBase)
3011
3088
  ]);
3012
3089
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3013
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3090
+ const models = generationModels(payload.model, input.sessionModel);
3091
+ factory.build({ type: "generation.start", generationId, model: models.request });
3014
3092
  factory.build({
3015
3093
  type: "generation.end",
3016
3094
  generationId,
3017
- model: UNKNOWN_MODEL,
3095
+ model: models.response,
3018
3096
  outcome: "ok",
3019
3097
  // Always a response fact: a body when Claude sent text, otherwise a
3020
3098
  // zero-length omitted fact so the log mapping can emit metadata_only
@@ -3026,7 +3104,7 @@ var parseClaudeCode = (input, context) => {
3026
3104
  text: assistantText
3027
3105
  })
3028
3106
  ],
3029
- ...withUsage(extractedUsage ?? payload.usage)
3107
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3030
3108
  });
3031
3109
  break;
3032
3110
  }
@@ -3037,11 +3115,12 @@ var parseClaudeCode = (input, context) => {
3037
3115
  payload.prompt_id ?? String(input.sequenceBase)
3038
3116
  ]);
3039
3117
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3040
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3118
+ const models = generationModels(payload.model, input.sessionModel);
3119
+ factory.build({ type: "generation.start", generationId, model: models.request });
3041
3120
  factory.build({
3042
3121
  type: "generation.end",
3043
3122
  generationId,
3044
- model: UNKNOWN_MODEL,
3123
+ model: models.response,
3045
3124
  outcome: mapStopFailureOutcome(payload.error_type),
3046
3125
  stopReason: payload.error_type,
3047
3126
  ...assistantText === void 0 ? {} : {
@@ -3053,7 +3132,7 @@ var parseClaudeCode = (input, context) => {
3053
3132
  })
3054
3133
  ]
3055
3134
  },
3056
- ...withUsage(extractedUsage ?? payload.usage)
3135
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3057
3136
  });
3058
3137
  break;
3059
3138
  }
@@ -3080,6 +3159,11 @@ var createClaudeCodeAdapter = (options = {}) => ({
3080
3159
  hookResponse: () => SILENT_HOOK_RESPONSE
3081
3160
  });
3082
3161
 
3162
+ // src/providers/claude/transcript.ts
3163
+ import { createHash as createHash2 } from "crypto";
3164
+ import { open, stat } from "fs/promises";
3165
+ import path from "path";
3166
+
3083
3167
  // src/providers/cursor/payload.ts
3084
3168
  import { z as z17 } from "zod";
3085
3169
  var CURSOR_PROVIDER_ID = "cursor";
@@ -5723,9 +5807,9 @@ var resolveDeliveryIdentity = (input) => {
5723
5807
  };
5724
5808
 
5725
5809
  // src/runtime/ids.ts
5726
- import { createHash as createHash2, randomUUID } from "crypto";
5810
+ import { createHash as createHash3, randomUUID } from "crypto";
5727
5811
  var digest = (namespace, parts) => {
5728
- const hash = createHash2("sha256");
5812
+ const hash = createHash3("sha256");
5729
5813
  hash.update(namespace);
5730
5814
  for (const part of parts) {
5731
5815
  hash.update("\0");
@@ -5788,6 +5872,49 @@ var stateValueSchema = z21.discriminatedUnion("kind", [
5788
5872
  z21.strictObject({
5789
5873
  kind: z21.literal("attributes"),
5790
5874
  attributes: attributesSchema
5875
+ }),
5876
+ /**
5877
+ * The model a session last reported, so a later invocation whose payload names
5878
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
5879
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
5880
+ * bounded canonical shape, never a payload fragment.
5881
+ */
5882
+ z21.strictObject({
5883
+ kind: z21.literal("session-model"),
5884
+ model: modelDescriptorSchema
5885
+ }),
5886
+ /**
5887
+ * How far a {@link PayloadEnricher} has read a session's append-only source
5888
+ * (Claude Code's transcript), so the next read starts where the last ended.
5889
+ * `source` is an opaque digest of what was read, never a path.
5890
+ */
5891
+ /**
5892
+ * Running state of one metric series (issue #69), so a cumulative data point
5893
+ * exported by a later hook process continues the same total. Holds numbers and
5894
+ * a series digest only; the series' attributes are re-supplied by the caller
5895
+ * and never read back from disk.
5896
+ */
5897
+ z21.strictObject({
5898
+ kind: z21.literal("metric-series"),
5899
+ /** Start of the cumulative interval. */
5900
+ startTimeMillis: epochMillisSchema,
5901
+ /** Counters: the running total. */
5902
+ value: z21.number().finite().min(0).optional(),
5903
+ /** Histograms: the running aggregation. */
5904
+ histogram: z21.strictObject({
5905
+ count: z21.number().int().min(0),
5906
+ sum: z21.number().finite().min(0),
5907
+ min: z21.number().finite(),
5908
+ max: z21.number().finite(),
5909
+ bucketCounts: z21.array(z21.number().int().min(0)).max(64)
5910
+ }).optional(),
5911
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
5912
+ appliedDelivery: z21.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
5913
+ }),
5914
+ z21.strictObject({
5915
+ kind: z21.literal("read-cursor"),
5916
+ source: z21.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
5917
+ offset: z21.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
5791
5918
  })
5792
5919
  ]);
5793
5920
  var stateRecordSchema = z21.strictObject({
@@ -5814,16 +5941,16 @@ var createNullLogger = () => ({
5814
5941
  });
5815
5942
 
5816
5943
  // src/runtime/target-resolution.ts
5817
- import * as path from "path";
5944
+ import * as path2 from "path";
5818
5945
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
5819
5946
  var absolutePathsOf = (hint) => {
5820
- const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
5947
+ const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
5821
5948
  const resolved = [];
5822
5949
  for (const candidate of hint.paths) {
5823
- if (path.isAbsolute(candidate)) {
5824
- resolved.push(path.resolve(candidate));
5950
+ if (path2.isAbsolute(candidate)) {
5951
+ resolved.push(path2.resolve(candidate));
5825
5952
  } else if (base !== void 0) {
5826
- resolved.push(path.resolve(base, candidate));
5953
+ resolved.push(path2.resolve(base, candidate));
5827
5954
  } else {
5828
5955
  return void 0;
5829
5956
  }
@@ -5987,6 +6114,22 @@ var usageScopeOf = (event3) => {
5987
6114
  }
5988
6115
  };
5989
6116
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
6117
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
6118
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
6119
+ var UNKNOWN_MODEL_ID = "unknown";
6120
+ var latestSessionModel = (events) => {
6121
+ let latest;
6122
+ for (const event3 of events) {
6123
+ if (event3.subagentId !== void 0) {
6124
+ continue;
6125
+ }
6126
+ if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
6127
+ latest = event3.model;
6128
+ }
6129
+ }
6130
+ return latest;
6131
+ };
6132
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
5990
6133
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
5991
6134
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
5992
6135
  var createOtelHook = (deps) => {
@@ -6034,6 +6177,66 @@ var createOtelHook = (deps) => {
6034
6177
  return 0;
6035
6178
  }
6036
6179
  };
6180
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
6181
+ let current = payload;
6182
+ for (const enricher of deps.payloadEnrichers ?? []) {
6183
+ if (enricher.providerId !== providerId) {
6184
+ continue;
6185
+ }
6186
+ const key = readCursorKey(enricher.id, sessionId);
6187
+ let cursor;
6188
+ try {
6189
+ const record = await deps.stateStore.read(key);
6190
+ if (record?.value.kind === "read-cursor") {
6191
+ cursor = { source: record.value.source, offset: record.value.offset };
6192
+ }
6193
+ } catch (thrown) {
6194
+ diagnostics.push(
6195
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
6196
+ );
6197
+ continue;
6198
+ }
6199
+ let result;
6200
+ try {
6201
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
6202
+ } catch (thrown) {
6203
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
6204
+ "enricher.id": enricher.id,
6205
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
6206
+ });
6207
+ continue;
6208
+ }
6209
+ current = result.payload;
6210
+ if (result.notes !== void 0 && result.notes.length > 0) {
6211
+ logger.debug("payload enricher notes", {
6212
+ "enricher.id": enricher.id,
6213
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
6214
+ });
6215
+ }
6216
+ const next = result.cursor;
6217
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
6218
+ try {
6219
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
6220
+ } catch (thrown) {
6221
+ diagnostics.push(
6222
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
6223
+ );
6224
+ }
6225
+ }
6226
+ }
6227
+ return current;
6228
+ };
6229
+ const readSessionModel = async (sessionId, diagnostics) => {
6230
+ try {
6231
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
6232
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
6233
+ } catch (thrown) {
6234
+ diagnostics.push(
6235
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
6236
+ );
6237
+ return void 0;
6238
+ }
6239
+ };
6037
6240
  const deriveUsage = async (events, diagnostics, suppress, series) => {
6038
6241
  const observations = [];
6039
6242
  for (const event3 of events) {
@@ -6354,10 +6557,19 @@ var createOtelHook = (deps) => {
6354
6557
  const identity = resolution.identity;
6355
6558
  const prepare = async () => {
6356
6559
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
6560
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
6561
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
6357
6562
  let parsed;
6358
6563
  try {
6359
6564
  parsed = adapter.parse(
6360
- { ...detectionInput, detection, identity, sequenceBase },
6565
+ {
6566
+ ...detectionInput,
6567
+ payload,
6568
+ detection,
6569
+ identity,
6570
+ sequenceBase,
6571
+ ...sessionModel === void 0 ? {} : { sessionModel }
6572
+ },
6361
6573
  providerContext
6362
6574
  );
6363
6575
  } catch (thrown) {
@@ -6467,6 +6679,23 @@ var createOtelHook = (deps) => {
6467
6679
  })
6468
6680
  );
6469
6681
  }
6682
+ const reportedModel = latestSessionModel(screened.kept);
6683
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
6684
+ try {
6685
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
6686
+ kind: "session-model",
6687
+ model: reportedModel
6688
+ });
6689
+ } catch (thrown) {
6690
+ diagnostics.push(
6691
+ errorInfoFromThrown(thrown, {
6692
+ code: "state-store-failure",
6693
+ phase: "state",
6694
+ occurredAt: clock.now()
6695
+ })
6696
+ );
6697
+ }
6698
+ }
6470
6699
  }
6471
6700
  return {
6472
6701
  kind: "ready",
@@ -7229,7 +7458,8 @@ var createTestHook = (options = {}) => {
7229
7458
  privacy,
7230
7459
  logger,
7231
7460
  ...options.worktreeLocator === void 0 ? {} : { worktreeLocator: options.worktreeLocator },
7232
- ...options.targetResolutionBudgetMillis === void 0 ? {} : { targetResolutionBudgetMillis: options.targetResolutionBudgetMillis }
7461
+ ...options.targetResolutionBudgetMillis === void 0 ? {} : { targetResolutionBudgetMillis: options.targetResolutionBudgetMillis },
7462
+ ...options.payloadEnrichers === void 0 ? {} : { payloadEnrichers: options.payloadEnrichers }
7233
7463
  });
7234
7464
  return { hook, sink, stateStore, clock, ids, privacy, logger, registry, config };
7235
7465
  };