@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/index.js CHANGED
@@ -876,6 +876,13 @@ var generationEndEventSchema = event({
876
876
  stopReason: nonEmptyStringSchema.optional(),
877
877
  durationMillis: durationMillisSchema.optional(),
878
878
  usage: canonicalUsageSchema.optional(),
879
+ /**
880
+ * True when `usage` is known to cover only part of the generation (for
881
+ * example the last model request of a multi-request turn); false when the
882
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
883
+ * without `usage`.
884
+ */
885
+ usagePartial: z9.boolean().optional(),
879
886
  cost: costFactsSchema.optional(),
880
887
  outputContent: contentFactsSchema.optional()
881
888
  });
@@ -1345,11 +1352,11 @@ var createPrivacyService = (policyInput) => {
1345
1352
  };
1346
1353
  const flattenToAttributes = (value, prefix) => {
1347
1354
  const attributes = {};
1348
- const walk = (current, path9) => {
1355
+ const walk = (current, path10) => {
1349
1356
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1350
1357
  const primitive = toAttributePrimitive(current);
1351
1358
  if (primitive !== void 0) {
1352
- attributes[path9] = primitive;
1359
+ attributes[path10] = primitive;
1353
1360
  }
1354
1361
  return;
1355
1362
  }
@@ -1368,16 +1375,16 @@ var createPrivacyService = (policyInput) => {
1368
1375
  primitives.push(entryPrimitive);
1369
1376
  }
1370
1377
  if (uniform) {
1371
- attributes[path9] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1378
+ attributes[path10] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1372
1379
  return;
1373
1380
  }
1374
1381
  for (const [index, entry] of current.entries()) {
1375
- walk(entry, `${path9}.${index}`);
1382
+ walk(entry, `${path10}.${index}`);
1376
1383
  }
1377
1384
  return;
1378
1385
  }
1379
1386
  for (const [key, entry] of Object.entries(current)) {
1380
- walk(entry, path9 === "" ? key : `${path9}.${key}`);
1387
+ walk(entry, path10 === "" ? key : `${path10}.${key}`);
1381
1388
  }
1382
1389
  };
1383
1390
  walk(value, prefix);
@@ -2079,11 +2086,18 @@ var diagnosticsPolicySchema = z14.strictObject({
2079
2086
  /** Emit `error.raised` events for contained failures. */
2080
2087
  emitErrorEvents: z14.boolean()
2081
2088
  });
2089
+ var providersPolicySchema = z14.strictObject({
2090
+ claudeCode: z14.strictObject({
2091
+ readTranscriptUsage: z14.boolean()
2092
+ }).optional()
2093
+ });
2082
2094
  var otelHookConfigSchema = z14.strictObject({
2083
2095
  exporter: exporterPolicySchema,
2084
2096
  privacy: privacyPolicySchema,
2085
2097
  detection: detectionPolicySchema,
2086
- diagnostics: diagnosticsPolicySchema
2098
+ diagnostics: diagnosticsPolicySchema,
2099
+ /** Optional so a hand-built configuration from before it existed stays valid. */
2100
+ providers: providersPolicySchema.optional()
2087
2101
  });
2088
2102
  var otelHookConfigPatchSchema = z14.strictObject({
2089
2103
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -2095,7 +2109,10 @@ var otelHookConfigPatchSchema = z14.strictObject({
2095
2109
  }).optional(),
2096
2110
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
2097
2111
  detection: detectionPolicySchema.partial().optional(),
2098
- diagnostics: diagnosticsPolicySchema.partial().optional()
2112
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
2113
+ providers: z14.strictObject({
2114
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2115
+ }).partial().optional()
2099
2116
  });
2100
2117
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
2101
2118
  enabled: true,
@@ -2118,24 +2135,29 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2118
2135
  logLevel: "warn",
2119
2136
  emitErrorEvents: true
2120
2137
  });
2138
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2139
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
2140
+ });
2121
2141
  var DEFAULT_CONFIG = Object.freeze({
2122
2142
  exporter: DEFAULT_EXPORTER_POLICY,
2123
2143
  privacy: DEFAULT_PRIVACY_POLICY,
2124
2144
  detection: DEFAULT_DETECTION_POLICY,
2125
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
2145
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
2146
+ providers: DEFAULT_PROVIDERS_POLICY
2126
2147
  });
2148
+ var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2127
2149
 
2128
2150
  // src/config/resolve.ts
2129
2151
  import { z as z15 } from "zod";
2130
2152
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2131
2153
  var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
2132
2154
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2133
- var mergeLeaf = (target, patch, source, provenance, path9) => {
2155
+ var mergeLeaf = (target, patch, source, provenance, path10) => {
2134
2156
  for (const [key, value] of Object.entries(patch)) {
2135
2157
  if (value === void 0) {
2136
2158
  continue;
2137
2159
  }
2138
- const childPath = path9 === "" ? key : `${path9}.${key}`;
2160
+ const childPath = path10 === "" ? key : `${path10}.${key}`;
2139
2161
  const existing = target[key];
2140
2162
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2141
2163
  const child = { ...existing ?? {} };
@@ -2149,14 +2171,14 @@ var mergeLeaf = (target, patch, source, provenance, path9) => {
2149
2171
  };
2150
2172
  var initialProvenance = (config) => {
2151
2173
  const provenance = {};
2152
- const walk = (value, path9) => {
2174
+ const walk = (value, path10) => {
2153
2175
  if (isPlainObject(value)) {
2154
2176
  for (const [key, child] of Object.entries(value)) {
2155
- walk(child, path9 === "" ? key : `${path9}.${key}`);
2177
+ walk(child, path10 === "" ? key : `${path10}.${key}`);
2156
2178
  }
2157
2179
  return;
2158
2180
  }
2159
- provenance[path9] = "defaults";
2181
+ provenance[path10] = "defaults";
2160
2182
  };
2161
2183
  walk(config, "");
2162
2184
  return provenance;
@@ -2371,7 +2393,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
2371
2393
  maxArrayLength: "OTEL_HOOK_MAX_ARRAY_LENGTH",
2372
2394
  maxEventsPerInvocation: "OTEL_HOOK_MAX_EVENTS_PER_INVOCATION",
2373
2395
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
2374
- logLevel: "OTEL_HOOK_LOG_LEVEL"
2396
+ logLevel: "OTEL_HOOK_LOG_LEVEL",
2397
+ /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
2398
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
2375
2399
  });
2376
2400
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
2377
2401
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -2548,11 +2572,14 @@ var parseEnvironmentConfig = (env) => {
2548
2572
  };
2549
2573
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
2550
2574
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
2575
+ const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
2576
+ const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
2551
2577
  const patch = {
2552
2578
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
2553
2579
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
2554
2580
  ...Object.keys(detection).length === 0 ? {} : { detection },
2555
- ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
2581
+ ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
2582
+ ...Object.keys(providers).length === 0 ? {} : { providers }
2556
2583
  };
2557
2584
  return { patch, warnings };
2558
2585
  };
@@ -3073,7 +3100,25 @@ var stopPayloadSchema = z17.object({
3073
3100
  * the former without suppressing the latter.
3074
3101
  */
3075
3102
  stop_hook_active: z17.boolean().optional(),
3076
- usage: claudeUsageSchema.optional()
3103
+ usage: claudeUsageSchema.optional(),
3104
+ /**
3105
+ * The model that answered this turn — harness-supplied, never upstream.
3106
+ *
3107
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
3108
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
3109
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
3110
+ * with `usage`, and it becomes the generation's response model. An unusable
3111
+ * value (empty, over 256 characters, not a string) is dropped rather than
3112
+ * failing the whole payload: the turn is still worth reporting without it.
3113
+ */
3114
+ model: z17.string().min(1).max(256).optional().catch(void 0),
3115
+ /**
3116
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
3117
+ * turn. `true` when it is the last model request alone (the tail fallback),
3118
+ * `false` when it sums every request since the previous stop. Exported as
3119
+ * `otelhook.usage.partial`; absent means the attacher did not say.
3120
+ */
3121
+ usage_partial: z17.boolean().optional().catch(void 0)
3077
3122
  });
3078
3123
  var stopFailurePayloadSchema = z17.object({
3079
3124
  ...commonFields,
@@ -3085,7 +3130,11 @@ var stopFailurePayloadSchema = z17.object({
3085
3130
  */
3086
3131
  error_type: z17.string().min(1),
3087
3132
  error_message: z17.string().optional(),
3088
- usage: claudeUsageSchema.optional()
3133
+ usage: claudeUsageSchema.optional(),
3134
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
3135
+ model: z17.string().min(1).max(256).optional().catch(void 0),
3136
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
3137
+ usage_partial: z17.boolean().optional().catch(void 0)
3089
3138
  });
3090
3139
  var claudeHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
3091
3140
  sessionStartPayloadSchema,
@@ -3617,6 +3666,13 @@ var inferToolKind = (toolName) => {
3617
3666
 
3618
3667
  // src/providers/claude/events.ts
3619
3668
  var UNKNOWN_MODEL = { modelId: "unknown" };
3669
+ var generationModels = (attached, sessionModel) => {
3670
+ const turnModel = attached === void 0 ? void 0 : { modelId: attached };
3671
+ return {
3672
+ request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
3673
+ response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
3674
+ };
3675
+ };
3620
3676
  var SESSION_END_REASON = Object.freeze({
3621
3677
  completed: "completed",
3622
3678
  aborted: "aborted",
@@ -3683,6 +3739,10 @@ var parseClaudeCode = (input, context) => {
3683
3739
  warnings.push(...normalized.warnings);
3684
3740
  return applyUsage(normalized);
3685
3741
  };
3742
+ const withPartialUsage = (usage, partial) => {
3743
+ const applied = withUsage(usage);
3744
+ return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
3745
+ };
3686
3746
  switch (payload.hook_event_name) {
3687
3747
  case "SessionStart":
3688
3748
  factory.build({
@@ -3795,11 +3855,12 @@ var parseClaudeCode = (input, context) => {
3795
3855
  payload.prompt_id ?? String(input.sequenceBase)
3796
3856
  ]);
3797
3857
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3798
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3858
+ const models = generationModels(payload.model, input.sessionModel);
3859
+ factory.build({ type: "generation.start", generationId, model: models.request });
3799
3860
  factory.build({
3800
3861
  type: "generation.end",
3801
3862
  generationId,
3802
- model: UNKNOWN_MODEL,
3863
+ model: models.response,
3803
3864
  outcome: "ok",
3804
3865
  // Always a response fact: a body when Claude sent text, otherwise a
3805
3866
  // zero-length omitted fact so the log mapping can emit metadata_only
@@ -3811,7 +3872,7 @@ var parseClaudeCode = (input, context) => {
3811
3872
  text: assistantText
3812
3873
  })
3813
3874
  ],
3814
- ...withUsage(extractedUsage ?? payload.usage)
3875
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3815
3876
  });
3816
3877
  break;
3817
3878
  }
@@ -3822,11 +3883,12 @@ var parseClaudeCode = (input, context) => {
3822
3883
  payload.prompt_id ?? String(input.sequenceBase)
3823
3884
  ]);
3824
3885
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3825
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3886
+ const models = generationModels(payload.model, input.sessionModel);
3887
+ factory.build({ type: "generation.start", generationId, model: models.request });
3826
3888
  factory.build({
3827
3889
  type: "generation.end",
3828
3890
  generationId,
3829
- model: UNKNOWN_MODEL,
3891
+ model: models.response,
3830
3892
  outcome: mapStopFailureOutcome(payload.error_type),
3831
3893
  stopReason: payload.error_type,
3832
3894
  ...assistantText === void 0 ? {} : {
@@ -3838,7 +3900,7 @@ var parseClaudeCode = (input, context) => {
3838
3900
  })
3839
3901
  ]
3840
3902
  },
3841
- ...withUsage(extractedUsage ?? payload.usage)
3903
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3842
3904
  });
3843
3905
  break;
3844
3906
  }
@@ -3865,6 +3927,339 @@ var createClaudeCodeAdapter = (options = {}) => ({
3865
3927
  hookResponse: () => SILENT_HOOK_RESPONSE
3866
3928
  });
3867
3929
 
3930
+ // src/providers/claude/transcript.ts
3931
+ import { createHash as createHash2 } from "crypto";
3932
+ import { open, stat } from "fs/promises";
3933
+ import path from "path";
3934
+ var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
3935
+ var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
3936
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
3937
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
3938
+ var MIN_TAIL_BYTES = 65536;
3939
+ var MAX_TAIL_BYTES = 16777216;
3940
+ var MAX_RANGE_BYTES = 67108864;
3941
+ var MIN_TIMEOUT_MILLIS = 10;
3942
+ var MAX_TIMEOUT_MILLIS = 5e3;
3943
+ var MAX_MODEL_ID_LENGTH = 256;
3944
+ var MAX_REQUESTS_PER_RANGE = 1e4;
3945
+ var SYNTHETIC_MODEL = "<synthetic>";
3946
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
3947
+ var clamp = (value, fallback, min, max) => {
3948
+ if (value === void 0 || !Number.isFinite(value)) {
3949
+ return fallback;
3950
+ }
3951
+ return Math.min(max, Math.max(min, Math.floor(value)));
3952
+ };
3953
+ var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3954
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
3955
+ var assistantRecordOf = (line) => {
3956
+ if (!line.includes('"assistant"')) {
3957
+ return void 0;
3958
+ }
3959
+ let parsed;
3960
+ try {
3961
+ parsed = JSON.parse(line);
3962
+ } catch {
3963
+ return void 0;
3964
+ }
3965
+ const record = asRecord5(parsed);
3966
+ if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
3967
+ return void 0;
3968
+ }
3969
+ const message = asRecord5(record.message);
3970
+ if (message === void 0 || message.model === SYNTHETIC_MODEL) {
3971
+ return void 0;
3972
+ }
3973
+ const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
3974
+ const usage = coerceClaudeUsage(message.usage);
3975
+ if (model === void 0 && usage === void 0) {
3976
+ return void 0;
3977
+ }
3978
+ const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
3979
+ return {
3980
+ ...id === void 0 ? {} : { id },
3981
+ ...model === void 0 ? {} : { model },
3982
+ ...usage === void 0 ? {} : { usage }
3983
+ };
3984
+ };
3985
+ var cacheCreationOf = (usage) => usage.cache_creation_input_tokens ?? (usage.cache_creation === void 0 ? 0 : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));
3986
+ var sumUsage = (usages) => {
3987
+ let input = 0;
3988
+ let output = 0;
3989
+ let cacheRead = 0;
3990
+ let cacheCreation = 0;
3991
+ for (const usage of usages) {
3992
+ input += usage.input_tokens;
3993
+ output += usage.output_tokens;
3994
+ cacheRead += usage.cache_read_input_tokens ?? 0;
3995
+ cacheCreation += cacheCreationOf(usage);
3996
+ }
3997
+ return {
3998
+ input_tokens: input,
3999
+ output_tokens: output,
4000
+ cache_read_input_tokens: cacheRead,
4001
+ cache_creation_input_tokens: cacheCreation
4002
+ };
4003
+ };
4004
+ var withTimeout = async (work, timeoutMillis, onError) => {
4005
+ let timer;
4006
+ const timeout = new Promise((resolve5) => {
4007
+ timer = setTimeout(() => {
4008
+ resolve5(TIMED_OUT);
4009
+ }, timeoutMillis);
4010
+ timer.unref();
4011
+ });
4012
+ try {
4013
+ return await Promise.race([work.catch(() => onError), timeout]);
4014
+ } finally {
4015
+ clearTimeout(timer);
4016
+ }
4017
+ };
4018
+ var withRegularFile = async (transcriptPath, body) => {
4019
+ let info;
4020
+ try {
4021
+ info = await stat(transcriptPath);
4022
+ } catch {
4023
+ return { status: "unavailable", reason: "unreadable" };
4024
+ }
4025
+ if (!info.isFile()) {
4026
+ return { status: "unavailable", reason: "not-a-file" };
4027
+ }
4028
+ let handle;
4029
+ try {
4030
+ handle = await open(transcriptPath, "r");
4031
+ } catch {
4032
+ return { status: "unavailable", reason: "unreadable" };
4033
+ }
4034
+ try {
4035
+ const { size } = await handle.stat();
4036
+ return await body(handle, size);
4037
+ } catch {
4038
+ return { status: "unavailable", reason: "unreadable" };
4039
+ } finally {
4040
+ await handle.close().catch(() => void 0);
4041
+ }
4042
+ };
4043
+ var readBytes = async (handle, start, length) => {
4044
+ const buffer = Buffer.alloc(length);
4045
+ let filled = 0;
4046
+ while (filled < length) {
4047
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
4048
+ if (bytesRead === 0) {
4049
+ break;
4050
+ }
4051
+ filled += bytesRead;
4052
+ }
4053
+ return buffer.subarray(0, filled);
4054
+ };
4055
+ var completeLinesEnd = (bytes, start) => {
4056
+ const lastNewline = bytes.lastIndexOf(10);
4057
+ return lastNewline < 0 ? start : start + lastNewline + 1;
4058
+ };
4059
+ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4060
+ const length = Math.min(size, maxTailBytes);
4061
+ const start = size - length;
4062
+ const bytes = await readBytes(handle, start, length);
4063
+ const endOffset = completeLinesEnd(bytes, start);
4064
+ const lines = bytes.toString("utf8").split("\n");
4065
+ if (start > 0) {
4066
+ lines.shift();
4067
+ }
4068
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
4069
+ const record = assistantRecordOf((lines[index] ?? "").trim());
4070
+ if (record !== void 0) {
4071
+ return {
4072
+ turn: {
4073
+ status: "found",
4074
+ ...record.model === void 0 ? {} : { model: record.model },
4075
+ ...record.usage === void 0 ? {} : { usage: record.usage }
4076
+ },
4077
+ endOffset
4078
+ };
4079
+ }
4080
+ }
4081
+ return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4082
+ });
4083
+ var boundedTail = async (transcriptPath, options) => withTimeout(
4084
+ readTail(
4085
+ transcriptPath,
4086
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4087
+ ),
4088
+ clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4089
+ { status: "unavailable", reason: "unreadable" }
4090
+ );
4091
+ var readClaudeTranscriptTurn = async (transcriptPath, options = {}) => {
4092
+ if (!isTranscriptPath(transcriptPath)) {
4093
+ return { status: "unavailable", reason: "invalid-path" };
4094
+ }
4095
+ const read = await boundedTail(transcriptPath, options);
4096
+ if (read === TIMED_OUT) {
4097
+ return { status: "unavailable", reason: "timeout" };
4098
+ }
4099
+ return "turn" in read ? read.turn : read;
4100
+ };
4101
+ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
4102
+ if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
4103
+ return { status: "unavailable", reason: "invalid-path" };
4104
+ }
4105
+ const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
4106
+ const timeoutMillis = clamp(
4107
+ options.rangeTimeoutMillis,
4108
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
4109
+ MIN_TIMEOUT_MILLIS,
4110
+ MAX_TIMEOUT_MILLIS
4111
+ );
4112
+ const work = withRegularFile(transcriptPath, async (handle, size) => {
4113
+ if (size < fromOffset) {
4114
+ return { status: "unavailable", reason: "truncated" };
4115
+ }
4116
+ if (size - fromOffset > maxRangeBytes) {
4117
+ return { status: "unavailable", reason: "over-cap" };
4118
+ }
4119
+ const bytes = await readBytes(handle, fromOffset, size - fromOffset);
4120
+ const endOffset = completeLinesEnd(bytes, fromOffset);
4121
+ const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
4122
+ const requests = /* @__PURE__ */ new Map();
4123
+ let anonymous = 0;
4124
+ let model;
4125
+ for (const line of complete.split("\n")) {
4126
+ const record = assistantRecordOf(line.trim());
4127
+ if (record === void 0) {
4128
+ continue;
4129
+ }
4130
+ if (record.model !== void 0) {
4131
+ model = record.model;
4132
+ }
4133
+ anonymous += record.id === void 0 ? 1 : 0;
4134
+ requests.set(record.id ?? `#${String(anonymous)}`, record);
4135
+ if (requests.size > MAX_REQUESTS_PER_RANGE) {
4136
+ return { status: "unavailable", reason: "over-cap" };
4137
+ }
4138
+ }
4139
+ const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
4140
+ return {
4141
+ status: "found",
4142
+ ...model === void 0 ? {} : { model },
4143
+ ...usages.length === 0 ? {} : { usage: sumUsage(usages) },
4144
+ requestCount: requests.size,
4145
+ endOffset
4146
+ };
4147
+ });
4148
+ const result = await withTimeout(work, timeoutMillis, {
4149
+ status: "unavailable",
4150
+ reason: "unreadable"
4151
+ });
4152
+ return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
4153
+ };
4154
+ var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
4155
+ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
4156
+ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
4157
+ var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
4158
+ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
4159
+ const record = asRecord5(payload);
4160
+ if (record === void 0) {
4161
+ return payload;
4162
+ }
4163
+ const eventName = eventNameOf(record);
4164
+ if (typeof eventName !== "string" || !STOP_EVENTS.has(eventName)) {
4165
+ return payload;
4166
+ }
4167
+ const transcriptPath = transcriptPathOf(record);
4168
+ if (typeof transcriptPath !== "string") {
4169
+ return payload;
4170
+ }
4171
+ const needsModel = record.model === void 0;
4172
+ const needsUsage = !hasUsage(record);
4173
+ if (!needsModel && !needsUsage) {
4174
+ return payload;
4175
+ }
4176
+ const turn = await readClaudeTranscriptTurn(transcriptPath, options);
4177
+ if (turn.status !== "found") {
4178
+ return payload;
4179
+ }
4180
+ return {
4181
+ ...record,
4182
+ ...needsModel && turn.model !== void 0 ? { model: turn.model } : {},
4183
+ ...needsUsage && turn.usage !== void 0 ? { usage: turn.usage, usage_partial: true } : {}
4184
+ };
4185
+ };
4186
+ var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4187
+ var sourceDigest = (transcriptPath) => createHash2("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4188
+ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4189
+ const fileSize = async (transcriptPath) => {
4190
+ try {
4191
+ const info = await stat(transcriptPath);
4192
+ return info.isFile() ? info.size : void 0;
4193
+ } catch (thrown) {
4194
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
4195
+ }
4196
+ };
4197
+ const enrich = async (input) => {
4198
+ const unchanged = { payload: input.payload };
4199
+ const record = asRecord5(input.payload);
4200
+ if (record === void 0) {
4201
+ return unchanged;
4202
+ }
4203
+ const eventName = eventNameOf(record);
4204
+ const transcriptPath = transcriptPathOf(record);
4205
+ if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4206
+ return unchanged;
4207
+ }
4208
+ const source = sourceDigest(transcriptPath);
4209
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
4210
+ if (eventName === "SessionStart") {
4211
+ if (cursor !== void 0) {
4212
+ return unchanged;
4213
+ }
4214
+ const size = await fileSize(transcriptPath);
4215
+ if (size === void 0) {
4216
+ return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
4217
+ }
4218
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
4219
+ }
4220
+ if (!STOP_EVENTS.has(eventName)) {
4221
+ return unchanged;
4222
+ }
4223
+ if (hasUsage(record)) {
4224
+ const size = await fileSize(transcriptPath);
4225
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4226
+ }
4227
+ const attach = (model, usage, partial) => ({
4228
+ ...record,
4229
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4230
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4231
+ });
4232
+ if (cursor !== void 0) {
4233
+ const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4234
+ if (range.status === "found") {
4235
+ return {
4236
+ payload: attach(range.model, range.usage, false),
4237
+ cursor: { source, offset: range.endOffset },
4238
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4239
+ };
4240
+ }
4241
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4242
+ return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4243
+ }
4244
+ }
4245
+ const tail = await boundedTail(transcriptPath, options);
4246
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4247
+ return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4248
+ }
4249
+ const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4250
+ return {
4251
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4252
+ cursor: { source, offset: tail.endOffset },
4253
+ notes: [`${why}; attached the last request only (usage_partial)`]
4254
+ };
4255
+ };
4256
+ return Object.freeze({
4257
+ id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4258
+ providerId: CLAUDE_CODE_PROVIDER_ID,
4259
+ enrich
4260
+ });
4261
+ };
4262
+
3868
4263
  // src/providers/cursor/payload.ts
3869
4264
  import { z as z18 } from "zod";
3870
4265
  var CURSOR_PROVIDER_ID = "cursor";
@@ -5019,7 +5414,7 @@ var codexDeliveryIdentity = (input) => {
5019
5414
 
5020
5415
  // src/providers/codex/target.ts
5021
5416
  var PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/;
5022
- var asRecord5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5417
+ var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5023
5418
  var nonEmptyString2 = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
5024
5419
  var commandText = (input) => {
5025
5420
  const command = input?.command ?? input?.cmd;
@@ -5046,7 +5441,7 @@ var patchTextOf = (toolName, input) => {
5046
5441
  if (typeof input === "string") {
5047
5442
  return /^apply[_-]?patch$/i.test(toolName) ? input : void 0;
5048
5443
  }
5049
- const record = asRecord5(input);
5444
+ const record = asRecord6(input);
5050
5445
  if (/^apply[_-]?patch$/i.test(toolName)) {
5051
5446
  return nonEmptyString2(record?.patch) ?? nonEmptyString2(record?.input) ?? commandText(record);
5052
5447
  }
@@ -5054,7 +5449,7 @@ var patchTextOf = (toolName, input) => {
5054
5449
  return command !== void 0 && /^\s*apply_patch\b/.test(command) ? command : void 0;
5055
5450
  };
5056
5451
  var codexTargetHint = (toolName, toolInput, cwd) => {
5057
- const record = asRecord5(toolInput);
5452
+ const record = asRecord6(toolInput);
5058
5453
  const workdir = nonEmptyString2(record?.workdir);
5059
5454
  const base = workdir ?? cwd;
5060
5455
  const patch = patchTextOf(toolName, toolInput);
@@ -5136,7 +5531,7 @@ var CODEX_CAPABILITIES = Object.freeze({
5136
5531
  // compaction callbacks do not. See `./delivery.ts` for which and why.
5137
5532
  deliveryIdentifier: "partial"
5138
5533
  });
5139
- var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5534
+ var asRecord7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5140
5535
  var hasExactMarker = (payload) => {
5141
5536
  if (payload.codex_version !== void 0) {
5142
5537
  return true;
@@ -5229,7 +5624,7 @@ var outcomeFromToolResponse = (toolResponse) => {
5229
5624
  if (toolResponse === void 0) {
5230
5625
  return "unknown";
5231
5626
  }
5232
- const record = asRecord6(toolResponse);
5627
+ const record = asRecord7(toolResponse);
5233
5628
  if (record === void 0) {
5234
5629
  return "ok";
5235
5630
  }
@@ -6527,6 +6922,26 @@ var stateValueSchema = z22.discriminatedUnion("kind", [
6527
6922
  z22.strictObject({
6528
6923
  kind: z22.literal("attributes"),
6529
6924
  attributes: attributesSchema
6925
+ }),
6926
+ /**
6927
+ * The model a session last reported, so a later invocation whose payload names
6928
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
6929
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
6930
+ * bounded canonical shape, never a payload fragment.
6931
+ */
6932
+ z22.strictObject({
6933
+ kind: z22.literal("session-model"),
6934
+ model: modelDescriptorSchema
6935
+ }),
6936
+ /**
6937
+ * How far a {@link PayloadEnricher} has read a session's append-only source
6938
+ * (Claude Code's transcript), so the next read starts where the last ended.
6939
+ * `source` is an opaque digest of what was read, never a path.
6940
+ */
6941
+ z22.strictObject({
6942
+ kind: z22.literal("read-cursor"),
6943
+ source: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6944
+ offset: z22.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
6530
6945
  })
6531
6946
  ]);
6532
6947
  var stateRecordSchema = z22.strictObject({
@@ -6572,9 +6987,9 @@ var createFixedClock = (options = {}) => {
6572
6987
  };
6573
6988
 
6574
6989
  // src/runtime/ids.ts
6575
- import { createHash as createHash2, randomUUID } from "crypto";
6990
+ import { createHash as createHash3, randomUUID } from "crypto";
6576
6991
  var digest = (namespace, parts) => {
6577
- const hash = createHash2("sha256");
6992
+ const hash = createHash3("sha256");
6578
6993
  hash.update(namespace);
6579
6994
  for (const part of parts) {
6580
6995
  hash.update("\0");
@@ -6810,16 +7225,16 @@ var resolveDeliveryIdentity = (input) => {
6810
7225
  import { z as z23 } from "zod";
6811
7226
 
6812
7227
  // src/runtime/target-resolution.ts
6813
- import * as path from "path";
7228
+ import * as path2 from "path";
6814
7229
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
6815
7230
  var absolutePathsOf = (hint) => {
6816
- const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
7231
+ const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
6817
7232
  const resolved = [];
6818
7233
  for (const candidate of hint.paths) {
6819
- if (path.isAbsolute(candidate)) {
6820
- resolved.push(path.resolve(candidate));
7234
+ if (path2.isAbsolute(candidate)) {
7235
+ resolved.push(path2.resolve(candidate));
6821
7236
  } else if (base !== void 0) {
6822
- resolved.push(path.resolve(base, candidate));
7237
+ resolved.push(path2.resolve(base, candidate));
6823
7238
  } else {
6824
7239
  return void 0;
6825
7240
  }
@@ -7035,6 +7450,22 @@ var usageScopeOf = (event3) => {
7035
7450
  }
7036
7451
  };
7037
7452
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
7453
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
7454
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
7455
+ var UNKNOWN_MODEL_ID = "unknown";
7456
+ var latestSessionModel = (events) => {
7457
+ let latest;
7458
+ for (const event3 of events) {
7459
+ if (event3.subagentId !== void 0) {
7460
+ continue;
7461
+ }
7462
+ if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
7463
+ latest = event3.model;
7464
+ }
7465
+ }
7466
+ return latest;
7467
+ };
7468
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
7038
7469
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
7039
7470
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
7040
7471
  var createOtelHook = (deps) => {
@@ -7082,6 +7513,66 @@ var createOtelHook = (deps) => {
7082
7513
  return 0;
7083
7514
  }
7084
7515
  };
7516
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
7517
+ let current = payload;
7518
+ for (const enricher of deps.payloadEnrichers ?? []) {
7519
+ if (enricher.providerId !== providerId) {
7520
+ continue;
7521
+ }
7522
+ const key = readCursorKey(enricher.id, sessionId);
7523
+ let cursor;
7524
+ try {
7525
+ const record = await deps.stateStore.read(key);
7526
+ if (record?.value.kind === "read-cursor") {
7527
+ cursor = { source: record.value.source, offset: record.value.offset };
7528
+ }
7529
+ } catch (thrown) {
7530
+ diagnostics.push(
7531
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
7532
+ );
7533
+ continue;
7534
+ }
7535
+ let result;
7536
+ try {
7537
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
7538
+ } catch (thrown) {
7539
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
7540
+ "enricher.id": enricher.id,
7541
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
7542
+ });
7543
+ continue;
7544
+ }
7545
+ current = result.payload;
7546
+ if (result.notes !== void 0 && result.notes.length > 0) {
7547
+ logger.debug("payload enricher notes", {
7548
+ "enricher.id": enricher.id,
7549
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
7550
+ });
7551
+ }
7552
+ const next = result.cursor;
7553
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
7554
+ try {
7555
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
7556
+ } catch (thrown) {
7557
+ diagnostics.push(
7558
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
7559
+ );
7560
+ }
7561
+ }
7562
+ }
7563
+ return current;
7564
+ };
7565
+ const readSessionModel = async (sessionId, diagnostics) => {
7566
+ try {
7567
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
7568
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
7569
+ } catch (thrown) {
7570
+ diagnostics.push(
7571
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
7572
+ );
7573
+ return void 0;
7574
+ }
7575
+ };
7085
7576
  const deriveUsage = async (events, diagnostics, suppress, series) => {
7086
7577
  const observations = [];
7087
7578
  for (const event3 of events) {
@@ -7402,10 +7893,19 @@ var createOtelHook = (deps) => {
7402
7893
  const identity = resolution.identity;
7403
7894
  const prepare = async () => {
7404
7895
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
7896
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
7897
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
7405
7898
  let parsed;
7406
7899
  try {
7407
7900
  parsed = adapter.parse(
7408
- { ...detectionInput, detection, identity, sequenceBase },
7901
+ {
7902
+ ...detectionInput,
7903
+ payload,
7904
+ detection,
7905
+ identity,
7906
+ sequenceBase,
7907
+ ...sessionModel === void 0 ? {} : { sessionModel }
7908
+ },
7409
7909
  providerContext
7410
7910
  );
7411
7911
  } catch (thrown) {
@@ -7515,6 +8015,23 @@ var createOtelHook = (deps) => {
7515
8015
  })
7516
8016
  );
7517
8017
  }
8018
+ const reportedModel = latestSessionModel(screened.kept);
8019
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
8020
+ try {
8021
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
8022
+ kind: "session-model",
8023
+ model: reportedModel
8024
+ });
8025
+ } catch (thrown) {
8026
+ diagnostics.push(
8027
+ errorInfoFromThrown(thrown, {
8028
+ code: "state-store-failure",
8029
+ phase: "state",
8030
+ occurredAt: clock.now()
8031
+ })
8032
+ );
8033
+ }
8034
+ }
7518
8035
  }
7519
8036
  return {
7520
8037
  kind: "ready",
@@ -7733,8 +8250,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
7733
8250
  };
7734
8251
 
7735
8252
  // src/runtime/git-worktree.ts
7736
- import { lstat, open, stat } from "fs/promises";
7737
- import * as path2 from "path";
8253
+ import { lstat, open as open2, stat as stat2 } from "fs/promises";
8254
+ import * as path3 from "path";
7738
8255
  var MAX_WORKTREE_WALK_DEPTH = 128;
7739
8256
  var MAX_GIT_FILE_BYTES = 4096;
7740
8257
  var MAX_CACHE_ENTRIES = 1024;
@@ -7745,7 +8262,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
7745
8262
  var readBounded = async (filePath) => {
7746
8263
  let handle;
7747
8264
  try {
7748
- handle = await open(filePath, "r");
8265
+ handle = await open2(filePath, "r");
7749
8266
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
7750
8267
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
7751
8268
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -7766,7 +8283,7 @@ var parseHeadBranch = (head) => {
7766
8283
  return branch;
7767
8284
  };
7768
8285
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
7769
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path2.resolve(base, target);
8286
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
7770
8287
  var parseGitDirFile = (content, worktreeRoot) => {
7771
8288
  const line = firstLine(content);
7772
8289
  return resolveGitPath(
@@ -7786,26 +8303,26 @@ var isMissing = async (filePath) => {
7786
8303
  };
7787
8304
  var isDirectory = async (directory) => {
7788
8305
  try {
7789
- return (await stat(directory)).isDirectory();
8306
+ return (await stat2(directory)).isDirectory();
7790
8307
  } catch {
7791
8308
  return false;
7792
8309
  }
7793
8310
  };
7794
8311
  var repositoryOf = async (worktreeRoot, gitDir) => {
7795
- const commonDirFile = path2.join(gitDir, "commondir");
8312
+ const commonDirFile = path3.join(gitDir, "commondir");
7796
8313
  const content = await readBounded(commonDirFile);
7797
8314
  if (content === void 0) {
7798
8315
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
7799
8316
  }
7800
8317
  const commonDir = parseCommonDirFile(content, gitDir);
7801
- const mainRoot = commonDir !== void 0 && path2.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path2.dirname(commonDir) : void 0;
8318
+ const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
7802
8319
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
7803
8320
  };
7804
8321
  var probeDirectory = async (directory) => {
7805
- const dotGit = path2.join(directory, ".git");
8322
+ const dotGit = path3.join(directory, ".git");
7806
8323
  let info;
7807
8324
  try {
7808
- info = await stat(dotGit);
8325
+ info = await stat2(dotGit);
7809
8326
  } catch {
7810
8327
  return ABSENT;
7811
8328
  }
@@ -7819,7 +8336,7 @@ var probeDirectory = async (directory) => {
7819
8336
  if (gitDir === void 0) {
7820
8337
  return INVALID;
7821
8338
  }
7822
- const head = await readBounded(path2.join(gitDir, "HEAD"));
8339
+ const head = await readBounded(path3.join(gitDir, "HEAD"));
7823
8340
  if (head === void 0) {
7824
8341
  return INVALID;
7825
8342
  }
@@ -7849,10 +8366,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
7849
8366
  };
7850
8367
  const locate = async (absolutePath) => {
7851
8368
  try {
7852
- if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8369
+ if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
7853
8370
  return void 0;
7854
8371
  }
7855
- let directory = path2.resolve(absolutePath);
8372
+ let directory = path3.resolve(absolutePath);
7856
8373
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
7857
8374
  const probe = await cachedProbe(directory);
7858
8375
  if (probe.kind === "worktree") {
@@ -7861,7 +8378,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
7861
8378
  if (probe.kind === "invalid") {
7862
8379
  return void 0;
7863
8380
  }
7864
- const parent = path2.dirname(directory);
8381
+ const parent = path3.dirname(directory);
7865
8382
  if (parent === directory) {
7866
8383
  return void 0;
7867
8384
  }
@@ -8071,7 +8588,7 @@ var createCallbackDeduplicator = (deps) => {
8071
8588
  };
8072
8589
 
8073
8590
  // src/telemetry/semconv.ts
8074
- import { createHash as createHash3 } from "crypto";
8591
+ import { createHash as createHash4 } from "crypto";
8075
8592
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
8076
8593
  import { millisToHrTime } from "@opentelemetry/core";
8077
8594
  import {
@@ -8090,7 +8607,7 @@ import {
8090
8607
  } from "@opentelemetry/semantic-conventions/incubating";
8091
8608
 
8092
8609
  // src/version.ts
8093
- var VERSION = "0.9.0";
8610
+ var VERSION = "0.10.0";
8094
8611
 
8095
8612
  // src/telemetry/export-identity.ts
8096
8613
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -8187,6 +8704,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
8187
8704
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
8188
8705
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
8189
8706
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
8707
+ var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
8190
8708
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
8191
8709
  var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
8192
8710
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
@@ -8194,7 +8712,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
8194
8712
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
8195
8713
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
8196
8714
  var FIELD_SEPARATOR = "\0";
8197
- var digestHex = (parts, length) => createHash3("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
8715
+ var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
8198
8716
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
8199
8717
  var familyOf = (type) => {
8200
8718
  switch (type) {
@@ -8459,7 +8977,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8459
8977
  // Codex turn): the key a consumer stores a usage observation under.
8460
8978
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
8461
8979
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
8462
- ...usageAttributes(end?.usage, false)
8980
+ ...usageAttributes(end?.usage, false),
8981
+ ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
8463
8982
  };
8464
8983
  status = outcomeStatus(end?.outcome);
8465
8984
  break;
@@ -9312,24 +9831,24 @@ var createBoundedMemoryStateStore = (options) => {
9312
9831
 
9313
9832
  // src/state/filesystem-store.ts
9314
9833
  import { randomBytes as randomBytes2 } from "crypto";
9315
- import { mkdir, open as open2, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
9316
- import * as path3 from "path";
9834
+ import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
9835
+ import * as path4 from "path";
9317
9836
 
9318
9837
  // src/state/keys.ts
9319
- import { createHash as createHash4 } from "crypto";
9838
+ import { createHash as createHash5 } from "crypto";
9320
9839
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
9321
9840
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
9322
9841
  var sanitizeSegment = (segment) => {
9323
9842
  if (isSafeSegment(segment)) {
9324
9843
  return segment;
9325
9844
  }
9326
- return `h_${createHash4("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
9845
+ return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
9327
9846
  };
9328
9847
  var namespaceSegments = (namespace) => [
9329
9848
  sanitizeSegment(namespace.providerId),
9330
9849
  sanitizeSegment(namespace.installationId)
9331
9850
  ];
9332
- var keyDigest = (key) => createHash4("sha256").update(key, "utf8").digest("hex");
9851
+ var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
9333
9852
 
9334
9853
  // src/state/filesystem-store.ts
9335
9854
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -9345,10 +9864,10 @@ var wrapFsError = (thrown, operation) => {
9345
9864
  };
9346
9865
  var createFilesystemStateStore = (options) => {
9347
9866
  const [providerSegment, installationSegment] = namespaceSegments(options);
9348
- const baseDir = path3.join(options.rootDir, providerSegment, installationSegment);
9349
- const recordsDir = path3.join(baseDir, "records");
9350
- const quarantineDir = path3.join(baseDir, "quarantine");
9351
- const locksDir = path3.join(baseDir, "locks");
9867
+ const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
9868
+ const recordsDir = path4.join(baseDir, "records");
9869
+ const quarantineDir = path4.join(baseDir, "quarantine");
9870
+ const locksDir = path4.join(baseDir, "locks");
9352
9871
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
9353
9872
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
9354
9873
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -9372,11 +9891,11 @@ var createFilesystemStateStore = (options) => {
9372
9891
  throw wrapFsError(thrown, "ensure-dirs");
9373
9892
  }
9374
9893
  };
9375
- const recordPath = (key) => path3.join(recordsDir, `${keyDigest(key)}.json`);
9376
- const tempPath = (key) => path3.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
9377
- const lockPath = (sessionId) => path3.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
9894
+ const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
9895
+ const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
9896
+ const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
9378
9897
  const quarantine = async (filePath, key, reason) => {
9379
- const dest = path3.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
9898
+ const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
9380
9899
  try {
9381
9900
  await rename(filePath, dest);
9382
9901
  } catch {
@@ -9440,7 +9959,7 @@ var createFilesystemStateStore = (options) => {
9440
9959
  const startedAt = options.clock.monotonicMillis();
9441
9960
  for (; ; ) {
9442
9961
  try {
9443
- const handle = await open2(filePath, "wx");
9962
+ const handle = await open3(filePath, "wx");
9444
9963
  try {
9445
9964
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
9446
9965
  } finally {
@@ -9508,7 +10027,7 @@ var createFilesystemStateStore = (options) => {
9508
10027
  }
9509
10028
  let raw;
9510
10029
  try {
9511
- raw = await readFile(path3.join(recordsDir, entry), "utf8");
10030
+ raw = await readFile(path4.join(recordsDir, entry), "utf8");
9512
10031
  } catch {
9513
10032
  continue;
9514
10033
  }
@@ -9561,7 +10080,7 @@ var createFilesystemStateStore = (options) => {
9561
10080
  continue;
9562
10081
  }
9563
10082
  scanned += 1;
9564
- const filePath = path3.join(recordsDir, entry);
10083
+ const filePath = path4.join(recordsDir, entry);
9565
10084
  try {
9566
10085
  const raw = await readFile(filePath, "utf8");
9567
10086
  const envelope = JSON.parse(raw);
@@ -9581,7 +10100,7 @@ var createFilesystemStateStore = (options) => {
9581
10100
  lockEntries = [];
9582
10101
  }
9583
10102
  for (const entry of lockEntries) {
9584
- const filePath = path3.join(locksDir, entry);
10103
+ const filePath = path4.join(locksDir, entry);
9585
10104
  try {
9586
10105
  const raw = await readFile(filePath, "utf8");
9587
10106
  const parsed = JSON.parse(raw);
@@ -9599,8 +10118,8 @@ var createFilesystemStateStore = (options) => {
9599
10118
 
9600
10119
  // src/telemetry/spool-queue.ts
9601
10120
  import { randomBytes as randomBytes3 } from "crypto";
9602
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
9603
- import * as path4 from "path";
10121
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
10122
+ import * as path5 from "path";
9604
10123
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
9605
10124
  total: 0,
9606
10125
  age: 0,
@@ -9616,7 +10135,7 @@ var enqueuedAtOf = (fileName) => {
9616
10135
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
9617
10136
  var readSpoolDropCounts = async (queueDir) => {
9618
10137
  try {
9619
- const parsed = JSON.parse(await readFile2(path4.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10138
+ const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
9620
10139
  if (typeof parsed !== "object" || parsed === null) {
9621
10140
  return EMPTY_SPOOL_DROP_COUNTS;
9622
10141
  }
@@ -9645,7 +10164,7 @@ var readSpoolQueueStats = async (queueDir) => {
9645
10164
  let bytes = 0;
9646
10165
  for (const file of files) {
9647
10166
  try {
9648
- bytes += (await stat2(path4.join(queueDir, file))).size;
10167
+ bytes += (await stat3(path5.join(queueDir, file))).size;
9649
10168
  } catch {
9650
10169
  }
9651
10170
  }
@@ -9661,8 +10180,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
9661
10180
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
9662
10181
  var createSpoolQueue = (options) => {
9663
10182
  const [providerSegment, installationSegment] = namespaceSegments(options);
9664
- const queueDir = path4.join(options.rootDir, providerSegment, installationSegment, options.queueName);
9665
- const corruptDir = path4.join(
10183
+ const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10184
+ const corruptDir = path5.join(
9666
10185
  options.rootDir,
9667
10186
  providerSegment,
9668
10187
  installationSegment,
@@ -9709,9 +10228,9 @@ var createSpoolQueue = (options) => {
9709
10228
  [reason]: current[reason] + dropped,
9710
10229
  lastDroppedAt: options.clock.now()
9711
10230
  };
9712
- const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10231
+ const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
9713
10232
  await writeFile2(tmp, JSON.stringify(next), "utf8");
9714
- await rename2(tmp, path4.join(queueDir, SPOOL_DROPS_FILE));
10233
+ await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
9715
10234
  } catch {
9716
10235
  }
9717
10236
  options.logger?.warn("durable spool dropped batches", {
@@ -9727,7 +10246,7 @@ var createSpoolQueue = (options) => {
9727
10246
  let bytes = 0;
9728
10247
  if (options.maxBytes !== void 0) {
9729
10248
  try {
9730
- bytes = (await stat2(path4.join(queueDir, name))).size;
10249
+ bytes = (await stat3(path5.join(queueDir, name))).size;
9731
10250
  } catch {
9732
10251
  continue;
9733
10252
  }
@@ -9741,7 +10260,7 @@ var createSpoolQueue = (options) => {
9741
10260
  let removed = 0;
9742
10261
  for (const file of files) {
9743
10262
  try {
9744
- await unlink2(path4.join(queueDir, file.name));
10263
+ await unlink2(path5.join(queueDir, file.name));
9745
10264
  removed += 1;
9746
10265
  } catch {
9747
10266
  }
@@ -9801,8 +10320,8 @@ var createSpoolQueue = (options) => {
9801
10320
  }
9802
10321
  }
9803
10322
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
9804
- const target = path4.join(queueDir, fileName);
9805
- const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
10323
+ const target = path5.join(queueDir, fileName);
10324
+ const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
9806
10325
  await writeFile2(tmp, serialized, "utf8");
9807
10326
  await rename2(tmp, target);
9808
10327
  return { spooled: true };
@@ -9832,7 +10351,7 @@ var createSpoolQueue = (options) => {
9832
10351
  if (fileName === void 0) {
9833
10352
  break;
9834
10353
  }
9835
- const filePath = path4.join(queueDir, fileName);
10354
+ const filePath = path5.join(queueDir, fileName);
9836
10355
  const quarantine = async (rejection) => {
9837
10356
  quarantined += 1;
9838
10357
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -9841,7 +10360,7 @@ var createSpoolQueue = (options) => {
9841
10360
  "spool.queue": options.queueName
9842
10361
  });
9843
10362
  try {
9844
- await rename2(filePath, path4.join(corruptDir, fileName));
10363
+ await rename2(filePath, path5.join(corruptDir, fileName));
9845
10364
  } catch {
9846
10365
  await unlink2(filePath).catch(() => void 0);
9847
10366
  }
@@ -10506,7 +11025,8 @@ var eventAttributes = (event3) => {
10506
11025
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
10507
11026
  [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
10508
11027
  ...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
10509
- ...usageAttributes2(event3.usage)
11028
+ ...usageAttributes2(event3.usage),
11029
+ ...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
10510
11030
  };
10511
11031
  case "tool.start":
10512
11032
  return {
@@ -11418,6 +11938,7 @@ var createHookRuntime = (options) => {
11418
11938
  privacy,
11419
11939
  logger,
11420
11940
  installationId: options.installationId,
11941
+ payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
11421
11942
  ...options.worktreeLocator === null ? {} : {
11422
11943
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
11423
11944
  }
@@ -12551,7 +13072,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
12551
13072
  );
12552
13073
 
12553
13074
  // src/install/scopes.ts
12554
- import * as path5 from "path";
13075
+ import * as path6 from "path";
12555
13076
  var REGISTRATION_SCOPES = Object.freeze([
12556
13077
  "global",
12557
13078
  "project"
@@ -12619,15 +13140,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
12619
13140
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
12620
13141
  (entry) => entry.providerId === providerId && entry.scope === scope
12621
13142
  );
12622
- var resolveInstallPath = (location, roots) => path5.resolve(
13143
+ var resolveInstallPath = (location, roots) => path6.resolve(
12623
13144
  location.scope === "global" ? roots.homeDir : roots.projectDir,
12624
13145
  ...location.segments
12625
13146
  );
12626
13147
 
12627
13148
  // src/install/document.ts
12628
13149
  import { randomBytes as randomBytes4 } from "crypto";
12629
- import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
12630
- import * as path6 from "path";
13150
+ import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
13151
+ import * as path7 from "path";
12631
13152
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12632
13153
  indent: " ",
12633
13154
  eol: "\n",
@@ -12698,15 +13219,15 @@ var renameWithRetry = async (from, to) => {
12698
13219
  var NEW_DOCUMENT_MODE = 384;
12699
13220
  var TEMPORARY_DOCUMENT_MODE = 384;
12700
13221
  var writeDocumentAtomically = async (filePath, contents) => {
12701
- const directory = path6.dirname(filePath);
13222
+ const directory = path7.dirname(filePath);
12702
13223
  await mkdir3(directory, { recursive: true });
12703
- const temporary = path6.join(
13224
+ const temporary = path7.join(
12704
13225
  directory,
12705
- `.${path6.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
13226
+ `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
12706
13227
  );
12707
13228
  let existingMode;
12708
13229
  try {
12709
- existingMode = (await stat3(filePath)).mode & 4095;
13230
+ existingMode = (await stat4(filePath)).mode & 4095;
12710
13231
  } catch (thrown) {
12711
13232
  if (!isErrnoException3(thrown, "ENOENT")) {
12712
13233
  throw thrown;
@@ -12714,7 +13235,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12714
13235
  }
12715
13236
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
12716
13237
  try {
12717
- const handle = await open3(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
13238
+ const handle = await open4(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12718
13239
  try {
12719
13240
  await handle.writeFile(contents, "utf8");
12720
13241
  await handle.sync();
@@ -12731,12 +13252,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
12731
13252
 
12732
13253
  // src/install/file-lock.ts
12733
13254
  import { randomBytes as randomBytes5 } from "crypto";
12734
- import { mkdir as mkdir4, open as open4, readFile as readFile4, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12735
- import * as path7 from "path";
13255
+ import { mkdir as mkdir4, open as open5, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
13256
+ import * as path8 from "path";
12736
13257
  var FileLockTimeoutError = class extends Error {
12737
13258
  constructor(lockPath, timeoutMillis) {
12738
13259
  super(
12739
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path7.basename(lockPath)}`
13260
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
12740
13261
  );
12741
13262
  this.name = "FileLockTimeoutError";
12742
13263
  }
@@ -12796,7 +13317,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12796
13317
  } catch {
12797
13318
  }
12798
13319
  try {
12799
- const stats = await stat4(lockPath);
13320
+ const stats = await stat5(lockPath);
12800
13321
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12801
13322
  } catch (thrown) {
12802
13323
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -12808,12 +13329,12 @@ var withFileLock = async (filePath, options, fn) => {
12808
13329
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
12809
13330
  const lockPath = lockPathFor(filePath);
12810
13331
  const startedAt = options.clock.monotonicMillis();
12811
- await mkdir4(path7.dirname(filePath), { recursive: true });
13332
+ await mkdir4(path8.dirname(filePath), { recursive: true });
12812
13333
  for (; ; ) {
12813
13334
  const token = randomBytes5(16).toString("hex");
12814
13335
  let acquired = false;
12815
13336
  try {
12816
- const handle = await open4(lockPath, "wx", 384);
13337
+ const handle = await open5(lockPath, "wx", 384);
12817
13338
  try {
12818
13339
  const contents = {
12819
13340
  token,
@@ -12856,7 +13377,7 @@ var withFileLock = async (filePath, options, fn) => {
12856
13377
 
12857
13378
  // src/install/lifecycle.ts
12858
13379
  import { readFile as readFile5 } from "fs/promises";
12859
- import * as path8 from "path";
13380
+ import * as path9 from "path";
12860
13381
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
12861
13382
  var unsupportedOutcome = (providerId, scope, reason) => ({
12862
13383
  providerId,
@@ -12873,7 +13394,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
12873
13394
  var resolveTarget = (providerId, scope, request) => {
12874
13395
  if (request.configFile !== void 0) {
12875
13396
  return {
12876
- configPath: path8.resolve(request.configFile),
13397
+ configPath: path9.resolve(request.configFile),
12877
13398
  evidence: "path supplied by the caller with --settings-file"
12878
13399
  };
12879
13400
  }
@@ -12890,14 +13411,14 @@ var resolveTarget = (providerId, scope, request) => {
12890
13411
  };
12891
13412
  };
12892
13413
  var codexFeatureNote = async (configPath) => {
12893
- const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
13414
+ const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
12894
13415
  let raw;
12895
13416
  try {
12896
13417
  raw = await readFile5(tomlPath, "utf8");
12897
13418
  } catch {
12898
13419
  return void 0;
12899
13420
  }
12900
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path8.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
13421
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
12901
13422
  };
12902
13423
  var readState = async (configPath) => {
12903
13424
  const read = await readJsonDocument(configPath);
@@ -12909,12 +13430,12 @@ var readState = async (configPath) => {
12909
13430
  case "unparseable":
12910
13431
  return {
12911
13432
  status: "blocked",
12912
- problem: `${path8.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
13433
+ problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
12913
13434
  };
12914
13435
  case "unreadable":
12915
13436
  return {
12916
13437
  status: "failed",
12917
- problem: `${path8.basename(configPath)} could not be read (${read.detail})`
13438
+ problem: `${path9.basename(configPath)} could not be read (${read.detail})`
12918
13439
  };
12919
13440
  }
12920
13441
  };
@@ -13026,7 +13547,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13026
13547
  missingEvents: [],
13027
13548
  notes,
13028
13549
  problems: planned.conflicts.map(
13029
- (conflict) => `${path8.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
13550
+ (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
13030
13551
  )
13031
13552
  };
13032
13553
  }
@@ -13037,7 +13558,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13037
13558
  changed: false,
13038
13559
  registeredEvents: [],
13039
13560
  missingEvents: [],
13040
- notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
13561
+ notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
13041
13562
  problems: []
13042
13563
  };
13043
13564
  }
@@ -13080,7 +13601,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13080
13601
  missingEvents: [],
13081
13602
  notes,
13082
13603
  problems: [
13083
- `could not write ${path8.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
13604
+ `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
13084
13605
  ]
13085
13606
  };
13086
13607
  }
@@ -13107,7 +13628,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13107
13628
  missingEvents: [],
13108
13629
  notes,
13109
13630
  problems: [
13110
- thrown instanceof Error ? `${path8.basename(configPath)}: ${thrown.message}` : `${path8.basename(configPath)}: the configuration file could not be locked`
13631
+ thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
13111
13632
  ]
13112
13633
  };
13113
13634
  }
@@ -13200,6 +13721,7 @@ export {
13200
13721
  CLAUDE_HOOK_EVENTS_MODELLED,
13201
13722
  CLAUDE_HOOK_EVENT_NAMES,
13202
13723
  CLAUDE_REGISTRABLE_HOOK_EVENTS,
13724
+ CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
13203
13725
  CLAUDE_UNREGISTERED_HOOK_EVENTS,
13204
13726
  CODEX_ADAPTER_VERSION,
13205
13727
  CODEX_CAPABILITIES,
@@ -13221,6 +13743,10 @@ export {
13221
13743
  CURSOR_REGISTRABLE_HOOK_EVENTS,
13222
13744
  CURSOR_UNMODELLED_HOOK_EVENT_NAMES,
13223
13745
  CURSOR_UNREGISTERED_HOOK_EVENTS,
13746
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES,
13747
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
13748
+ DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
13749
+ DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
13224
13750
  DEFAULT_CONFIG,
13225
13751
  DEFAULT_DESTINATION_NAME,
13226
13752
  DEFAULT_DETECTION_POLICY,
@@ -13233,6 +13759,7 @@ export {
13233
13759
  DEFAULT_MANAGED_COMMAND_MARKER,
13234
13760
  DEFAULT_PRIVACY_LIMITS,
13235
13761
  DEFAULT_PRIVACY_POLICY,
13762
+ DEFAULT_PROVIDERS_POLICY,
13236
13763
  DEFAULT_SECRET_KEY_PATTERNS,
13237
13764
  DEFAULT_SECRET_VALUE_PATTERNS,
13238
13765
  DEFAULT_SPOOL_POLICY,
@@ -13311,6 +13838,7 @@ export {
13311
13838
  addUsage,
13312
13839
  appliedDeliverySchema,
13313
13840
  asProviderId,
13841
+ attachClaudeTranscriptTurn,
13314
13842
  attributePrimitiveSchema,
13315
13843
  attributeValueSchema,
13316
13844
  attributesSchema,
@@ -13344,6 +13872,7 @@ export {
13344
13872
  createBoundedMemoryStateStore,
13345
13873
  createCallbackDeduplicator,
13346
13874
  createClaudeCodeAdapter,
13875
+ createClaudeTranscriptUsageEnricher,
13347
13876
  createCodexAdapter,
13348
13877
  createCursorAdapter,
13349
13878
  createDefaultProviderRegistry,
@@ -13483,8 +14012,11 @@ export {
13483
14012
  providerHookResponseSchema,
13484
14013
  providerIdSchema,
13485
14014
  providerTotalAgreementSchema,
14015
+ providersPolicySchema,
13486
14016
  readAntigravityHookRegistrations,
13487
14017
  readClaudeHookRegistrations,
14018
+ readClaudeTranscriptRange,
14019
+ readClaudeTranscriptTurn,
13488
14020
  readCodexHookRegistrations,
13489
14021
  readCodexHooksFeatureFlag,
13490
14022
  readCursorHookRegistrations,
@@ -13493,6 +14025,7 @@ export {
13493
14025
  readGeminiHookRegistrations,
13494
14026
  readJsonDocument,
13495
14027
  readNestedHookRegistrations,
14028
+ readsClaudeTranscriptUsage,
13496
14029
  removeAntigravityHookRegistration,
13497
14030
  removeClaudeHookRegistration,
13498
14031
  removeCodexHookRegistration,