@osfactory/otel-hook 0.12.0 → 0.13.1

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 (40) hide show
  1. package/README.md +6 -4
  2. package/dist/{adapter-DQiPu8xF.d.ts → adapter-DyCb7y1N.d.ts} +1 -1
  3. package/dist/cli.js +260 -74
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{export-destinations-CI7z4n3i.d.ts → export-destinations-DUeQKr_C.d.ts} +2 -2
  6. package/dist/{filesystem-store-CmnUlj1O.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
  7. package/dist/{hook-vM_cgqS2.d.ts → hook-D5imE0Qc.d.ts} +3 -3
  8. package/dist/index.d.ts +10 -10
  9. package/dist/index.js +252 -66
  10. package/dist/index.js.map +1 -1
  11. package/dist/install.d.ts +3 -3
  12. package/dist/install.js +14 -2
  13. package/dist/install.js.map +1 -1
  14. package/dist/integration.d.ts +7 -7
  15. package/dist/integration.js +211 -58
  16. package/dist/integration.js.map +1 -1
  17. package/dist/lifecycle.d.ts +9 -2
  18. package/dist/lifecycle.js +10 -3
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{memory-DdU1U91y.d.ts → memory-B3r6sZtC.d.ts} +1 -1
  21. package/dist/{metric-model-C9lLqqpI.d.ts → metric-model-B4lIuk6i.d.ts} +10 -1
  22. package/dist/{payload-BT19hiVZ.d.ts → payload-CdDKeRpH.d.ts} +1 -1
  23. package/dist/{ports-C3k_5eOQ.d.ts → ports-DhpSDIkp.d.ts} +8 -1
  24. package/dist/providers.d.ts +27 -11
  25. package/dist/providers.js +132 -43
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-gyJqaWmp.d.ts → registry-BKQhhIO3.d.ts} +1 -1
  28. package/dist/runtime.d.ts +6 -6
  29. package/dist/runtime.js +12 -2
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/state.d.ts +3 -3
  32. package/dist/state.js +20 -6
  33. package/dist/state.js.map +1 -1
  34. package/dist/telemetry.d.ts +3 -3
  35. package/dist/telemetry.js +72 -6
  36. package/dist/telemetry.js.map +1 -1
  37. package/dist/testing.d.ts +6 -6
  38. package/dist/testing.js +63 -8
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +2 -1
@@ -3,23 +3,23 @@ import { OverallHealth } from './diagnostics.js';
3
3
  import { OtelHookErrorInfo } from './errors.js';
4
4
  import { DeliveryClaimOutcome, UsageAccumulatorSnapshot, LifecycleCleanupReport, CallbackDeduplicator, UsageAccumulator, SpanCorrelator, MetricSeriesStore, LifecycleJanitor } from './lifecycle.js';
5
5
  import { P as PrivacyService } from './service-CbI9CObT.js';
6
- import { P as ProviderRegistry } from './registry-gyJqaWmp.js';
7
- import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-vM_cgqS2.js';
8
- import { C as Clock, I as IdGenerator, d as Logger, W as WorktreeLocator, P as PayloadEnricher, S as SessionContextReader } from './ports-C3k_5eOQ.js';
9
- import { F as FilesystemStateStore } from './filesystem-store-CmnUlj1O.js';
10
- import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-CI7z4n3i.js';
6
+ import { P as ProviderRegistry } from './registry-BKQhhIO3.js';
7
+ import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-D5imE0Qc.js';
8
+ import { C as Clock, I as IdGenerator, d as Logger, W as WorktreeLocator, P as PayloadEnricher, S as SessionContextReader } from './ports-DhpSDIkp.js';
9
+ import { F as FilesystemStateStore } from './filesystem-store-B3CpiIRl.js';
10
+ import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-DUeQKr_C.js';
11
11
  import 'zod';
12
12
  import './primitives-CJ8-rn-f.js';
13
13
  import './taxonomy-DwhTtuWd.js';
14
14
  import '@opentelemetry/api';
15
15
  import './events-fcomX6d5.js';
16
- import './metric-model-C9lLqqpI.js';
16
+ import './metric-model-B4lIuk6i.js';
17
17
  import '@opentelemetry/core';
18
18
  import '@opentelemetry/resources';
19
19
  import '@opentelemetry/sdk-trace';
20
20
  import './content-M9xIKG7h.js';
21
21
  import './policy-CimmCfRp.js';
22
- import './adapter-DQiPu8xF.js';
22
+ import './adapter-DyCb7y1N.js';
23
23
  import './identity-BrVBs901.js';
24
24
  import './keys-Dej5bN3L.js';
25
25
  import './destinations-DvqsPulb.js';
@@ -2085,6 +2085,9 @@ var deriveMetricObservations = (input) => {
2085
2085
  if (recovered !== void 0) {
2086
2086
  return end.occurredAt - recovered.startMillis;
2087
2087
  }
2088
+ if (end.subagentId !== void 0) {
2089
+ return void 0;
2090
+ }
2088
2091
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
2089
2092
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
2090
2093
  };
@@ -2416,7 +2419,7 @@ import {
2416
2419
  } from "@opentelemetry/semantic-conventions/incubating";
2417
2420
 
2418
2421
  // src/version.ts
2419
- var VERSION = "0.12.0";
2422
+ var VERSION = "0.13.1";
2420
2423
 
2421
2424
  // src/telemetry/semconv.ts
2422
2425
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -2652,7 +2655,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2652
2655
  const resolved = resolvePairing(group, anchor, correlation);
2653
2656
  const traceId = plan.traceId;
2654
2657
  const spanId = plan.spanId;
2655
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
2658
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
2659
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
2656
2660
  let name = group.ref.family;
2657
2661
  let kind = SpanKind.INTERNAL;
2658
2662
  let status = { code: SpanStatusCode.UNSET };
@@ -2876,7 +2880,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
2876
2880
  // persist something that should have been persisted.
2877
2881
  correlation === void 0 && correlationAvailable === void 0);
2878
2882
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
2879
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
2883
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
2880
2884
  return {
2881
2885
  group,
2882
2886
  anchor,
@@ -2896,6 +2900,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
2896
2900
  )
2897
2901
  };
2898
2902
  };
2903
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
2904
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
2899
2905
  var canonicalEventTraceIdentities = (events, options = {}) => {
2900
2906
  const layout = layoutBatch(events);
2901
2907
  const correlations = indexCorrelations(options.correlations);
@@ -2920,7 +2926,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
2920
2926
  });
2921
2927
  continue;
2922
2928
  }
2923
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
2929
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event2) ?? resumedSessionParent(plan.group.ref, plan.correlation);
2924
2930
  identities.set(event2.eventId, {
2925
2931
  traceId: plan.traceId,
2926
2932
  spanId: plan.spanId,
@@ -3003,6 +3009,7 @@ var encodeRecord = (record) => ({
3003
3009
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
3004
3010
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
3005
3011
  ...record.exported === true ? { exported: true } : {},
3012
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
3006
3013
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
3007
3014
  ...encodeAttributes(record.attributes)
3008
3015
  }
@@ -3026,6 +3033,7 @@ var decodeRecord = (attributes) => {
3026
3033
  return { kind: "corrupt" };
3027
3034
  }
3028
3035
  const exported = attributes["exported"] === true;
3036
+ const runKey = optionalString(attributes["runKey"]);
3029
3037
  const parentFamily = attributes["parentFamily"];
3030
3038
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
3031
3039
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -3040,6 +3048,7 @@ var decodeRecord = (attributes) => {
3040
3048
  ...endedAt === void 0 ? {} : { endedAt },
3041
3049
  ...parent === void 0 ? {} : { parent },
3042
3050
  ...exported ? { exported: true } : {},
3051
+ ...runKey === void 0 ? {} : { runKey },
3043
3052
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
3044
3053
  }
3045
3054
  };
@@ -3048,13 +3057,15 @@ var factsOf = (record) => ({
3048
3057
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
3049
3058
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
3050
3059
  ...record.parent === void 0 ? {} : { parent: record.parent },
3051
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
3060
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
3061
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
3052
3062
  });
3053
3063
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
3054
3064
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
3055
3065
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
3056
3066
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
3057
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
3067
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
3068
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
3058
3069
  });
3059
3070
  var orphanClassificationOf = (reason) => {
3060
3071
  switch (reason) {
@@ -3114,10 +3125,12 @@ var createSpanCorrelator = (deps) => {
3114
3125
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
3115
3126
  }
3116
3127
  }
3128
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
3117
3129
  const fresh = {
3118
3130
  providerId: input.providerId,
3119
3131
  startEventId: input.eventId,
3120
3132
  startedAt: input.occurredAt,
3133
+ ...previouslyExported ? { runKey: input.eventId } : {},
3121
3134
  ...input.parent === void 0 ? {} : { parent: input.parent },
3122
3135
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
3123
3136
  };
@@ -4024,7 +4037,10 @@ var postToolUseFailurePayloadSchema = z16.object({
4024
4037
  hook_event_name: z16.literal("PostToolUseFailure"),
4025
4038
  tool_name: z16.string().min(1),
4026
4039
  tool_input: z16.unknown().optional(),
4027
- tool_error: z16.unknown(),
4040
+ // Optional: a failure that names no message still ends its tool call. The
4041
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
4042
+ // `normalizeClaudeHookPayload`.
4043
+ tool_error: z16.unknown().optional(),
4028
4044
  tool_use_id: z16.string().min(1)
4029
4045
  });
4030
4046
  var permissionRequestPayloadSchema = z16.object({
@@ -4048,7 +4064,16 @@ var subagentStopPayloadSchema = z16.object({
4048
4064
  last_assistant_message: z16.string().optional(),
4049
4065
  /** True when this stop fired because a hook continued the subagent's turn. */
4050
4066
  stop_hook_active: z16.boolean().optional(),
4051
- usage: claudeUsageSchema.optional()
4067
+ /**
4068
+ * The subagent run's tokens since its previous stop — harness- or
4069
+ * enricher-supplied, never upstream. Reported on the subagent's own
4070
+ * generation, never on the parent turn (issue #68).
4071
+ */
4072
+ usage: claudeUsageSchema.optional(),
4073
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
4074
+ model: z16.string().min(1).max(256).optional().catch(void 0),
4075
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4076
+ usage_partial: z16.boolean().optional().catch(void 0)
4052
4077
  });
4053
4078
  var preCompactPayloadSchema = z16.object({
4054
4079
  ...commonFields,
@@ -4277,7 +4302,8 @@ var clamp = (value, fallback, min, max) => {
4277
4302
  };
4278
4303
  var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4279
4304
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
4280
- var assistantRecordOf = (line) => {
4305
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
4306
+ var assistantRecordOf = (line, agentId) => {
4281
4307
  if (!line.includes('"assistant"')) {
4282
4308
  return void 0;
4283
4309
  }
@@ -4288,7 +4314,10 @@ var assistantRecordOf = (line) => {
4288
4314
  return void 0;
4289
4315
  }
4290
4316
  const record = asRecord2(parsed);
4291
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
4317
+ if (record === void 0 || record.type !== "assistant") {
4318
+ return void 0;
4319
+ }
4320
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
4292
4321
  return void 0;
4293
4322
  }
4294
4323
  const message = asRecord2(record.message);
@@ -4381,7 +4410,7 @@ var completeLinesEnd = (bytes, start) => {
4381
4410
  const lastNewline = bytes.lastIndexOf(10);
4382
4411
  return lastNewline < 0 ? start : start + lastNewline + 1;
4383
4412
  };
4384
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4413
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
4385
4414
  const length = Math.min(size, maxTailBytes);
4386
4415
  const start = size - length;
4387
4416
  const bytes = await readBytes(handle, start, length);
@@ -4391,7 +4420,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4391
4420
  lines.shift();
4392
4421
  }
4393
4422
  for (let index = lines.length - 1; index >= 0; index -= 1) {
4394
- const record = assistantRecordOf((lines[index] ?? "").trim());
4423
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
4395
4424
  if (record !== void 0) {
4396
4425
  return {
4397
4426
  turn: {
@@ -4405,10 +4434,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4405
4434
  }
4406
4435
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4407
4436
  });
4408
- var boundedTail = async (transcriptPath, options) => withTimeout(
4437
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
4409
4438
  readTail(
4410
4439
  transcriptPath,
4411
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4440
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
4441
+ agentId
4412
4442
  ),
4413
4443
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4414
4444
  { status: "unavailable", reason: "unreadable" }
@@ -4438,7 +4468,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
4438
4468
  let anonymous = 0;
4439
4469
  let model;
4440
4470
  for (const line of complete.split("\n")) {
4441
- const record = assistantRecordOf(line.trim());
4471
+ const record = assistantRecordOf(line.trim(), options.agentId);
4442
4472
  if (record === void 0) {
4443
4473
  continue;
4444
4474
  }
@@ -4472,6 +4502,20 @@ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
4472
4502
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
4473
4503
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4474
4504
  var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4505
+ var SUBAGENT_STOP = "SubagentStop";
4506
+ var agentIdOf = (record) => {
4507
+ const agentId = record.agent_id ?? record.agentId;
4508
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
4509
+ };
4510
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
4511
+ var subagentCursorScope = (payload) => {
4512
+ const record = asRecord2(payload);
4513
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
4514
+ return void 0;
4515
+ }
4516
+ const agentId = agentIdOf(record);
4517
+ return agentId === void 0 ? void 0 : `agent-${createHash4("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
4518
+ };
4475
4519
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4476
4520
  const fileSize = async (transcriptPath) => {
4477
4521
  try {
@@ -4481,6 +4525,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4481
4525
  return thrown?.code === "ENOENT" ? "absent" : void 0;
4482
4526
  }
4483
4527
  };
4528
+ const readOptions = (agentId) => ({
4529
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
4530
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
4531
+ ...agentId === void 0 ? {} : { agentId }
4532
+ });
4533
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
4534
+ const source = sourceDigest(transcriptPath);
4535
+ const attach = (model, usage, partial) => ({
4536
+ ...record,
4537
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4538
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4539
+ });
4540
+ if (fromOffset !== void 0) {
4541
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
4542
+ if (range.status === "found") {
4543
+ return {
4544
+ payload: attach(range.model, range.usage, false),
4545
+ cursor: { source, offset: range.endOffset },
4546
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4547
+ };
4548
+ }
4549
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4550
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4551
+ }
4552
+ }
4553
+ const tail = await boundedTail(transcriptPath, options, agentId);
4554
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4555
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4556
+ }
4557
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4558
+ return {
4559
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
4560
+ cursor: { source, offset: tail.endOffset },
4561
+ notes: [`${why}; attached the last request only (usage_partial)`]
4562
+ };
4563
+ };
4564
+ const skipAttached = async (payload, transcriptPath) => {
4565
+ const size = await fileSize(transcriptPath);
4566
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
4567
+ };
4484
4568
  const enrich = async (input) => {
4485
4569
  const unchanged = { payload: input.payload };
4486
4570
  const record = asRecord2(input.payload);
@@ -4488,6 +4572,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4488
4572
  return unchanged;
4489
4573
  }
4490
4574
  const eventName = eventNameOf(record);
4575
+ if (eventName === SUBAGENT_STOP) {
4576
+ const agentTranscriptPath = agentTranscriptPathOf(record);
4577
+ const agentId = agentIdOf(record);
4578
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
4579
+ return unchanged;
4580
+ }
4581
+ if (hasUsage(record)) {
4582
+ return skipAttached(input.payload, agentTranscriptPath);
4583
+ }
4584
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
4585
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
4586
+ }
4491
4587
  const transcriptPath = transcriptPathOf(record);
4492
4588
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4493
4589
  return unchanged;
@@ -4508,41 +4604,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4508
4604
  return unchanged;
4509
4605
  }
4510
4606
  if (hasUsage(record)) {
4511
- const size = await fileSize(transcriptPath);
4512
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4607
+ return skipAttached(input.payload, transcriptPath);
4513
4608
  }
4514
- const attach = (model, usage, partial) => ({
4515
- ...record,
4516
- ...record.model === void 0 && model !== void 0 ? { model } : {},
4517
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
4518
- });
4519
- if (cursor !== void 0) {
4520
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4521
- if (range.status === "found") {
4522
- return {
4523
- payload: attach(range.model, range.usage, false),
4524
- cursor: { source, offset: range.endOffset },
4525
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4526
- };
4527
- }
4528
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
4529
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4530
- }
4531
- }
4532
- const tail = await boundedTail(transcriptPath, options);
4533
- if (tail === TIMED_OUT || !("turn" in tail)) {
4534
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4535
- }
4536
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4537
- return {
4538
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4539
- cursor: { source, offset: tail.endOffset },
4540
- notes: [`${why}; attached the last request only (usage_partial)`]
4541
- };
4609
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
4542
4610
  };
4543
4611
  return Object.freeze({
4544
4612
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4545
4613
  providerId: CLAUDE_CODE_PROVIDER_ID,
4614
+ cursorScope: subagentCursorScope,
4546
4615
  enrich
4547
4616
  });
4548
4617
  };
@@ -5231,7 +5300,7 @@ var usageScopeOf = (event2) => {
5231
5300
  };
5232
5301
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
5233
5302
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
5234
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
5303
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
5235
5304
  var UNKNOWN_MODEL_ID = "unknown";
5236
5305
  var latestSessionModel = (events) => {
5237
5306
  let latest;
@@ -5299,7 +5368,17 @@ var createOtelHook = (deps) => {
5299
5368
  if (enricher.providerId !== providerId) {
5300
5369
  continue;
5301
5370
  }
5302
- const key = readCursorKey(enricher.id, sessionId);
5371
+ let scope;
5372
+ try {
5373
+ scope = enricher.cursorScope?.(current);
5374
+ } catch (thrown) {
5375
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
5376
+ "enricher.id": enricher.id,
5377
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
5378
+ });
5379
+ continue;
5380
+ }
5381
+ const key = readCursorKey(enricher.id, sessionId, scope);
5303
5382
  let cursor;
5304
5383
  try {
5305
5384
  const record = await deps.stateStore.read(key);
@@ -6185,7 +6264,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6185
6264
 
6186
6265
  // src/state/filesystem-store.ts
6187
6266
  import { randomBytes as randomBytes2 } from "crypto";
6188
- import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
6267
+ import { mkdir, open as open4, readFile, readdir, rename, stat as stat3, unlink, writeFile } from "fs/promises";
6189
6268
  import * as path5 from "path";
6190
6269
 
6191
6270
  // src/state/keys.ts
@@ -6207,8 +6286,7 @@ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex")
6207
6286
  // src/state/filesystem-store.ts
6208
6287
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
6209
6288
  var sleep = (millis) => new Promise((resolve3) => {
6210
- const timer = setTimeout(resolve3, millis);
6211
- timer.unref?.();
6289
+ setTimeout(resolve3, millis);
6212
6290
  });
6213
6291
  var wrapFsError = (thrown, operation) => {
6214
6292
  if (thrown instanceof Error) {
@@ -6328,14 +6406,29 @@ var createFilesystemStateStore = (options) => {
6328
6406
  }
6329
6407
  }
6330
6408
  const stale = await (async () => {
6409
+ let raw;
6410
+ try {
6411
+ raw = await readFile(filePath, "utf8");
6412
+ } catch (thrown) {
6413
+ return isErrnoException(thrown, "ENOENT") ? "gone" : true;
6414
+ }
6331
6415
  try {
6332
- const raw = await readFile(filePath, "utf8");
6333
6416
  const parsed = JSON.parse(raw);
6334
- return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
6417
+ if (typeof parsed.acquiredAt === "number") {
6418
+ return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
6419
+ }
6335
6420
  } catch {
6336
- return true;
6421
+ }
6422
+ try {
6423
+ const stats = await stat3(filePath);
6424
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
6425
+ } catch {
6426
+ return "gone";
6337
6427
  }
6338
6428
  })();
6429
+ if (stale === "gone") {
6430
+ continue;
6431
+ }
6339
6432
  if (stale) {
6340
6433
  await unlink(filePath).catch(() => void 0);
6341
6434
  continue;
@@ -6506,7 +6599,7 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6506
6599
 
6507
6600
  // src/telemetry/spool-queue.ts
6508
6601
  import { randomBytes as randomBytes3 } from "crypto";
6509
- 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";
6602
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
6510
6603
  import * as path6 from "path";
6511
6604
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
6512
6605
  total: 0,
@@ -6552,7 +6645,7 @@ var readSpoolQueueStats = async (queueDir) => {
6552
6645
  let bytes = 0;
6553
6646
  for (const file of files) {
6554
6647
  try {
6555
- bytes += (await stat3(path6.join(queueDir, file))).size;
6648
+ bytes += (await stat4(path6.join(queueDir, file))).size;
6556
6649
  } catch {
6557
6650
  }
6558
6651
  }
@@ -6565,6 +6658,22 @@ var readSpoolQueueStats = async (queueDir) => {
6565
6658
  };
6566
6659
  };
6567
6660
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
6661
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
6662
+ var CLAIM_MARKER = ".claimed-";
6663
+ var isClaimOwnerAlive = (pid) => {
6664
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
6665
+ return true;
6666
+ }
6667
+ if (pid === process.pid) {
6668
+ return true;
6669
+ }
6670
+ try {
6671
+ process.kill(pid, 0);
6672
+ return true;
6673
+ } catch (thrown) {
6674
+ return thrown?.code !== "ESRCH";
6675
+ }
6676
+ };
6568
6677
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
6569
6678
  var createSpoolQueue = (options) => {
6570
6679
  const [providerSegment, installationSegment] = namespaceSegments(options);
@@ -6634,7 +6743,7 @@ var createSpoolQueue = (options) => {
6634
6743
  let bytes = 0;
6635
6744
  if (options.maxBytes !== void 0) {
6636
6745
  try {
6637
- bytes = (await stat3(path6.join(queueDir, name))).size;
6746
+ bytes = (await stat4(path6.join(queueDir, name))).size;
6638
6747
  } catch {
6639
6748
  continue;
6640
6749
  }
@@ -6714,9 +6823,33 @@ var createSpoolQueue = (options) => {
6714
6823
  await rename2(tmp, target);
6715
6824
  return { spooled: true };
6716
6825
  };
6826
+ const releaseStaleClaims = async () => {
6827
+ let entries;
6828
+ try {
6829
+ entries = await readdir2(queueDir);
6830
+ } catch {
6831
+ return;
6832
+ }
6833
+ const now = Date.now();
6834
+ for (const entry of entries) {
6835
+ const marker = entry.lastIndexOf(CLAIM_MARKER);
6836
+ if (marker <= 0) {
6837
+ continue;
6838
+ }
6839
+ const claimPath = path6.join(queueDir, entry);
6840
+ const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
6841
+ try {
6842
+ if (!isClaimOwnerAlive(owner) || now - (await stat4(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
6843
+ await rename2(claimPath, path6.join(queueDir, entry.slice(0, marker)));
6844
+ }
6845
+ } catch {
6846
+ }
6847
+ }
6848
+ };
6717
6849
  const drain = async (send, drainOptions) => {
6718
6850
  await ensureDirs();
6719
6851
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
6852
+ await releaseStaleClaims();
6720
6853
  let files = await listSorted();
6721
6854
  if (options.maxAgeMillis !== void 0) {
6722
6855
  const now = options.clock.now();
@@ -6739,7 +6872,16 @@ var createSpoolQueue = (options) => {
6739
6872
  if (fileName === void 0) {
6740
6873
  break;
6741
6874
  }
6742
- const filePath = path6.join(queueDir, fileName);
6875
+ const queuedPath = path6.join(queueDir, fileName);
6876
+ const filePath = path6.join(
6877
+ queueDir,
6878
+ `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes3(4).toString("hex")}`
6879
+ );
6880
+ try {
6881
+ await rename2(queuedPath, filePath);
6882
+ } catch {
6883
+ continue;
6884
+ }
6743
6885
  const quarantine = async (rejection) => {
6744
6886
  quarantined += 1;
6745
6887
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6753,9 +6895,19 @@ var createSpoolQueue = (options) => {
6753
6895
  await unlink2(filePath).catch(() => void 0);
6754
6896
  }
6755
6897
  };
6898
+ let text;
6899
+ try {
6900
+ text = await readFile2(filePath, "utf8");
6901
+ } catch (thrown) {
6902
+ if (thrown?.code === "ENOENT") {
6903
+ continue;
6904
+ }
6905
+ await quarantine("unreadable");
6906
+ continue;
6907
+ }
6756
6908
  let parsed;
6757
6909
  try {
6758
- parsed = JSON.parse(await readFile2(filePath, "utf8"));
6910
+ parsed = JSON.parse(text);
6759
6911
  } catch {
6760
6912
  await quarantine("unparseable-json");
6761
6913
  continue;
@@ -6784,6 +6936,7 @@ var createSpoolQueue = (options) => {
6784
6936
  await unlink2(filePath).catch(() => void 0);
6785
6937
  drained += 1;
6786
6938
  } else {
6939
+ await rename2(filePath, queuedPath).catch(() => void 0);
6787
6940
  failed += 1;
6788
6941
  break;
6789
6942
  }