@osfactory/otel-hook 0.13.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.
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({
@@ -4612,7 +4615,13 @@ var normalizeClaudeHookPayload = (payload) => {
4612
4615
  if (record === void 0) {
4613
4616
  return payload;
4614
4617
  }
4615
- 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 };
4616
4625
  };
4617
4626
  var applyUsageShape = (record) => {
4618
4627
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -7677,7 +7686,7 @@ var createSystemClock = () => ({
7677
7686
 
7678
7687
  // src/state/filesystem-store.ts
7679
7688
  import { randomBytes } from "crypto";
7680
- 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";
7681
7690
  import * as path2 from "path";
7682
7691
 
7683
7692
  // src/state/async-lock.ts
@@ -7778,8 +7787,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7778
7787
  // src/state/filesystem-store.ts
7779
7788
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
7780
7789
  var sleep = (millis) => new Promise((resolve8) => {
7781
- const timer = setTimeout(resolve8, millis);
7782
- timer.unref?.();
7790
+ setTimeout(resolve8, millis);
7783
7791
  });
7784
7792
  var wrapFsError = (thrown, operation) => {
7785
7793
  if (thrown instanceof Error) {
@@ -7899,14 +7907,29 @@ var createFilesystemStateStore = (options) => {
7899
7907
  }
7900
7908
  }
7901
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
+ }
7902
7916
  try {
7903
- const raw = await readFile2(filePath, "utf8");
7904
7917
  const parsed = JSON.parse(raw);
7905
- 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
+ }
7906
7921
  } catch {
7907
- return true;
7922
+ }
7923
+ try {
7924
+ const stats = await stat(filePath);
7925
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
7926
+ } catch {
7927
+ return "gone";
7908
7928
  }
7909
7929
  })();
7930
+ if (stale === "gone") {
7931
+ continue;
7932
+ }
7910
7933
  if (stale) {
7911
7934
  await unlink(filePath).catch(() => void 0);
7912
7935
  continue;
@@ -8043,7 +8066,7 @@ var createFilesystemStateStore = (options) => {
8043
8066
 
8044
8067
  // src/telemetry/spool-queue.ts
8045
8068
  import { randomBytes as randomBytes2 } from "crypto";
8046
- 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";
8047
8070
  import * as path3 from "path";
8048
8071
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
8049
8072
  total: 0,
@@ -8089,7 +8112,7 @@ var readSpoolQueueStats = async (queueDir) => {
8089
8112
  let bytes = 0;
8090
8113
  for (const file of files) {
8091
8114
  try {
8092
- bytes += (await stat(path3.join(queueDir, file))).size;
8115
+ bytes += (await stat2(path3.join(queueDir, file))).size;
8093
8116
  } catch {
8094
8117
  }
8095
8118
  }
@@ -8102,6 +8125,22 @@ var readSpoolQueueStats = async (queueDir) => {
8102
8125
  };
8103
8126
  };
8104
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
+ };
8105
8144
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
8106
8145
  var createSpoolQueue = (options) => {
8107
8146
  const [providerSegment, installationSegment] = namespaceSegments(options);
@@ -8171,7 +8210,7 @@ var createSpoolQueue = (options) => {
8171
8210
  let bytes = 0;
8172
8211
  if (options.maxBytes !== void 0) {
8173
8212
  try {
8174
- bytes = (await stat(path3.join(queueDir, name))).size;
8213
+ bytes = (await stat2(path3.join(queueDir, name))).size;
8175
8214
  } catch {
8176
8215
  continue;
8177
8216
  }
@@ -8251,9 +8290,33 @@ var createSpoolQueue = (options) => {
8251
8290
  await rename2(tmp, target);
8252
8291
  return { spooled: true };
8253
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
+ };
8254
8316
  const drain = async (send, drainOptions) => {
8255
8317
  await ensureDirs();
8256
8318
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
8319
+ await releaseStaleClaims();
8257
8320
  let files = await listSorted();
8258
8321
  if (options.maxAgeMillis !== void 0) {
8259
8322
  const now = options.clock.now();
@@ -8276,7 +8339,16 @@ var createSpoolQueue = (options) => {
8276
8339
  if (fileName === void 0) {
8277
8340
  break;
8278
8341
  }
8279
- 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
+ }
8280
8352
  const quarantine = async (rejection) => {
8281
8353
  quarantined += 1;
8282
8354
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -8290,9 +8362,19 @@ var createSpoolQueue = (options) => {
8290
8362
  await unlink2(filePath).catch(() => void 0);
8291
8363
  }
8292
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
+ }
8293
8375
  let parsed;
8294
8376
  try {
8295
- parsed = JSON.parse(await readFile3(filePath, "utf8"));
8377
+ parsed = JSON.parse(text);
8296
8378
  } catch {
8297
8379
  await quarantine("unparseable-json");
8298
8380
  continue;
@@ -8321,6 +8403,7 @@ var createSpoolQueue = (options) => {
8321
8403
  await unlink2(filePath).catch(() => void 0);
8322
8404
  drained += 1;
8323
8405
  } else {
8406
+ await rename2(filePath, queuedPath).catch(() => void 0);
8324
8407
  failed += 1;
8325
8408
  break;
8326
8409
  }
@@ -8738,7 +8821,7 @@ import {
8738
8821
  } from "@opentelemetry/semantic-conventions/incubating";
8739
8822
 
8740
8823
  // src/version.ts
8741
- var VERSION = "0.13.0";
8824
+ var VERSION = "0.13.1";
8742
8825
 
8743
8826
  // src/telemetry/semconv.ts
8744
8827
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8974,7 +9057,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8974
9057
  const resolved = resolvePairing(group, anchor, correlation);
8975
9058
  const traceId = plan.traceId;
8976
9059
  const spanId = plan.spanId;
8977
- 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);
8978
9062
  let name = group.ref.family;
8979
9063
  let kind = SpanKind.INTERNAL;
8980
9064
  let status = { code: SpanStatusCode.UNSET };
@@ -9198,7 +9282,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
9198
9282
  // persist something that should have been persisted.
9199
9283
  correlation === void 0 && correlationAvailable === void 0);
9200
9284
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
9201
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
9285
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
9202
9286
  return {
9203
9287
  group,
9204
9288
  anchor,
@@ -9218,6 +9302,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
9218
9302
  )
9219
9303
  };
9220
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;
9221
9307
  var canonicalEventTraceIdentities = (events, options = {}) => {
9222
9308
  const layout = layoutBatch(events);
9223
9309
  const correlations = indexCorrelations(options.correlations);
@@ -9242,7 +9328,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
9242
9328
  });
9243
9329
  continue;
9244
9330
  }
9245
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
9331
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3) ?? resumedSessionParent(plan.group.ref, plan.correlation);
9246
9332
  identities.set(event3.eventId, {
9247
9333
  traceId: plan.traceId,
9248
9334
  spanId: plan.spanId,
@@ -11091,7 +11177,7 @@ var collectDoctorReport = async (command, io) => {
11091
11177
  let contextDirExists = false;
11092
11178
  if (contextDir !== void 0) {
11093
11179
  try {
11094
- contextDirExists = (await stat2(contextDir)).isDirectory();
11180
+ contextDirExists = (await stat3(contextDir)).isDirectory();
11095
11181
  } catch {
11096
11182
  contextDirExists = false;
11097
11183
  }
@@ -12217,7 +12303,7 @@ var resolveInstallPath = (location, roots) => path5.resolve(
12217
12303
 
12218
12304
  // src/install/document.ts
12219
12305
  import { randomBytes as randomBytes3 } from "crypto";
12220
- 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";
12221
12307
  import * as path6 from "path";
12222
12308
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12223
12309
  indent: " ",
@@ -12297,7 +12383,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12297
12383
  );
12298
12384
  let existingMode;
12299
12385
  try {
12300
- existingMode = (await stat3(filePath)).mode & 4095;
12386
+ existingMode = (await stat4(filePath)).mode & 4095;
12301
12387
  } catch (thrown) {
12302
12388
  if (!isErrnoException3(thrown, "ENOENT")) {
12303
12389
  throw thrown;
@@ -12322,7 +12408,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12322
12408
 
12323
12409
  // src/install/file-lock.ts
12324
12410
  import { randomBytes as randomBytes4 } from "crypto";
12325
- 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";
12326
12412
  import * as path7 from "path";
12327
12413
  var FileLockTimeoutError = class extends Error {
12328
12414
  constructor(lockPath, timeoutMillis) {
@@ -12387,7 +12473,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12387
12473
  } catch {
12388
12474
  }
12389
12475
  try {
12390
- const stats = await stat4(lockPath);
12476
+ const stats = await stat5(lockPath);
12391
12477
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12392
12478
  } catch (thrown) {
12393
12479
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -13310,6 +13396,7 @@ var encodeRecord = (record) => ({
13310
13396
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
13311
13397
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
13312
13398
  ...record.exported === true ? { exported: true } : {},
13399
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
13313
13400
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
13314
13401
  ...encodeAttributes(record.attributes)
13315
13402
  }
@@ -13333,6 +13420,7 @@ var decodeRecord = (attributes) => {
13333
13420
  return { kind: "corrupt" };
13334
13421
  }
13335
13422
  const exported = attributes["exported"] === true;
13423
+ const runKey = optionalString(attributes["runKey"]);
13336
13424
  const parentFamily = attributes["parentFamily"];
13337
13425
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
13338
13426
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -13347,6 +13435,7 @@ var decodeRecord = (attributes) => {
13347
13435
  ...endedAt === void 0 ? {} : { endedAt },
13348
13436
  ...parent === void 0 ? {} : { parent },
13349
13437
  ...exported ? { exported: true } : {},
13438
+ ...runKey === void 0 ? {} : { runKey },
13350
13439
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
13351
13440
  }
13352
13441
  };
@@ -13355,13 +13444,15 @@ var factsOf = (record) => ({
13355
13444
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
13356
13445
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
13357
13446
  ...record.parent === void 0 ? {} : { parent: record.parent },
13358
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
13447
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
13448
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
13359
13449
  });
13360
13450
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
13361
13451
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
13362
13452
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
13363
13453
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
13364
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
13454
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
13455
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
13365
13456
  });
13366
13457
  var orphanClassificationOf = (reason) => {
13367
13458
  switch (reason) {
@@ -13421,10 +13512,12 @@ var createSpanCorrelator = (deps) => {
13421
13512
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
13422
13513
  }
13423
13514
  }
13515
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
13424
13516
  const fresh = {
13425
13517
  providerId: input.providerId,
13426
13518
  startEventId: input.eventId,
13427
13519
  startedAt: input.occurredAt,
13520
+ ...previouslyExported ? { runKey: input.eventId } : {},
13428
13521
  ...input.parent === void 0 ? {} : { parent: input.parent },
13429
13522
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
13430
13523
  };
@@ -13763,7 +13856,7 @@ var createUsageAccumulator = (deps) => {
13763
13856
 
13764
13857
  // src/providers/claude/transcript.ts
13765
13858
  import { createHash as createHash5 } from "crypto";
13766
- import { open as open4, stat as stat5 } from "fs/promises";
13859
+ import { open as open4, stat as stat6 } from "fs/promises";
13767
13860
  import path10 from "path";
13768
13861
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13769
13862
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
@@ -13856,7 +13949,7 @@ var withTimeout = async (work, timeoutMillis, onError) => {
13856
13949
  var withRegularFile = async (transcriptPath, body) => {
13857
13950
  let info;
13858
13951
  try {
13859
- info = await stat5(transcriptPath);
13952
+ info = await stat6(transcriptPath);
13860
13953
  } catch {
13861
13954
  return { status: "unavailable", reason: "unreadable" };
13862
13955
  }
@@ -14003,7 +14096,7 @@ var subagentCursorScope = (payload) => {
14003
14096
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
14004
14097
  const fileSize = async (transcriptPath) => {
14005
14098
  try {
14006
- const info = await stat5(transcriptPath);
14099
+ const info = await stat6(transcriptPath);
14007
14100
  return info.isFile() ? info.size : void 0;
14008
14101
  } catch (thrown) {
14009
14102
  return thrown?.code === "ENOENT" ? "absent" : void 0;
@@ -15333,7 +15426,7 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
15333
15426
  };
15334
15427
 
15335
15428
  // src/runtime/git-worktree.ts
15336
- import { lstat, open as open6, stat as stat6 } from "fs/promises";
15429
+ import { lstat, open as open6, stat as stat7 } from "fs/promises";
15337
15430
  import * as path13 from "path";
15338
15431
  var MAX_WORKTREE_WALK_DEPTH = 128;
15339
15432
  var MAX_GIT_FILE_BYTES = 4096;
@@ -15386,7 +15479,7 @@ var isMissing = async (filePath) => {
15386
15479
  };
15387
15480
  var isDirectory = async (directory) => {
15388
15481
  try {
15389
- return (await stat6(directory)).isDirectory();
15482
+ return (await stat7(directory)).isDirectory();
15390
15483
  } catch {
15391
15484
  return false;
15392
15485
  }
@@ -15405,7 +15498,7 @@ var probeDirectory = async (directory) => {
15405
15498
  const dotGit = path13.join(directory, ".git");
15406
15499
  let info;
15407
15500
  try {
15408
- info = await stat6(dotGit);
15501
+ info = await stat7(dotGit);
15409
15502
  } catch {
15410
15503
  return ABSENT;
15411
15504
  }