@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/cli.js CHANGED
@@ -3218,7 +3218,7 @@ var createCliLogger = (io, level) => createStderrLogger({
3218
3218
  var readIdentityFile = readJsonFile;
3219
3219
 
3220
3220
  // src/cli/doctor.ts
3221
- import { readdir as readdir3, stat as stat2 } from "fs/promises";
3221
+ import { readdir as readdir3, stat as stat3 } from "fs/promises";
3222
3222
  import * as path4 from "path";
3223
3223
 
3224
3224
  // src/diagnostics/health.ts
@@ -4243,7 +4243,10 @@ var postToolUseFailurePayloadSchema = z19.object({
4243
4243
  hook_event_name: z19.literal("PostToolUseFailure"),
4244
4244
  tool_name: z19.string().min(1),
4245
4245
  tool_input: z19.unknown().optional(),
4246
- tool_error: z19.unknown(),
4246
+ // Optional: a failure that names no message still ends its tool call. The
4247
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
4248
+ // `normalizeClaudeHookPayload`.
4249
+ tool_error: z19.unknown().optional(),
4247
4250
  tool_use_id: z19.string().min(1)
4248
4251
  });
4249
4252
  var permissionRequestPayloadSchema = z19.object({
@@ -4267,7 +4270,16 @@ var subagentStopPayloadSchema = z19.object({
4267
4270
  last_assistant_message: z19.string().optional(),
4268
4271
  /** True when this stop fired because a hook continued the subagent's turn. */
4269
4272
  stop_hook_active: z19.boolean().optional(),
4270
- usage: claudeUsageSchema.optional()
4273
+ /**
4274
+ * The subagent run's tokens since its previous stop — harness- or
4275
+ * enricher-supplied, never upstream. Reported on the subagent's own
4276
+ * generation, never on the parent turn (issue #68).
4277
+ */
4278
+ usage: claudeUsageSchema.optional(),
4279
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
4280
+ model: z19.string().min(1).max(256).optional().catch(void 0),
4281
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4282
+ usage_partial: z19.boolean().optional().catch(void 0)
4271
4283
  });
4272
4284
  var preCompactPayloadSchema = z19.object({
4273
4285
  ...commonFields2,
@@ -4603,7 +4615,13 @@ var normalizeClaudeHookPayload = (payload) => {
4603
4615
  if (record === void 0) {
4604
4616
  return payload;
4605
4617
  }
4606
- return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
4618
+ return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));
4619
+ };
4620
+ var applyToolFailureShape = (record) => {
4621
+ if (record.hook_event_name !== "PostToolUseFailure" || record.tool_error !== void 0 || record.error === void 0) {
4622
+ return record;
4623
+ }
4624
+ return { ...record, tool_error: record.error };
4607
4625
  };
4608
4626
  var applyUsageShape = (record) => {
4609
4627
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -4865,6 +4883,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
4865
4883
  WebFetch: "network",
4866
4884
  WebSearch: "network",
4867
4885
  Task: "delegate",
4886
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
4887
+ Agent: "delegate",
4868
4888
  TodoWrite: "other",
4869
4889
  ExitPlanMode: "other",
4870
4890
  AskUserQuestion: "other",
@@ -5038,14 +5058,39 @@ var parseClaudeCode = (input, context) => {
5038
5058
  delegationDepth: 1
5039
5059
  });
5040
5060
  break;
5041
- case "SubagentStop":
5061
+ case "SubagentStop": {
5062
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
5063
+ if (usage.usage !== void 0 || payload.model !== void 0) {
5064
+ const generationId = context.ids.newOpaqueId([
5065
+ "claude-subagent-generation",
5066
+ payload.session_id,
5067
+ payload.agent_id,
5068
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
5069
+ ]);
5070
+ const models = generationModels(payload.model, void 0);
5071
+ factory.build({ type: "generation.start", generationId, model: models.request });
5072
+ factory.build({
5073
+ type: "generation.end",
5074
+ generationId,
5075
+ model: models.response,
5076
+ outcome: "ok",
5077
+ outputContent: [
5078
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
5079
+ kind: "response",
5080
+ role: "assistant",
5081
+ text: payload.last_assistant_message
5082
+ })
5083
+ ],
5084
+ ...usage
5085
+ });
5086
+ }
5042
5087
  factory.build({
5043
5088
  type: "subagent.end",
5044
5089
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
5045
- outcome: "ok",
5046
- ...withUsage(payload.usage)
5090
+ outcome: "ok"
5047
5091
  });
5048
5092
  break;
5093
+ }
5049
5094
  case "PreCompact":
5050
5095
  return {
5051
5096
  status: "ignored",
@@ -7641,7 +7686,7 @@ var createSystemClock = () => ({
7641
7686
 
7642
7687
  // src/state/filesystem-store.ts
7643
7688
  import { randomBytes } from "crypto";
7644
- import { mkdir, open, readFile as readFile2, readdir, rename, unlink, writeFile } from "fs/promises";
7689
+ import { mkdir, open, readFile as readFile2, readdir, rename, stat, unlink, writeFile } from "fs/promises";
7645
7690
  import * as path2 from "path";
7646
7691
 
7647
7692
  // src/state/async-lock.ts
@@ -7742,8 +7787,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7742
7787
  // src/state/filesystem-store.ts
7743
7788
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
7744
7789
  var sleep = (millis) => new Promise((resolve8) => {
7745
- const timer = setTimeout(resolve8, millis);
7746
- timer.unref?.();
7790
+ setTimeout(resolve8, millis);
7747
7791
  });
7748
7792
  var wrapFsError = (thrown, operation) => {
7749
7793
  if (thrown instanceof Error) {
@@ -7863,14 +7907,29 @@ var createFilesystemStateStore = (options) => {
7863
7907
  }
7864
7908
  }
7865
7909
  const stale = await (async () => {
7910
+ let raw;
7911
+ try {
7912
+ raw = await readFile2(filePath, "utf8");
7913
+ } catch (thrown) {
7914
+ return isErrnoException(thrown, "ENOENT") ? "gone" : true;
7915
+ }
7866
7916
  try {
7867
- const raw = await readFile2(filePath, "utf8");
7868
7917
  const parsed = JSON.parse(raw);
7869
- return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
7918
+ if (typeof parsed.acquiredAt === "number") {
7919
+ return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
7920
+ }
7921
+ } catch {
7922
+ }
7923
+ try {
7924
+ const stats = await stat(filePath);
7925
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
7870
7926
  } catch {
7871
- return true;
7927
+ return "gone";
7872
7928
  }
7873
7929
  })();
7930
+ if (stale === "gone") {
7931
+ continue;
7932
+ }
7874
7933
  if (stale) {
7875
7934
  await unlink(filePath).catch(() => void 0);
7876
7935
  continue;
@@ -8007,7 +8066,7 @@ var createFilesystemStateStore = (options) => {
8007
8066
 
8008
8067
  // src/telemetry/spool-queue.ts
8009
8068
  import { randomBytes as randomBytes2 } from "crypto";
8010
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, stat, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8069
+ import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8011
8070
  import * as path3 from "path";
8012
8071
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
8013
8072
  total: 0,
@@ -8053,7 +8112,7 @@ var readSpoolQueueStats = async (queueDir) => {
8053
8112
  let bytes = 0;
8054
8113
  for (const file of files) {
8055
8114
  try {
8056
- bytes += (await stat(path3.join(queueDir, file))).size;
8115
+ bytes += (await stat2(path3.join(queueDir, file))).size;
8057
8116
  } catch {
8058
8117
  }
8059
8118
  }
@@ -8066,6 +8125,22 @@ var readSpoolQueueStats = async (queueDir) => {
8066
8125
  };
8067
8126
  };
8068
8127
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
8128
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
8129
+ var CLAIM_MARKER = ".claimed-";
8130
+ var isClaimOwnerAlive = (pid) => {
8131
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
8132
+ return true;
8133
+ }
8134
+ if (pid === process.pid) {
8135
+ return true;
8136
+ }
8137
+ try {
8138
+ process.kill(pid, 0);
8139
+ return true;
8140
+ } catch (thrown) {
8141
+ return thrown?.code !== "ESRCH";
8142
+ }
8143
+ };
8069
8144
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
8070
8145
  var createSpoolQueue = (options) => {
8071
8146
  const [providerSegment, installationSegment] = namespaceSegments(options);
@@ -8135,7 +8210,7 @@ var createSpoolQueue = (options) => {
8135
8210
  let bytes = 0;
8136
8211
  if (options.maxBytes !== void 0) {
8137
8212
  try {
8138
- bytes = (await stat(path3.join(queueDir, name))).size;
8213
+ bytes = (await stat2(path3.join(queueDir, name))).size;
8139
8214
  } catch {
8140
8215
  continue;
8141
8216
  }
@@ -8215,9 +8290,33 @@ var createSpoolQueue = (options) => {
8215
8290
  await rename2(tmp, target);
8216
8291
  return { spooled: true };
8217
8292
  };
8293
+ const releaseStaleClaims = async () => {
8294
+ let entries;
8295
+ try {
8296
+ entries = await readdir2(queueDir);
8297
+ } catch {
8298
+ return;
8299
+ }
8300
+ const now = Date.now();
8301
+ for (const entry of entries) {
8302
+ const marker = entry.lastIndexOf(CLAIM_MARKER);
8303
+ if (marker <= 0) {
8304
+ continue;
8305
+ }
8306
+ const claimPath = path3.join(queueDir, entry);
8307
+ const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
8308
+ try {
8309
+ if (!isClaimOwnerAlive(owner) || now - (await stat2(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
8310
+ await rename2(claimPath, path3.join(queueDir, entry.slice(0, marker)));
8311
+ }
8312
+ } catch {
8313
+ }
8314
+ }
8315
+ };
8218
8316
  const drain = async (send, drainOptions) => {
8219
8317
  await ensureDirs();
8220
8318
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
8319
+ await releaseStaleClaims();
8221
8320
  let files = await listSorted();
8222
8321
  if (options.maxAgeMillis !== void 0) {
8223
8322
  const now = options.clock.now();
@@ -8240,7 +8339,16 @@ var createSpoolQueue = (options) => {
8240
8339
  if (fileName === void 0) {
8241
8340
  break;
8242
8341
  }
8243
- const filePath = path3.join(queueDir, fileName);
8342
+ const queuedPath = path3.join(queueDir, fileName);
8343
+ const filePath = path3.join(
8344
+ queueDir,
8345
+ `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes2(4).toString("hex")}`
8346
+ );
8347
+ try {
8348
+ await rename2(queuedPath, filePath);
8349
+ } catch {
8350
+ continue;
8351
+ }
8244
8352
  const quarantine = async (rejection) => {
8245
8353
  quarantined += 1;
8246
8354
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -8254,9 +8362,19 @@ var createSpoolQueue = (options) => {
8254
8362
  await unlink2(filePath).catch(() => void 0);
8255
8363
  }
8256
8364
  };
8365
+ let text;
8366
+ try {
8367
+ text = await readFile3(filePath, "utf8");
8368
+ } catch (thrown) {
8369
+ if (thrown?.code === "ENOENT") {
8370
+ continue;
8371
+ }
8372
+ await quarantine("unreadable");
8373
+ continue;
8374
+ }
8257
8375
  let parsed;
8258
8376
  try {
8259
- parsed = JSON.parse(await readFile3(filePath, "utf8"));
8377
+ parsed = JSON.parse(text);
8260
8378
  } catch {
8261
8379
  await quarantine("unparseable-json");
8262
8380
  continue;
@@ -8285,6 +8403,7 @@ var createSpoolQueue = (options) => {
8285
8403
  await unlink2(filePath).catch(() => void 0);
8286
8404
  drained += 1;
8287
8405
  } else {
8406
+ await rename2(filePath, queuedPath).catch(() => void 0);
8288
8407
  failed += 1;
8289
8408
  break;
8290
8409
  }
@@ -8702,7 +8821,7 @@ import {
8702
8821
  } from "@opentelemetry/semantic-conventions/incubating";
8703
8822
 
8704
8823
  // src/version.ts
8705
- var VERSION = "0.12.0";
8824
+ var VERSION = "0.13.1";
8706
8825
 
8707
8826
  // src/telemetry/semconv.ts
8708
8827
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8938,7 +9057,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8938
9057
  const resolved = resolvePairing(group, anchor, correlation);
8939
9058
  const traceId = plan.traceId;
8940
9059
  const spanId = plan.spanId;
8941
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
9060
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
9061
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
8942
9062
  let name = group.ref.family;
8943
9063
  let kind = SpanKind.INTERNAL;
8944
9064
  let status = { code: SpanStatusCode.UNSET };
@@ -9162,7 +9282,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
9162
9282
  // persist something that should have been persisted.
9163
9283
  correlation === void 0 && correlationAvailable === void 0);
9164
9284
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
9165
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
9285
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
9166
9286
  return {
9167
9287
  group,
9168
9288
  anchor,
@@ -9182,6 +9302,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
9182
9302
  )
9183
9303
  };
9184
9304
  };
9305
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9306
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9185
9307
  var canonicalEventTraceIdentities = (events, options = {}) => {
9186
9308
  const layout = layoutBatch(events);
9187
9309
  const correlations = indexCorrelations(options.correlations);
@@ -9206,7 +9328,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
9206
9328
  });
9207
9329
  continue;
9208
9330
  }
9209
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
9331
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3) ?? resumedSessionParent(plan.group.ref, plan.correlation);
9210
9332
  identities.set(event3.eventId, {
9211
9333
  traceId: plan.traceId,
9212
9334
  spanId: plan.spanId,
@@ -10222,6 +10344,9 @@ var deriveMetricObservations = (input) => {
10222
10344
  if (recovered !== void 0) {
10223
10345
  return end.occurredAt - recovered.startMillis;
10224
10346
  }
10347
+ if (end.subagentId !== void 0) {
10348
+ return void 0;
10349
+ }
10225
10350
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10226
10351
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10227
10352
  };
@@ -11052,7 +11177,7 @@ var collectDoctorReport = async (command, io) => {
11052
11177
  let contextDirExists = false;
11053
11178
  if (contextDir !== void 0) {
11054
11179
  try {
11055
- contextDirExists = (await stat2(contextDir)).isDirectory();
11180
+ contextDirExists = (await stat3(contextDir)).isDirectory();
11056
11181
  } catch {
11057
11182
  contextDirExists = false;
11058
11183
  }
@@ -12178,7 +12303,7 @@ var resolveInstallPath = (location, roots) => path5.resolve(
12178
12303
 
12179
12304
  // src/install/document.ts
12180
12305
  import { randomBytes as randomBytes3 } from "crypto";
12181
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
12306
+ import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
12182
12307
  import * as path6 from "path";
12183
12308
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12184
12309
  indent: " ",
@@ -12258,7 +12383,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12258
12383
  );
12259
12384
  let existingMode;
12260
12385
  try {
12261
- existingMode = (await stat3(filePath)).mode & 4095;
12386
+ existingMode = (await stat4(filePath)).mode & 4095;
12262
12387
  } catch (thrown) {
12263
12388
  if (!isErrnoException3(thrown, "ENOENT")) {
12264
12389
  throw thrown;
@@ -12283,7 +12408,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12283
12408
 
12284
12409
  // src/install/file-lock.ts
12285
12410
  import { randomBytes as randomBytes4 } from "crypto";
12286
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12411
+ import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
12287
12412
  import * as path7 from "path";
12288
12413
  var FileLockTimeoutError = class extends Error {
12289
12414
  constructor(lockPath, timeoutMillis) {
@@ -12348,7 +12473,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12348
12473
  } catch {
12349
12474
  }
12350
12475
  try {
12351
- const stats = await stat4(lockPath);
12476
+ const stats = await stat5(lockPath);
12352
12477
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12353
12478
  } catch (thrown) {
12354
12479
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -13271,6 +13396,7 @@ var encodeRecord = (record) => ({
13271
13396
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
13272
13397
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
13273
13398
  ...record.exported === true ? { exported: true } : {},
13399
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
13274
13400
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
13275
13401
  ...encodeAttributes(record.attributes)
13276
13402
  }
@@ -13294,6 +13420,7 @@ var decodeRecord = (attributes) => {
13294
13420
  return { kind: "corrupt" };
13295
13421
  }
13296
13422
  const exported = attributes["exported"] === true;
13423
+ const runKey = optionalString(attributes["runKey"]);
13297
13424
  const parentFamily = attributes["parentFamily"];
13298
13425
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
13299
13426
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -13308,6 +13435,7 @@ var decodeRecord = (attributes) => {
13308
13435
  ...endedAt === void 0 ? {} : { endedAt },
13309
13436
  ...parent === void 0 ? {} : { parent },
13310
13437
  ...exported ? { exported: true } : {},
13438
+ ...runKey === void 0 ? {} : { runKey },
13311
13439
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
13312
13440
  }
13313
13441
  };
@@ -13316,13 +13444,15 @@ var factsOf = (record) => ({
13316
13444
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
13317
13445
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
13318
13446
  ...record.parent === void 0 ? {} : { parent: record.parent },
13319
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
13447
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
13448
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
13320
13449
  });
13321
13450
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
13322
13451
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
13323
13452
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
13324
13453
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
13325
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
13454
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
13455
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
13326
13456
  });
13327
13457
  var orphanClassificationOf = (reason) => {
13328
13458
  switch (reason) {
@@ -13382,10 +13512,12 @@ var createSpanCorrelator = (deps) => {
13382
13512
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
13383
13513
  }
13384
13514
  }
13515
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
13385
13516
  const fresh = {
13386
13517
  providerId: input.providerId,
13387
13518
  startEventId: input.eventId,
13388
13519
  startedAt: input.occurredAt,
13520
+ ...previouslyExported ? { runKey: input.eventId } : {},
13389
13521
  ...input.parent === void 0 ? {} : { parent: input.parent },
13390
13522
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
13391
13523
  };
@@ -13724,7 +13856,7 @@ var createUsageAccumulator = (deps) => {
13724
13856
 
13725
13857
  // src/providers/claude/transcript.ts
13726
13858
  import { createHash as createHash5 } from "crypto";
13727
- import { open as open4, stat as stat5 } from "fs/promises";
13859
+ import { open as open4, stat as stat6 } from "fs/promises";
13728
13860
  import path10 from "path";
13729
13861
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13730
13862
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
@@ -13747,7 +13879,8 @@ var clamp = (value, fallback, min, max) => {
13747
13879
  };
13748
13880
  var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13749
13881
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
13750
- var assistantRecordOf = (line) => {
13882
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
13883
+ var assistantRecordOf = (line, agentId) => {
13751
13884
  if (!line.includes('"assistant"')) {
13752
13885
  return void 0;
13753
13886
  }
@@ -13758,7 +13891,10 @@ var assistantRecordOf = (line) => {
13758
13891
  return void 0;
13759
13892
  }
13760
13893
  const record = asRecord7(parsed);
13761
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
13894
+ if (record === void 0 || record.type !== "assistant") {
13895
+ return void 0;
13896
+ }
13897
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
13762
13898
  return void 0;
13763
13899
  }
13764
13900
  const message = asRecord7(record.message);
@@ -13813,7 +13949,7 @@ var withTimeout = async (work, timeoutMillis, onError) => {
13813
13949
  var withRegularFile = async (transcriptPath, body) => {
13814
13950
  let info;
13815
13951
  try {
13816
- info = await stat5(transcriptPath);
13952
+ info = await stat6(transcriptPath);
13817
13953
  } catch {
13818
13954
  return { status: "unavailable", reason: "unreadable" };
13819
13955
  }
@@ -13851,7 +13987,7 @@ var completeLinesEnd = (bytes, start) => {
13851
13987
  const lastNewline = bytes.lastIndexOf(10);
13852
13988
  return lastNewline < 0 ? start : start + lastNewline + 1;
13853
13989
  };
13854
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
13990
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
13855
13991
  const length = Math.min(size, maxTailBytes);
13856
13992
  const start = size - length;
13857
13993
  const bytes = await readBytes(handle, start, length);
@@ -13861,7 +13997,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
13861
13997
  lines.shift();
13862
13998
  }
13863
13999
  for (let index = lines.length - 1; index >= 0; index -= 1) {
13864
- const record = assistantRecordOf((lines[index] ?? "").trim());
14000
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
13865
14001
  if (record !== void 0) {
13866
14002
  return {
13867
14003
  turn: {
@@ -13875,10 +14011,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
13875
14011
  }
13876
14012
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
13877
14013
  });
13878
- var boundedTail = async (transcriptPath, options) => withTimeout(
14014
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
13879
14015
  readTail(
13880
14016
  transcriptPath,
13881
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
14017
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
14018
+ agentId
13882
14019
  ),
13883
14020
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
13884
14021
  { status: "unavailable", reason: "unreadable" }
@@ -13908,7 +14045,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
13908
14045
  let anonymous = 0;
13909
14046
  let model;
13910
14047
  for (const line of complete.split("\n")) {
13911
- const record = assistantRecordOf(line.trim());
14048
+ const record = assistantRecordOf(line.trim(), options.agentId);
13912
14049
  if (record === void 0) {
13913
14050
  continue;
13914
14051
  }
@@ -13942,15 +14079,69 @@ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
13942
14079
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
13943
14080
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
13944
14081
  var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
14082
+ var SUBAGENT_STOP = "SubagentStop";
14083
+ var agentIdOf = (record) => {
14084
+ const agentId = record.agent_id ?? record.agentId;
14085
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
14086
+ };
14087
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
14088
+ var subagentCursorScope = (payload) => {
14089
+ const record = asRecord7(payload);
14090
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
14091
+ return void 0;
14092
+ }
14093
+ const agentId = agentIdOf(record);
14094
+ return agentId === void 0 ? void 0 : `agent-${createHash5("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14095
+ };
13945
14096
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
13946
14097
  const fileSize = async (transcriptPath) => {
13947
14098
  try {
13948
- const info = await stat5(transcriptPath);
14099
+ const info = await stat6(transcriptPath);
13949
14100
  return info.isFile() ? info.size : void 0;
13950
14101
  } catch (thrown) {
13951
14102
  return thrown?.code === "ENOENT" ? "absent" : void 0;
13952
14103
  }
13953
14104
  };
14105
+ const readOptions = (agentId) => ({
14106
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
14107
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
14108
+ ...agentId === void 0 ? {} : { agentId }
14109
+ });
14110
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
14111
+ const source = sourceDigest(transcriptPath);
14112
+ const attach = (model, usage, partial) => ({
14113
+ ...record,
14114
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
14115
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
14116
+ });
14117
+ if (fromOffset !== void 0) {
14118
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
14119
+ if (range.status === "found") {
14120
+ return {
14121
+ payload: attach(range.model, range.usage, false),
14122
+ cursor: { source, offset: range.endOffset },
14123
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
14124
+ };
14125
+ }
14126
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
14127
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
14128
+ }
14129
+ }
14130
+ const tail = await boundedTail(transcriptPath, options, agentId);
14131
+ if (tail === TIMED_OUT || !("turn" in tail)) {
14132
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
14133
+ }
14134
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
14135
+ return {
14136
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
14137
+ cursor: { source, offset: tail.endOffset },
14138
+ notes: [`${why}; attached the last request only (usage_partial)`]
14139
+ };
14140
+ };
14141
+ const skipAttached = async (payload, transcriptPath) => {
14142
+ const size = await fileSize(transcriptPath);
14143
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
14144
+ };
13954
14145
  const enrich = async (input) => {
13955
14146
  const unchanged = { payload: input.payload };
13956
14147
  const record = asRecord7(input.payload);
@@ -13958,6 +14149,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13958
14149
  return unchanged;
13959
14150
  }
13960
14151
  const eventName = eventNameOf(record);
14152
+ if (eventName === SUBAGENT_STOP) {
14153
+ const agentTranscriptPath = agentTranscriptPathOf(record);
14154
+ const agentId = agentIdOf(record);
14155
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
14156
+ return unchanged;
14157
+ }
14158
+ if (hasUsage(record)) {
14159
+ return skipAttached(input.payload, agentTranscriptPath);
14160
+ }
14161
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
14162
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
14163
+ }
13961
14164
  const transcriptPath = transcriptPathOf(record);
13962
14165
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
13963
14166
  return unchanged;
@@ -13978,41 +14181,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13978
14181
  return unchanged;
13979
14182
  }
13980
14183
  if (hasUsage(record)) {
13981
- const size = await fileSize(transcriptPath);
13982
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
13983
- }
13984
- const attach = (model, usage, partial) => ({
13985
- ...record,
13986
- ...record.model === void 0 && model !== void 0 ? { model } : {},
13987
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
13988
- });
13989
- if (cursor !== void 0) {
13990
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
13991
- if (range.status === "found") {
13992
- return {
13993
- payload: attach(range.model, range.usage, false),
13994
- cursor: { source, offset: range.endOffset },
13995
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
13996
- };
13997
- }
13998
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
13999
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
14000
- }
14001
- }
14002
- const tail = await boundedTail(transcriptPath, options);
14003
- if (tail === TIMED_OUT || !("turn" in tail)) {
14004
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
14184
+ return skipAttached(input.payload, transcriptPath);
14005
14185
  }
14006
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
14007
- return {
14008
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
14009
- cursor: { source, offset: tail.endOffset },
14010
- notes: [`${why}; attached the last request only (usage_partial)`]
14011
- };
14186
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
14012
14187
  };
14013
14188
  return Object.freeze({
14014
14189
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
14015
14190
  providerId: CLAUDE_CODE_PROVIDER_ID,
14191
+ cursorScope: subagentCursorScope,
14016
14192
  enrich
14017
14193
  });
14018
14194
  };
@@ -14430,7 +14606,7 @@ var usageScopeOf = (event3) => {
14430
14606
  };
14431
14607
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
14432
14608
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
14433
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
14609
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
14434
14610
  var UNKNOWN_MODEL_ID = "unknown";
14435
14611
  var latestSessionModel = (events) => {
14436
14612
  let latest;
@@ -14498,7 +14674,17 @@ var createOtelHook = (deps) => {
14498
14674
  if (enricher.providerId !== providerId) {
14499
14675
  continue;
14500
14676
  }
14501
- const key = readCursorKey(enricher.id, sessionId);
14677
+ let scope;
14678
+ try {
14679
+ scope = enricher.cursorScope?.(current);
14680
+ } catch (thrown) {
14681
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
14682
+ "enricher.id": enricher.id,
14683
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
14684
+ });
14685
+ continue;
14686
+ }
14687
+ const key = readCursorKey(enricher.id, sessionId, scope);
14502
14688
  let cursor;
14503
14689
  try {
14504
14690
  const record = await deps.stateStore.read(key);
@@ -15240,7 +15426,7 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
15240
15426
  };
15241
15427
 
15242
15428
  // src/runtime/git-worktree.ts
15243
- import { lstat, open as open6, stat as stat6 } from "fs/promises";
15429
+ import { lstat, open as open6, stat as stat7 } from "fs/promises";
15244
15430
  import * as path13 from "path";
15245
15431
  var MAX_WORKTREE_WALK_DEPTH = 128;
15246
15432
  var MAX_GIT_FILE_BYTES = 4096;
@@ -15293,7 +15479,7 @@ var isMissing = async (filePath) => {
15293
15479
  };
15294
15480
  var isDirectory = async (directory) => {
15295
15481
  try {
15296
- return (await stat6(directory)).isDirectory();
15482
+ return (await stat7(directory)).isDirectory();
15297
15483
  } catch {
15298
15484
  return false;
15299
15485
  }
@@ -15312,7 +15498,7 @@ var probeDirectory = async (directory) => {
15312
15498
  const dotGit = path13.join(directory, ".git");
15313
15499
  let info;
15314
15500
  try {
15315
- info = await stat6(dotGit);
15501
+ info = await stat7(dotGit);
15316
15502
  } catch {
15317
15503
  return ABSENT;
15318
15504
  }