@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
package/dist/index.js CHANGED
@@ -3139,7 +3139,10 @@ var postToolUseFailurePayloadSchema = z17.object({
3139
3139
  hook_event_name: z17.literal("PostToolUseFailure"),
3140
3140
  tool_name: z17.string().min(1),
3141
3141
  tool_input: z17.unknown().optional(),
3142
- tool_error: z17.unknown(),
3142
+ // Optional: a failure that names no message still ends its tool call. The
3143
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
3144
+ // `normalizeClaudeHookPayload`.
3145
+ tool_error: z17.unknown().optional(),
3143
3146
  tool_use_id: z17.string().min(1)
3144
3147
  });
3145
3148
  var permissionRequestPayloadSchema = z17.object({
@@ -3163,7 +3166,16 @@ var subagentStopPayloadSchema = z17.object({
3163
3166
  last_assistant_message: z17.string().optional(),
3164
3167
  /** True when this stop fired because a hook continued the subagent's turn. */
3165
3168
  stop_hook_active: z17.boolean().optional(),
3166
- usage: claudeUsageSchema.optional()
3169
+ /**
3170
+ * The subagent run's tokens since its previous stop — harness- or
3171
+ * enricher-supplied, never upstream. Reported on the subagent's own
3172
+ * generation, never on the parent turn (issue #68).
3173
+ */
3174
+ usage: claudeUsageSchema.optional(),
3175
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
3176
+ model: z17.string().min(1).max(256).optional().catch(void 0),
3177
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
3178
+ usage_partial: z17.boolean().optional().catch(void 0)
3167
3179
  });
3168
3180
  var preCompactPayloadSchema = z17.object({
3169
3181
  ...commonFields,
@@ -3499,7 +3511,13 @@ var normalizeClaudeHookPayload = (payload) => {
3499
3511
  if (record === void 0) {
3500
3512
  return payload;
3501
3513
  }
3502
- return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
3514
+ return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));
3515
+ };
3516
+ var applyToolFailureShape = (record) => {
3517
+ if (record.hook_event_name !== "PostToolUseFailure" || record.tool_error !== void 0 || record.error === void 0) {
3518
+ return record;
3519
+ }
3520
+ return { ...record, tool_error: record.error };
3503
3521
  };
3504
3522
  var applyUsageShape = (record) => {
3505
3523
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -3761,6 +3779,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
3761
3779
  WebFetch: "network",
3762
3780
  WebSearch: "network",
3763
3781
  Task: "delegate",
3782
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
3783
+ Agent: "delegate",
3764
3784
  TodoWrite: "other",
3765
3785
  ExitPlanMode: "other",
3766
3786
  AskUserQuestion: "other",
@@ -3934,14 +3954,39 @@ var parseClaudeCode = (input, context) => {
3934
3954
  delegationDepth: 1
3935
3955
  });
3936
3956
  break;
3937
- case "SubagentStop":
3957
+ case "SubagentStop": {
3958
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
3959
+ if (usage.usage !== void 0 || payload.model !== void 0) {
3960
+ const generationId = context.ids.newOpaqueId([
3961
+ "claude-subagent-generation",
3962
+ payload.session_id,
3963
+ payload.agent_id,
3964
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
3965
+ ]);
3966
+ const models = generationModels(payload.model, void 0);
3967
+ factory.build({ type: "generation.start", generationId, model: models.request });
3968
+ factory.build({
3969
+ type: "generation.end",
3970
+ generationId,
3971
+ model: models.response,
3972
+ outcome: "ok",
3973
+ outputContent: [
3974
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
3975
+ kind: "response",
3976
+ role: "assistant",
3977
+ text: payload.last_assistant_message
3978
+ })
3979
+ ],
3980
+ ...usage
3981
+ });
3982
+ }
3938
3983
  factory.build({
3939
3984
  type: "subagent.end",
3940
3985
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
3941
- outcome: "ok",
3942
- ...withUsage(payload.usage)
3986
+ outcome: "ok"
3943
3987
  });
3944
3988
  break;
3989
+ }
3945
3990
  case "PreCompact":
3946
3991
  return {
3947
3992
  status: "ignored",
@@ -4061,7 +4106,8 @@ var clamp = (value, fallback, min, max) => {
4061
4106
  };
4062
4107
  var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4063
4108
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
4064
- var assistantRecordOf = (line) => {
4109
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
4110
+ var assistantRecordOf = (line, agentId) => {
4065
4111
  if (!line.includes('"assistant"')) {
4066
4112
  return void 0;
4067
4113
  }
@@ -4072,7 +4118,10 @@ var assistantRecordOf = (line) => {
4072
4118
  return void 0;
4073
4119
  }
4074
4120
  const record = asRecord5(parsed);
4075
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
4121
+ if (record === void 0 || record.type !== "assistant") {
4122
+ return void 0;
4123
+ }
4124
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
4076
4125
  return void 0;
4077
4126
  }
4078
4127
  const message = asRecord5(record.message);
@@ -4165,7 +4214,7 @@ var completeLinesEnd = (bytes, start) => {
4165
4214
  const lastNewline = bytes.lastIndexOf(10);
4166
4215
  return lastNewline < 0 ? start : start + lastNewline + 1;
4167
4216
  };
4168
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4217
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
4169
4218
  const length = Math.min(size, maxTailBytes);
4170
4219
  const start = size - length;
4171
4220
  const bytes = await readBytes(handle, start, length);
@@ -4175,7 +4224,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4175
4224
  lines.shift();
4176
4225
  }
4177
4226
  for (let index = lines.length - 1; index >= 0; index -= 1) {
4178
- const record = assistantRecordOf((lines[index] ?? "").trim());
4227
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
4179
4228
  if (record !== void 0) {
4180
4229
  return {
4181
4230
  turn: {
@@ -4189,10 +4238,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4189
4238
  }
4190
4239
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4191
4240
  });
4192
- var boundedTail = async (transcriptPath, options) => withTimeout(
4241
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
4193
4242
  readTail(
4194
4243
  transcriptPath,
4195
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4244
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
4245
+ agentId
4196
4246
  ),
4197
4247
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4198
4248
  { status: "unavailable", reason: "unreadable" }
@@ -4232,7 +4282,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
4232
4282
  let anonymous = 0;
4233
4283
  let model;
4234
4284
  for (const line of complete.split("\n")) {
4235
- const record = assistantRecordOf(line.trim());
4285
+ const record = assistantRecordOf(line.trim(), options.agentId);
4236
4286
  if (record === void 0) {
4237
4287
  continue;
4238
4288
  }
@@ -4294,6 +4344,20 @@ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
4294
4344
  };
4295
4345
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4296
4346
  var sourceDigest = (transcriptPath) => createHash2("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4347
+ var SUBAGENT_STOP = "SubagentStop";
4348
+ var agentIdOf = (record) => {
4349
+ const agentId = record.agent_id ?? record.agentId;
4350
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
4351
+ };
4352
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
4353
+ var subagentCursorScope = (payload) => {
4354
+ const record = asRecord5(payload);
4355
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
4356
+ return void 0;
4357
+ }
4358
+ const agentId = agentIdOf(record);
4359
+ return agentId === void 0 ? void 0 : `agent-${createHash2("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
4360
+ };
4297
4361
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4298
4362
  const fileSize = async (transcriptPath) => {
4299
4363
  try {
@@ -4303,6 +4367,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4303
4367
  return thrown?.code === "ENOENT" ? "absent" : void 0;
4304
4368
  }
4305
4369
  };
4370
+ const readOptions = (agentId) => ({
4371
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
4372
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
4373
+ ...agentId === void 0 ? {} : { agentId }
4374
+ });
4375
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
4376
+ const source = sourceDigest(transcriptPath);
4377
+ const attach = (model, usage, partial) => ({
4378
+ ...record,
4379
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4380
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4381
+ });
4382
+ if (fromOffset !== void 0) {
4383
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
4384
+ if (range.status === "found") {
4385
+ return {
4386
+ payload: attach(range.model, range.usage, false),
4387
+ cursor: { source, offset: range.endOffset },
4388
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4389
+ };
4390
+ }
4391
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4392
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4393
+ }
4394
+ }
4395
+ const tail = await boundedTail(transcriptPath, options, agentId);
4396
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4397
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4398
+ }
4399
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4400
+ return {
4401
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
4402
+ cursor: { source, offset: tail.endOffset },
4403
+ notes: [`${why}; attached the last request only (usage_partial)`]
4404
+ };
4405
+ };
4406
+ const skipAttached = async (payload, transcriptPath) => {
4407
+ const size = await fileSize(transcriptPath);
4408
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
4409
+ };
4306
4410
  const enrich = async (input) => {
4307
4411
  const unchanged = { payload: input.payload };
4308
4412
  const record = asRecord5(input.payload);
@@ -4310,6 +4414,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4310
4414
  return unchanged;
4311
4415
  }
4312
4416
  const eventName = eventNameOf(record);
4417
+ if (eventName === SUBAGENT_STOP) {
4418
+ const agentTranscriptPath = agentTranscriptPathOf(record);
4419
+ const agentId = agentIdOf(record);
4420
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
4421
+ return unchanged;
4422
+ }
4423
+ if (hasUsage(record)) {
4424
+ return skipAttached(input.payload, agentTranscriptPath);
4425
+ }
4426
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
4427
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
4428
+ }
4313
4429
  const transcriptPath = transcriptPathOf(record);
4314
4430
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4315
4431
  return unchanged;
@@ -4330,41 +4446,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4330
4446
  return unchanged;
4331
4447
  }
4332
4448
  if (hasUsage(record)) {
4333
- const size = await fileSize(transcriptPath);
4334
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4449
+ return skipAttached(input.payload, transcriptPath);
4335
4450
  }
4336
- const attach = (model, usage, partial) => ({
4337
- ...record,
4338
- ...record.model === void 0 && model !== void 0 ? { model } : {},
4339
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
4340
- });
4341
- if (cursor !== void 0) {
4342
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4343
- if (range.status === "found") {
4344
- return {
4345
- payload: attach(range.model, range.usage, false),
4346
- cursor: { source, offset: range.endOffset },
4347
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4348
- };
4349
- }
4350
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
4351
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4352
- }
4353
- }
4354
- const tail = await boundedTail(transcriptPath, options);
4355
- if (tail === TIMED_OUT || !("turn" in tail)) {
4356
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4357
- }
4358
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4359
- return {
4360
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4361
- cursor: { source, offset: tail.endOffset },
4362
- notes: [`${why}; attached the last request only (usage_partial)`]
4363
- };
4451
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
4364
4452
  };
4365
4453
  return Object.freeze({
4366
4454
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4367
4455
  providerId: CLAUDE_CODE_PROVIDER_ID,
4456
+ cursorScope: subagentCursorScope,
4368
4457
  enrich
4369
4458
  });
4370
4459
  };
@@ -7775,7 +7864,7 @@ var usageScopeOf = (event3) => {
7775
7864
  };
7776
7865
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
7777
7866
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
7778
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
7867
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
7779
7868
  var UNKNOWN_MODEL_ID = "unknown";
7780
7869
  var latestSessionModel = (events) => {
7781
7870
  let latest;
@@ -7843,7 +7932,17 @@ var createOtelHook = (deps) => {
7843
7932
  if (enricher.providerId !== providerId) {
7844
7933
  continue;
7845
7934
  }
7846
- const key = readCursorKey(enricher.id, sessionId);
7935
+ let scope;
7936
+ try {
7937
+ scope = enricher.cursorScope?.(current);
7938
+ } catch (thrown) {
7939
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
7940
+ "enricher.id": enricher.id,
7941
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
7942
+ });
7943
+ continue;
7944
+ }
7945
+ const key = readCursorKey(enricher.id, sessionId, scope);
7847
7946
  let cursor;
7848
7947
  try {
7849
7948
  const record = await deps.stateStore.read(key);
@@ -8944,7 +9043,7 @@ import {
8944
9043
  } from "@opentelemetry/semantic-conventions/incubating";
8945
9044
 
8946
9045
  // src/version.ts
8947
- var VERSION = "0.12.0";
9046
+ var VERSION = "0.13.1";
8948
9047
 
8949
9048
  // src/telemetry/export-identity.ts
8950
9049
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9270,7 +9369,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9270
9369
  const resolved = resolvePairing(group, anchor, correlation);
9271
9370
  const traceId = plan.traceId;
9272
9371
  const spanId = plan.spanId;
9273
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
9372
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
9373
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
9274
9374
  let name = group.ref.family;
9275
9375
  let kind = SpanKind.INTERNAL;
9276
9376
  let status = { code: SpanStatusCode.UNSET };
@@ -9494,7 +9594,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
9494
9594
  // persist something that should have been persisted.
9495
9595
  correlation === void 0 && correlationAvailable === void 0);
9496
9596
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
9497
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
9597
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
9498
9598
  return {
9499
9599
  group,
9500
9600
  anchor,
@@ -9514,6 +9614,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
9514
9614
  )
9515
9615
  };
9516
9616
  };
9617
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9618
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9517
9619
  var canonicalEventTraceIdentities = (events, options = {}) => {
9518
9620
  const layout = layoutBatch(events);
9519
9621
  const correlations = indexCorrelations(options.correlations);
@@ -9538,7 +9640,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
9538
9640
  });
9539
9641
  continue;
9540
9642
  }
9541
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
9643
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3) ?? resumedSessionParent(plan.group.ref, plan.correlation);
9542
9644
  identities.set(event3.eventId, {
9543
9645
  traceId: plan.traceId,
9544
9646
  spanId: plan.spanId,
@@ -9621,6 +9723,7 @@ var encodeRecord = (record) => ({
9621
9723
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
9622
9724
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9623
9725
  ...record.exported === true ? { exported: true } : {},
9726
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
9624
9727
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
9625
9728
  ...encodeAttributes(record.attributes)
9626
9729
  }
@@ -9644,6 +9747,7 @@ var decodeRecord = (attributes) => {
9644
9747
  return { kind: "corrupt" };
9645
9748
  }
9646
9749
  const exported = attributes["exported"] === true;
9750
+ const runKey = optionalString(attributes["runKey"]);
9647
9751
  const parentFamily = attributes["parentFamily"];
9648
9752
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
9649
9753
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -9658,6 +9762,7 @@ var decodeRecord = (attributes) => {
9658
9762
  ...endedAt === void 0 ? {} : { endedAt },
9659
9763
  ...parent === void 0 ? {} : { parent },
9660
9764
  ...exported ? { exported: true } : {},
9765
+ ...runKey === void 0 ? {} : { runKey },
9661
9766
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
9662
9767
  }
9663
9768
  };
@@ -9666,13 +9771,15 @@ var factsOf = (record) => ({
9666
9771
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
9667
9772
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9668
9773
  ...record.parent === void 0 ? {} : { parent: record.parent },
9669
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
9774
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
9775
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
9670
9776
  });
9671
9777
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
9672
9778
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
9673
9779
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
9674
9780
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
9675
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
9781
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
9782
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
9676
9783
  });
9677
9784
  var orphanClassificationOf = (reason) => {
9678
9785
  switch (reason) {
@@ -9732,10 +9839,12 @@ var createSpanCorrelator = (deps) => {
9732
9839
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
9733
9840
  }
9734
9841
  }
9842
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
9735
9843
  const fresh = {
9736
9844
  providerId: input.providerId,
9737
9845
  startEventId: input.eventId,
9738
9846
  startedAt: input.occurredAt,
9847
+ ...previouslyExported ? { runKey: input.eventId } : {},
9739
9848
  ...input.parent === void 0 ? {} : { parent: input.parent },
9740
9849
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9741
9850
  };
@@ -10214,6 +10323,9 @@ var deriveMetricObservations = (input) => {
10214
10323
  if (recovered !== void 0) {
10215
10324
  return end.occurredAt - recovered.startMillis;
10216
10325
  }
10326
+ if (end.subagentId !== void 0) {
10327
+ return void 0;
10328
+ }
10217
10329
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10218
10330
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10219
10331
  };
@@ -10595,7 +10707,7 @@ var createBoundedMemoryStateStore = (options) => {
10595
10707
 
10596
10708
  // src/state/filesystem-store.ts
10597
10709
  import { randomBytes as randomBytes2 } from "crypto";
10598
- import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10710
+ import { mkdir, open as open4, readFile, readdir, rename, stat as stat3, unlink, writeFile } from "fs/promises";
10599
10711
  import * as path5 from "path";
10600
10712
 
10601
10713
  // src/state/keys.ts
@@ -10617,8 +10729,7 @@ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex")
10617
10729
  // src/state/filesystem-store.ts
10618
10730
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
10619
10731
  var sleep = (millis) => new Promise((resolve5) => {
10620
- const timer = setTimeout(resolve5, millis);
10621
- timer.unref?.();
10732
+ setTimeout(resolve5, millis);
10622
10733
  });
10623
10734
  var wrapFsError = (thrown, operation) => {
10624
10735
  if (thrown instanceof Error) {
@@ -10738,14 +10849,29 @@ var createFilesystemStateStore = (options) => {
10738
10849
  }
10739
10850
  }
10740
10851
  const stale = await (async () => {
10852
+ let raw;
10853
+ try {
10854
+ raw = await readFile(filePath, "utf8");
10855
+ } catch (thrown) {
10856
+ return isErrnoException(thrown, "ENOENT") ? "gone" : true;
10857
+ }
10741
10858
  try {
10742
- const raw = await readFile(filePath, "utf8");
10743
10859
  const parsed = JSON.parse(raw);
10744
- return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
10860
+ if (typeof parsed.acquiredAt === "number") {
10861
+ return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
10862
+ }
10745
10863
  } catch {
10746
- return true;
10864
+ }
10865
+ try {
10866
+ const stats = await stat3(filePath);
10867
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
10868
+ } catch {
10869
+ return "gone";
10747
10870
  }
10748
10871
  })();
10872
+ if (stale === "gone") {
10873
+ continue;
10874
+ }
10749
10875
  if (stale) {
10750
10876
  await unlink(filePath).catch(() => void 0);
10751
10877
  continue;
@@ -10882,7 +11008,7 @@ var createFilesystemStateStore = (options) => {
10882
11008
 
10883
11009
  // src/telemetry/spool-queue.ts
10884
11010
  import { randomBytes as randomBytes3 } from "crypto";
10885
- 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";
11011
+ 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";
10886
11012
  import * as path6 from "path";
10887
11013
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10888
11014
  total: 0,
@@ -10928,7 +11054,7 @@ var readSpoolQueueStats = async (queueDir) => {
10928
11054
  let bytes = 0;
10929
11055
  for (const file of files) {
10930
11056
  try {
10931
- bytes += (await stat3(path6.join(queueDir, file))).size;
11057
+ bytes += (await stat4(path6.join(queueDir, file))).size;
10932
11058
  } catch {
10933
11059
  }
10934
11060
  }
@@ -10941,6 +11067,22 @@ var readSpoolQueueStats = async (queueDir) => {
10941
11067
  };
10942
11068
  };
10943
11069
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
11070
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
11071
+ var CLAIM_MARKER = ".claimed-";
11072
+ var isClaimOwnerAlive = (pid) => {
11073
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
11074
+ return true;
11075
+ }
11076
+ if (pid === process.pid) {
11077
+ return true;
11078
+ }
11079
+ try {
11080
+ process.kill(pid, 0);
11081
+ return true;
11082
+ } catch (thrown) {
11083
+ return thrown?.code !== "ESRCH";
11084
+ }
11085
+ };
10944
11086
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
10945
11087
  var createSpoolQueue = (options) => {
10946
11088
  const [providerSegment, installationSegment] = namespaceSegments(options);
@@ -11010,7 +11152,7 @@ var createSpoolQueue = (options) => {
11010
11152
  let bytes = 0;
11011
11153
  if (options.maxBytes !== void 0) {
11012
11154
  try {
11013
- bytes = (await stat3(path6.join(queueDir, name))).size;
11155
+ bytes = (await stat4(path6.join(queueDir, name))).size;
11014
11156
  } catch {
11015
11157
  continue;
11016
11158
  }
@@ -11090,9 +11232,33 @@ var createSpoolQueue = (options) => {
11090
11232
  await rename2(tmp, target);
11091
11233
  return { spooled: true };
11092
11234
  };
11235
+ const releaseStaleClaims = async () => {
11236
+ let entries;
11237
+ try {
11238
+ entries = await readdir2(queueDir);
11239
+ } catch {
11240
+ return;
11241
+ }
11242
+ const now = Date.now();
11243
+ for (const entry of entries) {
11244
+ const marker = entry.lastIndexOf(CLAIM_MARKER);
11245
+ if (marker <= 0) {
11246
+ continue;
11247
+ }
11248
+ const claimPath = path6.join(queueDir, entry);
11249
+ const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
11250
+ try {
11251
+ if (!isClaimOwnerAlive(owner) || now - (await stat4(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
11252
+ await rename2(claimPath, path6.join(queueDir, entry.slice(0, marker)));
11253
+ }
11254
+ } catch {
11255
+ }
11256
+ }
11257
+ };
11093
11258
  const drain = async (send, drainOptions) => {
11094
11259
  await ensureDirs();
11095
11260
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
11261
+ await releaseStaleClaims();
11096
11262
  let files = await listSorted();
11097
11263
  if (options.maxAgeMillis !== void 0) {
11098
11264
  const now = options.clock.now();
@@ -11115,7 +11281,16 @@ var createSpoolQueue = (options) => {
11115
11281
  if (fileName === void 0) {
11116
11282
  break;
11117
11283
  }
11118
- const filePath = path6.join(queueDir, fileName);
11284
+ const queuedPath = path6.join(queueDir, fileName);
11285
+ const filePath = path6.join(
11286
+ queueDir,
11287
+ `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes3(4).toString("hex")}`
11288
+ );
11289
+ try {
11290
+ await rename2(queuedPath, filePath);
11291
+ } catch {
11292
+ continue;
11293
+ }
11119
11294
  const quarantine = async (rejection) => {
11120
11295
  quarantined += 1;
11121
11296
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -11129,9 +11304,19 @@ var createSpoolQueue = (options) => {
11129
11304
  await unlink2(filePath).catch(() => void 0);
11130
11305
  }
11131
11306
  };
11307
+ let text;
11308
+ try {
11309
+ text = await readFile2(filePath, "utf8");
11310
+ } catch (thrown) {
11311
+ if (thrown?.code === "ENOENT") {
11312
+ continue;
11313
+ }
11314
+ await quarantine("unreadable");
11315
+ continue;
11316
+ }
11132
11317
  let parsed;
11133
11318
  try {
11134
- parsed = JSON.parse(await readFile2(filePath, "utf8"));
11319
+ parsed = JSON.parse(text);
11135
11320
  } catch {
11136
11321
  await quarantine("unparseable-json");
11137
11322
  continue;
@@ -11160,6 +11345,7 @@ var createSpoolQueue = (options) => {
11160
11345
  await unlink2(filePath).catch(() => void 0);
11161
11346
  drained += 1;
11162
11347
  } else {
11348
+ await rename2(filePath, queuedPath).catch(() => void 0);
11163
11349
  failed += 1;
11164
11350
  break;
11165
11351
  }
@@ -14424,7 +14610,7 @@ var resolveInstallPath = (location, roots) => path7.resolve(
14424
14610
 
14425
14611
  // src/install/document.ts
14426
14612
  import { randomBytes as randomBytes4 } from "crypto";
14427
- import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
14613
+ import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat5, unlink as unlink3 } from "fs/promises";
14428
14614
  import * as path8 from "path";
14429
14615
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14430
14616
  indent: " ",
@@ -14504,7 +14690,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14504
14690
  );
14505
14691
  let existingMode;
14506
14692
  try {
14507
- existingMode = (await stat4(filePath)).mode & 4095;
14693
+ existingMode = (await stat5(filePath)).mode & 4095;
14508
14694
  } catch (thrown) {
14509
14695
  if (!isErrnoException3(thrown, "ENOENT")) {
14510
14696
  throw thrown;
@@ -14529,7 +14715,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14529
14715
 
14530
14716
  // src/install/file-lock.ts
14531
14717
  import { randomBytes as randomBytes5 } from "crypto";
14532
- import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
14718
+ import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat6, unlink as unlink4 } from "fs/promises";
14533
14719
  import * as path9 from "path";
14534
14720
  var FileLockTimeoutError = class extends Error {
14535
14721
  constructor(lockPath, timeoutMillis) {
@@ -14594,7 +14780,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
14594
14780
  } catch {
14595
14781
  }
14596
14782
  try {
14597
- const stats = await stat5(lockPath);
14783
+ const stats = await stat6(lockPath);
14598
14784
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
14599
14785
  } catch (thrown) {
14600
14786
  return { stale: !isErrnoException4(thrown, "ENOENT") };