@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.
@@ -7,13 +7,13 @@ import { P as ProviderRegistry } from './registry-BKQhhIO3.js';
7
7
  import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-D5imE0Qc.js';
8
8
  import { C as Clock, I as IdGenerator, d as Logger, W as WorktreeLocator, P as PayloadEnricher, S as SessionContextReader } from './ports-DhpSDIkp.js';
9
9
  import { F as FilesystemStateStore } from './filesystem-store-B3CpiIRl.js';
10
- import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-Bey2djRk.js';
10
+ import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-DUeQKr_C.js';
11
11
  import 'zod';
12
12
  import './primitives-CJ8-rn-f.js';
13
13
  import './taxonomy-DwhTtuWd.js';
14
14
  import '@opentelemetry/api';
15
15
  import './events-fcomX6d5.js';
16
- import './metric-model-CFIeUwqd.js';
16
+ import './metric-model-B4lIuk6i.js';
17
17
  import '@opentelemetry/core';
18
18
  import '@opentelemetry/resources';
19
19
  import '@opentelemetry/sdk-trace';
@@ -2419,7 +2419,7 @@ import {
2419
2419
  } from "@opentelemetry/semantic-conventions/incubating";
2420
2420
 
2421
2421
  // src/version.ts
2422
- var VERSION = "0.13.0";
2422
+ var VERSION = "0.13.1";
2423
2423
 
2424
2424
  // src/telemetry/semconv.ts
2425
2425
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -2655,7 +2655,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2655
2655
  const resolved = resolvePairing(group, anchor, correlation);
2656
2656
  const traceId = plan.traceId;
2657
2657
  const spanId = plan.spanId;
2658
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
2658
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
2659
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
2659
2660
  let name = group.ref.family;
2660
2661
  let kind = SpanKind.INTERNAL;
2661
2662
  let status = { code: SpanStatusCode.UNSET };
@@ -2879,7 +2880,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
2879
2880
  // persist something that should have been persisted.
2880
2881
  correlation === void 0 && correlationAvailable === void 0);
2881
2882
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
2882
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
2883
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
2883
2884
  return {
2884
2885
  group,
2885
2886
  anchor,
@@ -2899,6 +2900,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
2899
2900
  )
2900
2901
  };
2901
2902
  };
2903
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
2904
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
2902
2905
  var canonicalEventTraceIdentities = (events, options = {}) => {
2903
2906
  const layout = layoutBatch(events);
2904
2907
  const correlations = indexCorrelations(options.correlations);
@@ -2923,7 +2926,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
2923
2926
  });
2924
2927
  continue;
2925
2928
  }
2926
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
2929
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event2) ?? resumedSessionParent(plan.group.ref, plan.correlation);
2927
2930
  identities.set(event2.eventId, {
2928
2931
  traceId: plan.traceId,
2929
2932
  spanId: plan.spanId,
@@ -3006,6 +3009,7 @@ var encodeRecord = (record) => ({
3006
3009
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
3007
3010
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
3008
3011
  ...record.exported === true ? { exported: true } : {},
3012
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
3009
3013
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
3010
3014
  ...encodeAttributes(record.attributes)
3011
3015
  }
@@ -3029,6 +3033,7 @@ var decodeRecord = (attributes) => {
3029
3033
  return { kind: "corrupt" };
3030
3034
  }
3031
3035
  const exported = attributes["exported"] === true;
3036
+ const runKey = optionalString(attributes["runKey"]);
3032
3037
  const parentFamily = attributes["parentFamily"];
3033
3038
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
3034
3039
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -3043,6 +3048,7 @@ var decodeRecord = (attributes) => {
3043
3048
  ...endedAt === void 0 ? {} : { endedAt },
3044
3049
  ...parent === void 0 ? {} : { parent },
3045
3050
  ...exported ? { exported: true } : {},
3051
+ ...runKey === void 0 ? {} : { runKey },
3046
3052
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
3047
3053
  }
3048
3054
  };
@@ -3051,13 +3057,15 @@ var factsOf = (record) => ({
3051
3057
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
3052
3058
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
3053
3059
  ...record.parent === void 0 ? {} : { parent: record.parent },
3054
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
3060
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
3061
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
3055
3062
  });
3056
3063
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
3057
3064
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
3058
3065
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
3059
3066
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
3060
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
3067
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
3068
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
3061
3069
  });
3062
3070
  var orphanClassificationOf = (reason) => {
3063
3071
  switch (reason) {
@@ -3117,10 +3125,12 @@ var createSpanCorrelator = (deps) => {
3117
3125
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
3118
3126
  }
3119
3127
  }
3128
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
3120
3129
  const fresh = {
3121
3130
  providerId: input.providerId,
3122
3131
  startEventId: input.eventId,
3123
3132
  startedAt: input.occurredAt,
3133
+ ...previouslyExported ? { runKey: input.eventId } : {},
3124
3134
  ...input.parent === void 0 ? {} : { parent: input.parent },
3125
3135
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
3126
3136
  };
@@ -4027,7 +4037,10 @@ var postToolUseFailurePayloadSchema = z16.object({
4027
4037
  hook_event_name: z16.literal("PostToolUseFailure"),
4028
4038
  tool_name: z16.string().min(1),
4029
4039
  tool_input: z16.unknown().optional(),
4030
- tool_error: z16.unknown(),
4040
+ // Optional: a failure that names no message still ends its tool call. The
4041
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
4042
+ // `normalizeClaudeHookPayload`.
4043
+ tool_error: z16.unknown().optional(),
4031
4044
  tool_use_id: z16.string().min(1)
4032
4045
  });
4033
4046
  var permissionRequestPayloadSchema = z16.object({
@@ -6251,7 +6264,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6251
6264
 
6252
6265
  // src/state/filesystem-store.ts
6253
6266
  import { randomBytes as randomBytes2 } from "crypto";
6254
- import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
6267
+ import { mkdir, open as open4, readFile, readdir, rename, stat as stat3, unlink, writeFile } from "fs/promises";
6255
6268
  import * as path5 from "path";
6256
6269
 
6257
6270
  // src/state/keys.ts
@@ -6273,8 +6286,7 @@ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex")
6273
6286
  // src/state/filesystem-store.ts
6274
6287
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
6275
6288
  var sleep = (millis) => new Promise((resolve3) => {
6276
- const timer = setTimeout(resolve3, millis);
6277
- timer.unref?.();
6289
+ setTimeout(resolve3, millis);
6278
6290
  });
6279
6291
  var wrapFsError = (thrown, operation) => {
6280
6292
  if (thrown instanceof Error) {
@@ -6394,14 +6406,29 @@ var createFilesystemStateStore = (options) => {
6394
6406
  }
6395
6407
  }
6396
6408
  const stale = await (async () => {
6409
+ let raw;
6410
+ try {
6411
+ raw = await readFile(filePath, "utf8");
6412
+ } catch (thrown) {
6413
+ return isErrnoException(thrown, "ENOENT") ? "gone" : true;
6414
+ }
6397
6415
  try {
6398
- const raw = await readFile(filePath, "utf8");
6399
6416
  const parsed = JSON.parse(raw);
6400
- return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
6417
+ if (typeof parsed.acquiredAt === "number") {
6418
+ return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
6419
+ }
6401
6420
  } catch {
6402
- return true;
6421
+ }
6422
+ try {
6423
+ const stats = await stat3(filePath);
6424
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
6425
+ } catch {
6426
+ return "gone";
6403
6427
  }
6404
6428
  })();
6429
+ if (stale === "gone") {
6430
+ continue;
6431
+ }
6405
6432
  if (stale) {
6406
6433
  await unlink(filePath).catch(() => void 0);
6407
6434
  continue;
@@ -6572,7 +6599,7 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6572
6599
 
6573
6600
  // src/telemetry/spool-queue.ts
6574
6601
  import { randomBytes as randomBytes3 } from "crypto";
6575
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
6602
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
6576
6603
  import * as path6 from "path";
6577
6604
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
6578
6605
  total: 0,
@@ -6618,7 +6645,7 @@ var readSpoolQueueStats = async (queueDir) => {
6618
6645
  let bytes = 0;
6619
6646
  for (const file of files) {
6620
6647
  try {
6621
- bytes += (await stat3(path6.join(queueDir, file))).size;
6648
+ bytes += (await stat4(path6.join(queueDir, file))).size;
6622
6649
  } catch {
6623
6650
  }
6624
6651
  }
@@ -6631,6 +6658,22 @@ var readSpoolQueueStats = async (queueDir) => {
6631
6658
  };
6632
6659
  };
6633
6660
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
6661
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
6662
+ var CLAIM_MARKER = ".claimed-";
6663
+ var isClaimOwnerAlive = (pid) => {
6664
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
6665
+ return true;
6666
+ }
6667
+ if (pid === process.pid) {
6668
+ return true;
6669
+ }
6670
+ try {
6671
+ process.kill(pid, 0);
6672
+ return true;
6673
+ } catch (thrown) {
6674
+ return thrown?.code !== "ESRCH";
6675
+ }
6676
+ };
6634
6677
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
6635
6678
  var createSpoolQueue = (options) => {
6636
6679
  const [providerSegment, installationSegment] = namespaceSegments(options);
@@ -6700,7 +6743,7 @@ var createSpoolQueue = (options) => {
6700
6743
  let bytes = 0;
6701
6744
  if (options.maxBytes !== void 0) {
6702
6745
  try {
6703
- bytes = (await stat3(path6.join(queueDir, name))).size;
6746
+ bytes = (await stat4(path6.join(queueDir, name))).size;
6704
6747
  } catch {
6705
6748
  continue;
6706
6749
  }
@@ -6780,9 +6823,33 @@ var createSpoolQueue = (options) => {
6780
6823
  await rename2(tmp, target);
6781
6824
  return { spooled: true };
6782
6825
  };
6826
+ const releaseStaleClaims = async () => {
6827
+ let entries;
6828
+ try {
6829
+ entries = await readdir2(queueDir);
6830
+ } catch {
6831
+ return;
6832
+ }
6833
+ const now = Date.now();
6834
+ for (const entry of entries) {
6835
+ const marker = entry.lastIndexOf(CLAIM_MARKER);
6836
+ if (marker <= 0) {
6837
+ continue;
6838
+ }
6839
+ const claimPath = path6.join(queueDir, entry);
6840
+ const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
6841
+ try {
6842
+ if (!isClaimOwnerAlive(owner) || now - (await stat4(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
6843
+ await rename2(claimPath, path6.join(queueDir, entry.slice(0, marker)));
6844
+ }
6845
+ } catch {
6846
+ }
6847
+ }
6848
+ };
6783
6849
  const drain = async (send, drainOptions) => {
6784
6850
  await ensureDirs();
6785
6851
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
6852
+ await releaseStaleClaims();
6786
6853
  let files = await listSorted();
6787
6854
  if (options.maxAgeMillis !== void 0) {
6788
6855
  const now = options.clock.now();
@@ -6805,7 +6872,16 @@ var createSpoolQueue = (options) => {
6805
6872
  if (fileName === void 0) {
6806
6873
  break;
6807
6874
  }
6808
- const filePath = path6.join(queueDir, fileName);
6875
+ const queuedPath = path6.join(queueDir, fileName);
6876
+ const filePath = path6.join(
6877
+ queueDir,
6878
+ `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes3(4).toString("hex")}`
6879
+ );
6880
+ try {
6881
+ await rename2(queuedPath, filePath);
6882
+ } catch {
6883
+ continue;
6884
+ }
6809
6885
  const quarantine = async (rejection) => {
6810
6886
  quarantined += 1;
6811
6887
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6819,9 +6895,19 @@ var createSpoolQueue = (options) => {
6819
6895
  await unlink2(filePath).catch(() => void 0);
6820
6896
  }
6821
6897
  };
6898
+ let text;
6899
+ try {
6900
+ text = await readFile2(filePath, "utf8");
6901
+ } catch (thrown) {
6902
+ if (thrown?.code === "ENOENT") {
6903
+ continue;
6904
+ }
6905
+ await quarantine("unreadable");
6906
+ continue;
6907
+ }
6822
6908
  let parsed;
6823
6909
  try {
6824
- parsed = JSON.parse(await readFile2(filePath, "utf8"));
6910
+ parsed = JSON.parse(text);
6825
6911
  } catch {
6826
6912
  await quarantine("unparseable-json");
6827
6913
  continue;
@@ -6850,6 +6936,7 @@ var createSpoolQueue = (options) => {
6850
6936
  await unlink2(filePath).catch(() => void 0);
6851
6937
  drained += 1;
6852
6938
  } else {
6939
+ await rename2(filePath, queuedPath).catch(() => void 0);
6853
6940
  failed += 1;
6854
6941
  break;
6855
6942
  }