@osfactory/otel-hook 0.9.0 → 0.10.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 (49) hide show
  1. package/README.md +42 -1
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-B9RwW6TO.d.ts} +14 -2
  3. package/dist/cli.js +1272 -784
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +5 -3
  6. package/dist/config.js +28 -5
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C6Bm89W6.d.ts → destinations-DWOkVxV1.d.ts} +1 -1
  9. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  10. package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-lORbe25J.d.ts} +5 -5
  11. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-DX3dGIgu.d.ts} +1 -1
  12. package/dist/{hook-zA1b4cWd.d.ts → hook-BAxXoKsp.d.ts} +10 -5
  13. package/dist/index.d.ts +14 -14
  14. package/dist/index.js +643 -110
  15. package/dist/index.js.map +1 -1
  16. package/dist/install.d.ts +4 -4
  17. package/dist/install.js +31 -2
  18. package/dist/install.js.map +1 -1
  19. package/dist/integration.d.ts +17 -10
  20. package/dist/integration.js +3864 -3107
  21. package/dist/integration.js.map +1 -1
  22. package/dist/lifecycle.d.ts +3 -3
  23. package/dist/lifecycle.js +8 -1
  24. package/dist/lifecycle.js.map +1 -1
  25. package/dist/{memory-Bl9ANVff.d.ts → memory-aJilVG4R.d.ts} +2 -2
  26. package/dist/model.d.ts +1 -1
  27. package/dist/model.js +7 -0
  28. package/dist/model.js.map +1 -1
  29. package/dist/{payload-Ci8_ERm6.d.ts → payload-D7gc0-WQ.d.ts} +41 -2
  30. package/dist/{ports-n7KFOpKo.d.ts → ports-plO5MKrY.d.ts} +63 -2
  31. package/dist/providers.d.ts +146 -10
  32. package/dist/providers.js +397 -13
  33. package/dist/providers.js.map +1 -1
  34. package/dist/{registry-B8ZHc2bc.d.ts → registry-C7XO4DzD.d.ts} +2 -2
  35. package/dist/runtime.d.ts +8 -8
  36. package/dist/runtime.js +1356 -1217
  37. package/dist/runtime.js.map +1 -1
  38. package/dist/{schema-BxiVsU-d.d.ts → schema-CHb3GU1r.d.ts} +30 -1
  39. package/dist/{semconv-fPRb-dpU.d.ts → semconv-Dw7gcQcg.d.ts} +1 -1
  40. package/dist/state.d.ts +4 -4
  41. package/dist/state.js +607 -39
  42. package/dist/state.js.map +1 -1
  43. package/dist/telemetry.d.ts +6 -6
  44. package/dist/telemetry.js +13 -3
  45. package/dist/telemetry.js.map +1 -1
  46. package/dist/testing.d.ts +10 -8
  47. package/dist/testing.js +209 -25
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +1 -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, h as OtelHookConfigPatch } from './schema-CHb3GU1r.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-B9RwW6TO.js';
6
+ import { P as ProviderRegistry } from './registry-C7XO4DzD.js';
7
+ import { I as IdGenerator, W as WorktreeLocator, P as PayloadEnricher } from './ports-plO5MKrY.js';
8
+ import { c as RecordingTelemetrySink, I as InMemoryStateStore, F as FixedClock, R as RecordingLogger } from './memory-aJilVG4R.js';
9
+ export { e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, j as createRecordingLogger, k as createRecordingTelemetrySink } from './memory-aJilVG4R.js';
10
+ import { O as OtelHook } from './hook-BAxXoKsp.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';
@@ -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
@@ -390,11 +390,18 @@ var diagnosticsPolicySchema = z5.strictObject({
390
390
  /** Emit `error.raised` events for contained failures. */
391
391
  emitErrorEvents: z5.boolean()
392
392
  });
393
+ var providersPolicySchema = z5.strictObject({
394
+ claudeCode: z5.strictObject({
395
+ readTranscriptUsage: z5.boolean()
396
+ }).optional()
397
+ });
393
398
  var otelHookConfigSchema = z5.strictObject({
394
399
  exporter: exporterPolicySchema,
395
400
  privacy: privacyPolicySchema,
396
401
  detection: detectionPolicySchema,
397
- diagnostics: diagnosticsPolicySchema
402
+ diagnostics: diagnosticsPolicySchema,
403
+ /** Optional so a hand-built configuration from before it existed stays valid. */
404
+ providers: providersPolicySchema.optional()
398
405
  });
399
406
  var otelHookConfigPatchSchema = z5.strictObject({
400
407
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -406,7 +413,10 @@ var otelHookConfigPatchSchema = z5.strictObject({
406
413
  }).optional(),
407
414
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
408
415
  detection: detectionPolicySchema.partial().optional(),
409
- diagnostics: diagnosticsPolicySchema.partial().optional()
416
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
417
+ providers: z5.strictObject({
418
+ claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
419
+ }).partial().optional()
410
420
  });
411
421
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
412
422
  enabled: true,
@@ -429,11 +439,15 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
429
439
  logLevel: "warn",
430
440
  emitErrorEvents: true
431
441
  });
442
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
443
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
444
+ });
432
445
  var DEFAULT_CONFIG = Object.freeze({
433
446
  exporter: DEFAULT_EXPORTER_POLICY,
434
447
  privacy: DEFAULT_PRIVACY_POLICY,
435
448
  detection: DEFAULT_DETECTION_POLICY,
436
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
449
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
450
+ providers: DEFAULT_PROVIDERS_POLICY
437
451
  });
438
452
 
439
453
  // src/model/identity.ts
@@ -878,11 +892,11 @@ var createPrivacyService = (policyInput) => {
878
892
  };
879
893
  const flattenToAttributes = (value, prefix) => {
880
894
  const attributes = {};
881
- const walk = (current, path2) => {
895
+ const walk = (current, path3) => {
882
896
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
883
897
  const primitive = toAttributePrimitive(current);
884
898
  if (primitive !== void 0) {
885
- attributes[path2] = primitive;
899
+ attributes[path3] = primitive;
886
900
  }
887
901
  return;
888
902
  }
@@ -901,16 +915,16 @@ var createPrivacyService = (policyInput) => {
901
915
  primitives.push(entryPrimitive);
902
916
  }
903
917
  if (uniform) {
904
- attributes[path2] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
918
+ attributes[path3] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
905
919
  return;
906
920
  }
907
921
  for (const [index, entry] of current.entries()) {
908
- walk(entry, `${path2}.${index}`);
922
+ walk(entry, `${path3}.${index}`);
909
923
  }
910
924
  return;
911
925
  }
912
926
  for (const [key, entry] of Object.entries(current)) {
913
- walk(entry, path2 === "" ? key : `${path2}.${key}`);
927
+ walk(entry, path3 === "" ? key : `${path3}.${key}`);
914
928
  }
915
929
  };
916
930
  walk(value, prefix);
@@ -1586,6 +1600,13 @@ var generationEndEventSchema = event({
1586
1600
  stopReason: nonEmptyStringSchema.optional(),
1587
1601
  durationMillis: durationMillisSchema.optional(),
1588
1602
  usage: canonicalUsageSchema.optional(),
1603
+ /**
1604
+ * True when `usage` is known to cover only part of the generation (for
1605
+ * example the last model request of a multi-request turn); false when the
1606
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
1607
+ * without `usage`.
1608
+ */
1609
+ usagePartial: z13.boolean().optional(),
1589
1610
  cost: costFactsSchema.optional(),
1590
1611
  outputContent: contentFactsSchema.optional()
1591
1612
  });
@@ -2241,7 +2262,25 @@ var stopPayloadSchema = z16.object({
2241
2262
  * the former without suppressing the latter.
2242
2263
  */
2243
2264
  stop_hook_active: z16.boolean().optional(),
2244
- usage: claudeUsageSchema.optional()
2265
+ usage: claudeUsageSchema.optional(),
2266
+ /**
2267
+ * The model that answered this turn — harness-supplied, never upstream.
2268
+ *
2269
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
2270
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
2271
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
2272
+ * with `usage`, and it becomes the generation's response model. An unusable
2273
+ * value (empty, over 256 characters, not a string) is dropped rather than
2274
+ * failing the whole payload: the turn is still worth reporting without it.
2275
+ */
2276
+ model: z16.string().min(1).max(256).optional().catch(void 0),
2277
+ /**
2278
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
2279
+ * turn. `true` when it is the last model request alone (the tail fallback),
2280
+ * `false` when it sums every request since the previous stop. Exported as
2281
+ * `otelhook.usage.partial`; absent means the attacher did not say.
2282
+ */
2283
+ usage_partial: z16.boolean().optional().catch(void 0)
2245
2284
  });
2246
2285
  var stopFailurePayloadSchema = z16.object({
2247
2286
  ...commonFields,
@@ -2253,7 +2292,11 @@ var stopFailurePayloadSchema = z16.object({
2253
2292
  */
2254
2293
  error_type: z16.string().min(1),
2255
2294
  error_message: z16.string().optional(),
2256
- usage: claudeUsageSchema.optional()
2295
+ usage: claudeUsageSchema.optional(),
2296
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
2297
+ model: z16.string().min(1).max(256).optional().catch(void 0),
2298
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
2299
+ usage_partial: z16.boolean().optional().catch(void 0)
2257
2300
  });
2258
2301
  var claudeHookPayloadSchema = z16.discriminatedUnion("hook_event_name", [
2259
2302
  sessionStartPayloadSchema,
@@ -2832,6 +2875,13 @@ var inferToolKind = (toolName) => {
2832
2875
 
2833
2876
  // src/providers/claude/events.ts
2834
2877
  var UNKNOWN_MODEL = { modelId: "unknown" };
2878
+ var generationModels = (attached, sessionModel) => {
2879
+ const turnModel = attached === void 0 ? void 0 : { modelId: attached };
2880
+ return {
2881
+ request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
2882
+ response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
2883
+ };
2884
+ };
2835
2885
  var SESSION_END_REASON = Object.freeze({
2836
2886
  completed: "completed",
2837
2887
  aborted: "aborted",
@@ -2898,6 +2948,10 @@ var parseClaudeCode = (input, context) => {
2898
2948
  warnings.push(...normalized.warnings);
2899
2949
  return applyUsage(normalized);
2900
2950
  };
2951
+ const withPartialUsage = (usage, partial) => {
2952
+ const applied = withUsage(usage);
2953
+ return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
2954
+ };
2901
2955
  switch (payload.hook_event_name) {
2902
2956
  case "SessionStart":
2903
2957
  factory.build({
@@ -3010,11 +3064,12 @@ var parseClaudeCode = (input, context) => {
3010
3064
  payload.prompt_id ?? String(input.sequenceBase)
3011
3065
  ]);
3012
3066
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3013
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3067
+ const models = generationModels(payload.model, input.sessionModel);
3068
+ factory.build({ type: "generation.start", generationId, model: models.request });
3014
3069
  factory.build({
3015
3070
  type: "generation.end",
3016
3071
  generationId,
3017
- model: UNKNOWN_MODEL,
3072
+ model: models.response,
3018
3073
  outcome: "ok",
3019
3074
  // Always a response fact: a body when Claude sent text, otherwise a
3020
3075
  // zero-length omitted fact so the log mapping can emit metadata_only
@@ -3026,7 +3081,7 @@ var parseClaudeCode = (input, context) => {
3026
3081
  text: assistantText
3027
3082
  })
3028
3083
  ],
3029
- ...withUsage(extractedUsage ?? payload.usage)
3084
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3030
3085
  });
3031
3086
  break;
3032
3087
  }
@@ -3037,11 +3092,12 @@ var parseClaudeCode = (input, context) => {
3037
3092
  payload.prompt_id ?? String(input.sequenceBase)
3038
3093
  ]);
3039
3094
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3040
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3095
+ const models = generationModels(payload.model, input.sessionModel);
3096
+ factory.build({ type: "generation.start", generationId, model: models.request });
3041
3097
  factory.build({
3042
3098
  type: "generation.end",
3043
3099
  generationId,
3044
- model: UNKNOWN_MODEL,
3100
+ model: models.response,
3045
3101
  outcome: mapStopFailureOutcome(payload.error_type),
3046
3102
  stopReason: payload.error_type,
3047
3103
  ...assistantText === void 0 ? {} : {
@@ -3053,7 +3109,7 @@ var parseClaudeCode = (input, context) => {
3053
3109
  })
3054
3110
  ]
3055
3111
  },
3056
- ...withUsage(extractedUsage ?? payload.usage)
3112
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3057
3113
  });
3058
3114
  break;
3059
3115
  }
@@ -3080,6 +3136,11 @@ var createClaudeCodeAdapter = (options = {}) => ({
3080
3136
  hookResponse: () => SILENT_HOOK_RESPONSE
3081
3137
  });
3082
3138
 
3139
+ // src/providers/claude/transcript.ts
3140
+ import { createHash as createHash2 } from "crypto";
3141
+ import { open, stat } from "fs/promises";
3142
+ import path from "path";
3143
+
3083
3144
  // src/providers/cursor/payload.ts
3084
3145
  import { z as z17 } from "zod";
3085
3146
  var CURSOR_PROVIDER_ID = "cursor";
@@ -5723,9 +5784,9 @@ var resolveDeliveryIdentity = (input) => {
5723
5784
  };
5724
5785
 
5725
5786
  // src/runtime/ids.ts
5726
- import { createHash as createHash2, randomUUID } from "crypto";
5787
+ import { createHash as createHash3, randomUUID } from "crypto";
5727
5788
  var digest = (namespace, parts) => {
5728
- const hash = createHash2("sha256");
5789
+ const hash = createHash3("sha256");
5729
5790
  hash.update(namespace);
5730
5791
  for (const part of parts) {
5731
5792
  hash.update("\0");
@@ -5788,6 +5849,26 @@ var stateValueSchema = z21.discriminatedUnion("kind", [
5788
5849
  z21.strictObject({
5789
5850
  kind: z21.literal("attributes"),
5790
5851
  attributes: attributesSchema
5852
+ }),
5853
+ /**
5854
+ * The model a session last reported, so a later invocation whose payload names
5855
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
5856
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
5857
+ * bounded canonical shape, never a payload fragment.
5858
+ */
5859
+ z21.strictObject({
5860
+ kind: z21.literal("session-model"),
5861
+ model: modelDescriptorSchema
5862
+ }),
5863
+ /**
5864
+ * How far a {@link PayloadEnricher} has read a session's append-only source
5865
+ * (Claude Code's transcript), so the next read starts where the last ended.
5866
+ * `source` is an opaque digest of what was read, never a path.
5867
+ */
5868
+ z21.strictObject({
5869
+ kind: z21.literal("read-cursor"),
5870
+ source: z21.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
5871
+ offset: z21.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
5791
5872
  })
5792
5873
  ]);
5793
5874
  var stateRecordSchema = z21.strictObject({
@@ -5814,16 +5895,16 @@ var createNullLogger = () => ({
5814
5895
  });
5815
5896
 
5816
5897
  // src/runtime/target-resolution.ts
5817
- import * as path from "path";
5898
+ import * as path2 from "path";
5818
5899
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
5819
5900
  var absolutePathsOf = (hint) => {
5820
- const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
5901
+ const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
5821
5902
  const resolved = [];
5822
5903
  for (const candidate of hint.paths) {
5823
- if (path.isAbsolute(candidate)) {
5824
- resolved.push(path.resolve(candidate));
5904
+ if (path2.isAbsolute(candidate)) {
5905
+ resolved.push(path2.resolve(candidate));
5825
5906
  } else if (base !== void 0) {
5826
- resolved.push(path.resolve(base, candidate));
5907
+ resolved.push(path2.resolve(base, candidate));
5827
5908
  } else {
5828
5909
  return void 0;
5829
5910
  }
@@ -5987,6 +6068,22 @@ var usageScopeOf = (event3) => {
5987
6068
  }
5988
6069
  };
5989
6070
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
6071
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
6072
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
6073
+ var UNKNOWN_MODEL_ID = "unknown";
6074
+ var latestSessionModel = (events) => {
6075
+ let latest;
6076
+ for (const event3 of events) {
6077
+ if (event3.subagentId !== void 0) {
6078
+ continue;
6079
+ }
6080
+ if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
6081
+ latest = event3.model;
6082
+ }
6083
+ }
6084
+ return latest;
6085
+ };
6086
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
5990
6087
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
5991
6088
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
5992
6089
  var createOtelHook = (deps) => {
@@ -6034,6 +6131,66 @@ var createOtelHook = (deps) => {
6034
6131
  return 0;
6035
6132
  }
6036
6133
  };
6134
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
6135
+ let current = payload;
6136
+ for (const enricher of deps.payloadEnrichers ?? []) {
6137
+ if (enricher.providerId !== providerId) {
6138
+ continue;
6139
+ }
6140
+ const key = readCursorKey(enricher.id, sessionId);
6141
+ let cursor;
6142
+ try {
6143
+ const record = await deps.stateStore.read(key);
6144
+ if (record?.value.kind === "read-cursor") {
6145
+ cursor = { source: record.value.source, offset: record.value.offset };
6146
+ }
6147
+ } catch (thrown) {
6148
+ diagnostics.push(
6149
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
6150
+ );
6151
+ continue;
6152
+ }
6153
+ let result;
6154
+ try {
6155
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
6156
+ } catch (thrown) {
6157
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
6158
+ "enricher.id": enricher.id,
6159
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
6160
+ });
6161
+ continue;
6162
+ }
6163
+ current = result.payload;
6164
+ if (result.notes !== void 0 && result.notes.length > 0) {
6165
+ logger.debug("payload enricher notes", {
6166
+ "enricher.id": enricher.id,
6167
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
6168
+ });
6169
+ }
6170
+ const next = result.cursor;
6171
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
6172
+ try {
6173
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
6174
+ } catch (thrown) {
6175
+ diagnostics.push(
6176
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
6177
+ );
6178
+ }
6179
+ }
6180
+ }
6181
+ return current;
6182
+ };
6183
+ const readSessionModel = async (sessionId, diagnostics) => {
6184
+ try {
6185
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
6186
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
6187
+ } catch (thrown) {
6188
+ diagnostics.push(
6189
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
6190
+ );
6191
+ return void 0;
6192
+ }
6193
+ };
6037
6194
  const deriveUsage = async (events, diagnostics, suppress, series) => {
6038
6195
  const observations = [];
6039
6196
  for (const event3 of events) {
@@ -6354,10 +6511,19 @@ var createOtelHook = (deps) => {
6354
6511
  const identity = resolution.identity;
6355
6512
  const prepare = async () => {
6356
6513
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
6514
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
6515
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
6357
6516
  let parsed;
6358
6517
  try {
6359
6518
  parsed = adapter.parse(
6360
- { ...detectionInput, detection, identity, sequenceBase },
6519
+ {
6520
+ ...detectionInput,
6521
+ payload,
6522
+ detection,
6523
+ identity,
6524
+ sequenceBase,
6525
+ ...sessionModel === void 0 ? {} : { sessionModel }
6526
+ },
6361
6527
  providerContext
6362
6528
  );
6363
6529
  } catch (thrown) {
@@ -6467,6 +6633,23 @@ var createOtelHook = (deps) => {
6467
6633
  })
6468
6634
  );
6469
6635
  }
6636
+ const reportedModel = latestSessionModel(screened.kept);
6637
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
6638
+ try {
6639
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
6640
+ kind: "session-model",
6641
+ model: reportedModel
6642
+ });
6643
+ } catch (thrown) {
6644
+ diagnostics.push(
6645
+ errorInfoFromThrown(thrown, {
6646
+ code: "state-store-failure",
6647
+ phase: "state",
6648
+ occurredAt: clock.now()
6649
+ })
6650
+ );
6651
+ }
6652
+ }
6470
6653
  }
6471
6654
  return {
6472
6655
  kind: "ready",
@@ -7229,7 +7412,8 @@ var createTestHook = (options = {}) => {
7229
7412
  privacy,
7230
7413
  logger,
7231
7414
  ...options.worktreeLocator === void 0 ? {} : { worktreeLocator: options.worktreeLocator },
7232
- ...options.targetResolutionBudgetMillis === void 0 ? {} : { targetResolutionBudgetMillis: options.targetResolutionBudgetMillis }
7415
+ ...options.targetResolutionBudgetMillis === void 0 ? {} : { targetResolutionBudgetMillis: options.targetResolutionBudgetMillis },
7416
+ ...options.payloadEnrichers === void 0 ? {} : { payloadEnrichers: options.payloadEnrichers }
7233
7417
  });
7234
7418
  return { hook, sink, stateStore, clock, ids, privacy, logger, registry, config };
7235
7419
  };