@osfactory/otel-hook 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +124 -4
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-DiLknaTF.d.ts} +14 -2
  3. package/dist/cli.js +2272 -730
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +13 -4
  6. package/dist/config.js +128 -23
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C6Bm89W6.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  12. package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-QWKGGEjk.d.ts} +131 -6
  13. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  14. package/dist/{hook-zA1b4cWd.d.ts → hook-BOecWGSz.d.ts} +10 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1808 -251
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +31 -2
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +37 -12
  22. package/dist/integration.js +3271 -1551
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +277 -4
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-Bl9ANVff.d.ts → memory-Cs51jyRk.d.ts} +2 -2
  28. package/dist/{semconv-fPRb-dpU.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-ChtrEX6A.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-CeqLq31i.d.ts} +87 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-B8ZHc2bc.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1404 -1219
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-BxiVsU-d.d.ts → schema-DMnoU1V_.d.ts} +93 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +630 -39
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +872 -19
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +264 -34
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +3 -1
package/dist/providers.js CHANGED
@@ -690,6 +690,13 @@ var generationEndEventSchema = event({
690
690
  stopReason: nonEmptyStringSchema.optional(),
691
691
  durationMillis: durationMillisSchema.optional(),
692
692
  usage: canonicalUsageSchema.optional(),
693
+ /**
694
+ * True when `usage` is known to cover only part of the generation (for
695
+ * example the last model request of a multi-request turn); false when the
696
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
697
+ * without `usage`.
698
+ */
699
+ usagePartial: z9.boolean().optional(),
693
700
  cost: costFactsSchema.optional(),
694
701
  outputContent: contentFactsSchema.optional()
695
702
  });
@@ -1353,7 +1360,25 @@ var stopPayloadSchema = z12.object({
1353
1360
  * the former without suppressing the latter.
1354
1361
  */
1355
1362
  stop_hook_active: z12.boolean().optional(),
1356
- usage: claudeUsageSchema.optional()
1363
+ usage: claudeUsageSchema.optional(),
1364
+ /**
1365
+ * The model that answered this turn — harness-supplied, never upstream.
1366
+ *
1367
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
1368
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
1369
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
1370
+ * with `usage`, and it becomes the generation's response model. An unusable
1371
+ * value (empty, over 256 characters, not a string) is dropped rather than
1372
+ * failing the whole payload: the turn is still worth reporting without it.
1373
+ */
1374
+ model: z12.string().min(1).max(256).optional().catch(void 0),
1375
+ /**
1376
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
1377
+ * turn. `true` when it is the last model request alone (the tail fallback),
1378
+ * `false` when it sums every request since the previous stop. Exported as
1379
+ * `otelhook.usage.partial`; absent means the attacher did not say.
1380
+ */
1381
+ usage_partial: z12.boolean().optional().catch(void 0)
1357
1382
  });
1358
1383
  var stopFailurePayloadSchema = z12.object({
1359
1384
  ...commonFields,
@@ -1365,7 +1390,11 @@ var stopFailurePayloadSchema = z12.object({
1365
1390
  */
1366
1391
  error_type: z12.string().min(1),
1367
1392
  error_message: z12.string().optional(),
1368
- usage: claudeUsageSchema.optional()
1393
+ usage: claudeUsageSchema.optional(),
1394
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
1395
+ model: z12.string().min(1).max(256).optional().catch(void 0),
1396
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
1397
+ usage_partial: z12.boolean().optional().catch(void 0)
1369
1398
  });
1370
1399
  var claudeHookPayloadSchema = z12.discriminatedUnion("hook_event_name", [
1371
1400
  sessionStartPayloadSchema,
@@ -1944,6 +1973,13 @@ var inferToolKind = (toolName) => {
1944
1973
 
1945
1974
  // src/providers/claude/events.ts
1946
1975
  var UNKNOWN_MODEL = { modelId: "unknown" };
1976
+ var generationModels = (attached, sessionModel) => {
1977
+ const turnModel = attached === void 0 ? void 0 : { modelId: attached };
1978
+ return {
1979
+ request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
1980
+ response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
1981
+ };
1982
+ };
1947
1983
  var SESSION_END_REASON = Object.freeze({
1948
1984
  completed: "completed",
1949
1985
  aborted: "aborted",
@@ -2010,6 +2046,10 @@ var parseClaudeCode = (input, context) => {
2010
2046
  warnings.push(...normalized.warnings);
2011
2047
  return applyUsage(normalized);
2012
2048
  };
2049
+ const withPartialUsage = (usage, partial) => {
2050
+ const applied = withUsage(usage);
2051
+ return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
2052
+ };
2013
2053
  switch (payload.hook_event_name) {
2014
2054
  case "SessionStart":
2015
2055
  factory.build({
@@ -2122,11 +2162,12 @@ var parseClaudeCode = (input, context) => {
2122
2162
  payload.prompt_id ?? String(input.sequenceBase)
2123
2163
  ]);
2124
2164
  const assistantText = extractClaudeAssistantText(normalizedPayload);
2125
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
2165
+ const models = generationModels(payload.model, input.sessionModel);
2166
+ factory.build({ type: "generation.start", generationId, model: models.request });
2126
2167
  factory.build({
2127
2168
  type: "generation.end",
2128
2169
  generationId,
2129
- model: UNKNOWN_MODEL,
2170
+ model: models.response,
2130
2171
  outcome: "ok",
2131
2172
  // Always a response fact: a body when Claude sent text, otherwise a
2132
2173
  // zero-length omitted fact so the log mapping can emit metadata_only
@@ -2138,7 +2179,7 @@ var parseClaudeCode = (input, context) => {
2138
2179
  text: assistantText
2139
2180
  })
2140
2181
  ],
2141
- ...withUsage(extractedUsage ?? payload.usage)
2182
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
2142
2183
  });
2143
2184
  break;
2144
2185
  }
@@ -2149,11 +2190,12 @@ var parseClaudeCode = (input, context) => {
2149
2190
  payload.prompt_id ?? String(input.sequenceBase)
2150
2191
  ]);
2151
2192
  const assistantText = extractClaudeAssistantText(normalizedPayload);
2152
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
2193
+ const models = generationModels(payload.model, input.sessionModel);
2194
+ factory.build({ type: "generation.start", generationId, model: models.request });
2153
2195
  factory.build({
2154
2196
  type: "generation.end",
2155
2197
  generationId,
2156
- model: UNKNOWN_MODEL,
2198
+ model: models.response,
2157
2199
  outcome: mapStopFailureOutcome(payload.error_type),
2158
2200
  stopReason: payload.error_type,
2159
2201
  ...assistantText === void 0 ? {} : {
@@ -2165,7 +2207,7 @@ var parseClaudeCode = (input, context) => {
2165
2207
  })
2166
2208
  ]
2167
2209
  },
2168
- ...withUsage(extractedUsage ?? payload.usage)
2210
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
2169
2211
  });
2170
2212
  break;
2171
2213
  }
@@ -2192,6 +2234,339 @@ var createClaudeCodeAdapter = (options = {}) => ({
2192
2234
  hookResponse: () => SILENT_HOOK_RESPONSE
2193
2235
  });
2194
2236
 
2237
+ // src/providers/claude/transcript.ts
2238
+ import { createHash } from "crypto";
2239
+ import { open, stat } from "fs/promises";
2240
+ import path from "path";
2241
+ var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
2242
+ var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
2243
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
2244
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
2245
+ var MIN_TAIL_BYTES = 65536;
2246
+ var MAX_TAIL_BYTES = 16777216;
2247
+ var MAX_RANGE_BYTES = 67108864;
2248
+ var MIN_TIMEOUT_MILLIS = 10;
2249
+ var MAX_TIMEOUT_MILLIS = 5e3;
2250
+ var MAX_MODEL_ID_LENGTH = 256;
2251
+ var MAX_REQUESTS_PER_RANGE = 1e4;
2252
+ var SYNTHETIC_MODEL = "<synthetic>";
2253
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
2254
+ var clamp = (value, fallback, min, max) => {
2255
+ if (value === void 0 || !Number.isFinite(value)) {
2256
+ return fallback;
2257
+ }
2258
+ return Math.min(max, Math.max(min, Math.floor(value)));
2259
+ };
2260
+ var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2261
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
2262
+ var assistantRecordOf = (line) => {
2263
+ if (!line.includes('"assistant"')) {
2264
+ return void 0;
2265
+ }
2266
+ let parsed;
2267
+ try {
2268
+ parsed = JSON.parse(line);
2269
+ } catch {
2270
+ return void 0;
2271
+ }
2272
+ const record = asRecord5(parsed);
2273
+ if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
2274
+ return void 0;
2275
+ }
2276
+ const message = asRecord5(record.message);
2277
+ if (message === void 0 || message.model === SYNTHETIC_MODEL) {
2278
+ return void 0;
2279
+ }
2280
+ const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
2281
+ const usage = coerceClaudeUsage(message.usage);
2282
+ if (model === void 0 && usage === void 0) {
2283
+ return void 0;
2284
+ }
2285
+ const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
2286
+ return {
2287
+ ...id === void 0 ? {} : { id },
2288
+ ...model === void 0 ? {} : { model },
2289
+ ...usage === void 0 ? {} : { usage }
2290
+ };
2291
+ };
2292
+ 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));
2293
+ var sumUsage = (usages) => {
2294
+ let input = 0;
2295
+ let output = 0;
2296
+ let cacheRead = 0;
2297
+ let cacheCreation = 0;
2298
+ for (const usage of usages) {
2299
+ input += usage.input_tokens;
2300
+ output += usage.output_tokens;
2301
+ cacheRead += usage.cache_read_input_tokens ?? 0;
2302
+ cacheCreation += cacheCreationOf(usage);
2303
+ }
2304
+ return {
2305
+ input_tokens: input,
2306
+ output_tokens: output,
2307
+ cache_read_input_tokens: cacheRead,
2308
+ cache_creation_input_tokens: cacheCreation
2309
+ };
2310
+ };
2311
+ var withTimeout = async (work, timeoutMillis, onError) => {
2312
+ let timer;
2313
+ const timeout = new Promise((resolve) => {
2314
+ timer = setTimeout(() => {
2315
+ resolve(TIMED_OUT);
2316
+ }, timeoutMillis);
2317
+ timer.unref();
2318
+ });
2319
+ try {
2320
+ return await Promise.race([work.catch(() => onError), timeout]);
2321
+ } finally {
2322
+ clearTimeout(timer);
2323
+ }
2324
+ };
2325
+ var withRegularFile = async (transcriptPath, body) => {
2326
+ let info;
2327
+ try {
2328
+ info = await stat(transcriptPath);
2329
+ } catch {
2330
+ return { status: "unavailable", reason: "unreadable" };
2331
+ }
2332
+ if (!info.isFile()) {
2333
+ return { status: "unavailable", reason: "not-a-file" };
2334
+ }
2335
+ let handle;
2336
+ try {
2337
+ handle = await open(transcriptPath, "r");
2338
+ } catch {
2339
+ return { status: "unavailable", reason: "unreadable" };
2340
+ }
2341
+ try {
2342
+ const { size } = await handle.stat();
2343
+ return await body(handle, size);
2344
+ } catch {
2345
+ return { status: "unavailable", reason: "unreadable" };
2346
+ } finally {
2347
+ await handle.close().catch(() => void 0);
2348
+ }
2349
+ };
2350
+ var readBytes = async (handle, start, length) => {
2351
+ const buffer = Buffer.alloc(length);
2352
+ let filled = 0;
2353
+ while (filled < length) {
2354
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
2355
+ if (bytesRead === 0) {
2356
+ break;
2357
+ }
2358
+ filled += bytesRead;
2359
+ }
2360
+ return buffer.subarray(0, filled);
2361
+ };
2362
+ var completeLinesEnd = (bytes, start) => {
2363
+ const lastNewline = bytes.lastIndexOf(10);
2364
+ return lastNewline < 0 ? start : start + lastNewline + 1;
2365
+ };
2366
+ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
2367
+ const length = Math.min(size, maxTailBytes);
2368
+ const start = size - length;
2369
+ const bytes = await readBytes(handle, start, length);
2370
+ const endOffset = completeLinesEnd(bytes, start);
2371
+ const lines = bytes.toString("utf8").split("\n");
2372
+ if (start > 0) {
2373
+ lines.shift();
2374
+ }
2375
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
2376
+ const record = assistantRecordOf((lines[index] ?? "").trim());
2377
+ if (record !== void 0) {
2378
+ return {
2379
+ turn: {
2380
+ status: "found",
2381
+ ...record.model === void 0 ? {} : { model: record.model },
2382
+ ...record.usage === void 0 ? {} : { usage: record.usage }
2383
+ },
2384
+ endOffset
2385
+ };
2386
+ }
2387
+ }
2388
+ return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
2389
+ });
2390
+ var boundedTail = async (transcriptPath, options) => withTimeout(
2391
+ readTail(
2392
+ transcriptPath,
2393
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
2394
+ ),
2395
+ clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
2396
+ { status: "unavailable", reason: "unreadable" }
2397
+ );
2398
+ var readClaudeTranscriptTurn = async (transcriptPath, options = {}) => {
2399
+ if (!isTranscriptPath(transcriptPath)) {
2400
+ return { status: "unavailable", reason: "invalid-path" };
2401
+ }
2402
+ const read = await boundedTail(transcriptPath, options);
2403
+ if (read === TIMED_OUT) {
2404
+ return { status: "unavailable", reason: "timeout" };
2405
+ }
2406
+ return "turn" in read ? read.turn : read;
2407
+ };
2408
+ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
2409
+ if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
2410
+ return { status: "unavailable", reason: "invalid-path" };
2411
+ }
2412
+ const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
2413
+ const timeoutMillis = clamp(
2414
+ options.rangeTimeoutMillis,
2415
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
2416
+ MIN_TIMEOUT_MILLIS,
2417
+ MAX_TIMEOUT_MILLIS
2418
+ );
2419
+ const work = withRegularFile(transcriptPath, async (handle, size) => {
2420
+ if (size < fromOffset) {
2421
+ return { status: "unavailable", reason: "truncated" };
2422
+ }
2423
+ if (size - fromOffset > maxRangeBytes) {
2424
+ return { status: "unavailable", reason: "over-cap" };
2425
+ }
2426
+ const bytes = await readBytes(handle, fromOffset, size - fromOffset);
2427
+ const endOffset = completeLinesEnd(bytes, fromOffset);
2428
+ const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
2429
+ const requests = /* @__PURE__ */ new Map();
2430
+ let anonymous = 0;
2431
+ let model;
2432
+ for (const line of complete.split("\n")) {
2433
+ const record = assistantRecordOf(line.trim());
2434
+ if (record === void 0) {
2435
+ continue;
2436
+ }
2437
+ if (record.model !== void 0) {
2438
+ model = record.model;
2439
+ }
2440
+ anonymous += record.id === void 0 ? 1 : 0;
2441
+ requests.set(record.id ?? `#${String(anonymous)}`, record);
2442
+ if (requests.size > MAX_REQUESTS_PER_RANGE) {
2443
+ return { status: "unavailable", reason: "over-cap" };
2444
+ }
2445
+ }
2446
+ const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
2447
+ return {
2448
+ status: "found",
2449
+ ...model === void 0 ? {} : { model },
2450
+ ...usages.length === 0 ? {} : { usage: sumUsage(usages) },
2451
+ requestCount: requests.size,
2452
+ endOffset
2453
+ };
2454
+ });
2455
+ const result = await withTimeout(work, timeoutMillis, {
2456
+ status: "unavailable",
2457
+ reason: "unreadable"
2458
+ });
2459
+ return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
2460
+ };
2461
+ var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
2462
+ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
2463
+ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
2464
+ var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
2465
+ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
2466
+ const record = asRecord5(payload);
2467
+ if (record === void 0) {
2468
+ return payload;
2469
+ }
2470
+ const eventName = eventNameOf(record);
2471
+ if (typeof eventName !== "string" || !STOP_EVENTS.has(eventName)) {
2472
+ return payload;
2473
+ }
2474
+ const transcriptPath = transcriptPathOf(record);
2475
+ if (typeof transcriptPath !== "string") {
2476
+ return payload;
2477
+ }
2478
+ const needsModel = record.model === void 0;
2479
+ const needsUsage = !hasUsage(record);
2480
+ if (!needsModel && !needsUsage) {
2481
+ return payload;
2482
+ }
2483
+ const turn = await readClaudeTranscriptTurn(transcriptPath, options);
2484
+ if (turn.status !== "found") {
2485
+ return payload;
2486
+ }
2487
+ return {
2488
+ ...record,
2489
+ ...needsModel && turn.model !== void 0 ? { model: turn.model } : {},
2490
+ ...needsUsage && turn.usage !== void 0 ? { usage: turn.usage, usage_partial: true } : {}
2491
+ };
2492
+ };
2493
+ var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
2494
+ var sourceDigest = (transcriptPath) => createHash("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
2495
+ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2496
+ const fileSize = async (transcriptPath) => {
2497
+ try {
2498
+ const info = await stat(transcriptPath);
2499
+ return info.isFile() ? info.size : void 0;
2500
+ } catch (thrown) {
2501
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
2502
+ }
2503
+ };
2504
+ const enrich = async (input) => {
2505
+ const unchanged = { payload: input.payload };
2506
+ const record = asRecord5(input.payload);
2507
+ if (record === void 0) {
2508
+ return unchanged;
2509
+ }
2510
+ const eventName = eventNameOf(record);
2511
+ const transcriptPath = transcriptPathOf(record);
2512
+ if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
2513
+ return unchanged;
2514
+ }
2515
+ const source = sourceDigest(transcriptPath);
2516
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
2517
+ if (eventName === "SessionStart") {
2518
+ if (cursor !== void 0) {
2519
+ return unchanged;
2520
+ }
2521
+ const size = await fileSize(transcriptPath);
2522
+ if (size === void 0) {
2523
+ return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
2524
+ }
2525
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
2526
+ }
2527
+ if (!STOP_EVENTS.has(eventName)) {
2528
+ return unchanged;
2529
+ }
2530
+ if (hasUsage(record)) {
2531
+ const size = await fileSize(transcriptPath);
2532
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
2533
+ }
2534
+ const attach = (model, usage, partial) => ({
2535
+ ...record,
2536
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
2537
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
2538
+ });
2539
+ if (cursor !== void 0) {
2540
+ const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
2541
+ if (range.status === "found") {
2542
+ return {
2543
+ payload: attach(range.model, range.usage, false),
2544
+ cursor: { source, offset: range.endOffset },
2545
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
2546
+ };
2547
+ }
2548
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
2549
+ return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
2550
+ }
2551
+ }
2552
+ const tail = await boundedTail(transcriptPath, options);
2553
+ if (tail === TIMED_OUT || !("turn" in tail)) {
2554
+ return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
2555
+ }
2556
+ const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
2557
+ return {
2558
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
2559
+ cursor: { source, offset: tail.endOffset },
2560
+ notes: [`${why}; attached the last request only (usage_partial)`]
2561
+ };
2562
+ };
2563
+ return Object.freeze({
2564
+ id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
2565
+ providerId: CLAUDE_CODE_PROVIDER_ID,
2566
+ enrich
2567
+ });
2568
+ };
2569
+
2195
2570
  // src/providers/cursor/payload.ts
2196
2571
  import { z as z13 } from "zod";
2197
2572
  var CURSOR_PROVIDER_ID = "cursor";
@@ -3346,7 +3721,7 @@ var codexDeliveryIdentity = (input) => {
3346
3721
 
3347
3722
  // src/providers/codex/target.ts
3348
3723
  var PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/;
3349
- var asRecord5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3724
+ var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3350
3725
  var nonEmptyString2 = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
3351
3726
  var commandText = (input) => {
3352
3727
  const command = input?.command ?? input?.cmd;
@@ -3373,7 +3748,7 @@ var patchTextOf = (toolName, input) => {
3373
3748
  if (typeof input === "string") {
3374
3749
  return /^apply[_-]?patch$/i.test(toolName) ? input : void 0;
3375
3750
  }
3376
- const record = asRecord5(input);
3751
+ const record = asRecord6(input);
3377
3752
  if (/^apply[_-]?patch$/i.test(toolName)) {
3378
3753
  return nonEmptyString2(record?.patch) ?? nonEmptyString2(record?.input) ?? commandText(record);
3379
3754
  }
@@ -3381,7 +3756,7 @@ var patchTextOf = (toolName, input) => {
3381
3756
  return command !== void 0 && /^\s*apply_patch\b/.test(command) ? command : void 0;
3382
3757
  };
3383
3758
  var codexTargetHint = (toolName, toolInput, cwd) => {
3384
- const record = asRecord5(toolInput);
3759
+ const record = asRecord6(toolInput);
3385
3760
  const workdir = nonEmptyString2(record?.workdir);
3386
3761
  const base = workdir ?? cwd;
3387
3762
  const patch = patchTextOf(toolName, toolInput);
@@ -3463,7 +3838,7 @@ var CODEX_CAPABILITIES = Object.freeze({
3463
3838
  // compaction callbacks do not. See `./delivery.ts` for which and why.
3464
3839
  deliveryIdentifier: "partial"
3465
3840
  });
3466
- var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3841
+ var asRecord7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3467
3842
  var hasExactMarker = (payload) => {
3468
3843
  if (payload.codex_version !== void 0) {
3469
3844
  return true;
@@ -3556,7 +3931,7 @@ var outcomeFromToolResponse = (toolResponse) => {
3556
3931
  if (toolResponse === void 0) {
3557
3932
  return "unknown";
3558
3933
  }
3559
- const record = asRecord6(toolResponse);
3934
+ const record = asRecord7(toolResponse);
3560
3935
  if (record === void 0) {
3561
3936
  return "ok";
3562
3937
  }
@@ -4838,6 +5213,7 @@ export {
4838
5213
  CLAUDE_CODE_CAPABILITIES,
4839
5214
  CLAUDE_CODE_PROVIDER_ID,
4840
5215
  CLAUDE_HOOK_EVENT_NAMES,
5216
+ CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4841
5217
  CODEX_ADAPTER_VERSION,
4842
5218
  CODEX_CAPABILITIES,
4843
5219
  CODEX_HOOK_EVENT_NAMES,
@@ -4848,6 +5224,10 @@ export {
4848
5224
  CURSOR_HOOK_EVENT_NAMES,
4849
5225
  CURSOR_PROVIDER_ID,
4850
5226
  CURSOR_UNMODELLED_HOOK_EVENT_NAMES,
5227
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES,
5228
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
5229
+ DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
5230
+ DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
4851
5231
  DEFAULT_GEMINI_CAPABILITIES,
4852
5232
  DELIVERY_COMPONENT_PATTERN,
4853
5233
  DELIVERY_GAP_REASON_PATTERN,
@@ -4862,8 +5242,10 @@ export {
4862
5242
  SILENT_HOOK_RESPONSE,
4863
5243
  adapterSupports,
4864
5244
  asProviderId,
5245
+ attachClaudeTranscriptTurn,
4865
5246
  createAntigravityAdapter,
4866
5247
  createClaudeCodeAdapter,
5248
+ createClaudeTranscriptUsageEnricher,
4867
5249
  createCodexAdapter,
4868
5250
  createCursorAdapter,
4869
5251
  createDefaultProviderRegistry,
@@ -4882,6 +5264,8 @@ export {
4882
5264
  providerDeliveryGapsSchema,
4883
5265
  providerDetectionSchema,
4884
5266
  providerHookResponseSchema,
5267
+ readClaudeTranscriptRange,
5268
+ readClaudeTranscriptTurn,
4885
5269
  readDeliveryClaim,
4886
5270
  readDeliveryGap,
4887
5271
  unknownDetection