@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.
@@ -3,7 +3,7 @@ import { E as ExporterPolicy } from './schema-SpFM6YQY.js';
3
3
  import { C as Clock, d as Logger, l as TelemetrySink } from './ports-DhpSDIkp.js';
4
4
  import { Attributes } from '@opentelemetry/api';
5
5
  import { S as StoreNamespace } from './keys-Dej5bN3L.js';
6
- import { n as SpanCorrelationResolver, m as SpanCorrelation, k as MetricPoint } from './metric-model-CFIeUwqd.js';
6
+ import { n as SpanCorrelationResolver, m as SpanCorrelation, k as MetricPoint } from './metric-model-B4lIuk6i.js';
7
7
  import { InstrumentationScope } from '@opentelemetry/core';
8
8
  import { Resource } from '@opentelemetry/resources';
9
9
  import { ReadableLogRecord } from '@opentelemetry/sdk-logs';
package/dist/index.d.ts CHANGED
@@ -22,8 +22,8 @@ export { CallbackDeduplicator, CallbackDeduplicatorDependencies, DedupCheckResul
22
22
  export { S as StoreNamespace } from './keys-Dej5bN3L.js';
23
23
  export { F as FilesystemStateStore, a as FilesystemStateStoreOptions, L as LockingStateStore, S as StateStoreDependencies, c as createFilesystemStateStore, i as isLockingStateStore, w as withOptionalSessionLock } from './filesystem-store-B3CpiIRl.js';
24
24
  export { BoundedMemoryStateStore, BoundedMemoryStateStoreOptions, createBoundedMemoryStateStore } from './state.js';
25
- export { D as DEFAULT_INSTRUMENTATION_SCOPE, a as DeriveMetricObservationsInput, E as EventTraceIdentity, M as MAX_RECOVERED_START_ATTRIBUTES, b as METRIC_COST_USAGE, c as METRIC_INSTRUMENTS, d as METRIC_OPERATION_DURATION, e as METRIC_SESSIONS, f as METRIC_TOKEN_USAGE, g as METRIC_TOOL_CALLS, h as MetricInstrument, i as MetricInstrumentName, j as MetricObservation, k as MetricPoint, l as MetricsTemporality, O as OPERATION_DURATION_BUCKETS, S as SemanticMappingOptions, m as SpanCorrelation, n as SpanCorrelationResolver, o as SpanDisposition, p as SpanFamily, q as SpanOrphanClassification, r as SpanPairing, s as SpanScopeRef, T as TOKEN_USAGE_BUCKETS, t as TokenType, u as aggregateDeltaPoints, v as canonicalEventTraceIdentities, w as canonicalEventsToReadableSpans, x as deriveMetricObservations, y as parentScopeRefOf, z as spanScopeRefOf, A as startOnlySpanAttributes } from './metric-model-CFIeUwqd.js';
26
- export { C as ContentWithholdingReason, D as DurableLogSpool, a as DurableLogSpoolOptions, b as DurableMetricSpool, c as DurableMetricSpoolOptions, d as DurableSpool, e as DurableSpoolOptions, E as ExportDestinationSinks, f as ExportDestinationsOptions, L as LOG_MAPPING_VERSION, g as LOG_SIGNALS, h as LogContentPolicy, i as LogMappingOptions, j as LogMappingResult, k as LogSignal, l as LogSpoolBatch, m as LogsDeliverability, M as MAX_LOG_BODY_CHARACTERS, n as MAX_LOG_RECORDS_PER_BATCH, o as MAX_LOG_RECORDS_PER_EVENT, p as MCP_TOOL_NAME_PATTERN, q as MetricExportResult, r as MetricSpoolBatch, s as MetricsDeliverability, N as NO_LOG_CONTENT, O as OtlpLogSinkOptions, t as OtlpLogTelemetrySink, u as OtlpMetricSinkOptions, v as OtlpMetricTelemetrySink, w as OtlpTelemetrySink, x as OtlpTraceSinkOptions, S as SerializedLogRecord, y as SerializedSpan, z as SignalFanoutOptions, A as SignalFanoutSink, B as SkippedExportDestination, F as SpoolBatch, G as SpoolDrainResult, H as SpoolDropCounts, I as SpoolDropReason, J as SpoolEnqueueResult, K as SpoolOverflowPolicy, P as SpoolSendOutcome, Q as SpoolStats, R as canonicalEventsToLogRecords, T as createDestinationFanout, U as createExportDestinationSinks, V as createFileDurableLogSpool, W as createFileDurableMetricSpool, X as createFileDurableSpool, Y as createOtlpLogSink, Z as createOtlpMetricSink, _ as createOtlpTraceSink, $ as createSignalFanout, a0 as describeLogsDeliverability, a1 as describeMetricsDeliverability, a2 as exporterPolicyForDestination, a3 as logSignalOf, a4 as logSignalsForLifecycleEvents, a5 as resolveLogsEndpoint, a6 as resolveMetricsEndpoint, a7 as shareCorrelationPerBatch, a8 as spoolQueueNamesFor, a9 as validateMetricSpoolBatch } from './export-destinations-Bey2djRk.js';
25
+ export { D as DEFAULT_INSTRUMENTATION_SCOPE, a as DeriveMetricObservationsInput, E as EventTraceIdentity, M as MAX_RECOVERED_START_ATTRIBUTES, b as METRIC_COST_USAGE, c as METRIC_INSTRUMENTS, d as METRIC_OPERATION_DURATION, e as METRIC_SESSIONS, f as METRIC_TOKEN_USAGE, g as METRIC_TOOL_CALLS, h as MetricInstrument, i as MetricInstrumentName, j as MetricObservation, k as MetricPoint, l as MetricsTemporality, O as OPERATION_DURATION_BUCKETS, S as SemanticMappingOptions, m as SpanCorrelation, n as SpanCorrelationResolver, o as SpanDisposition, p as SpanFamily, q as SpanOrphanClassification, r as SpanPairing, s as SpanScopeRef, T as TOKEN_USAGE_BUCKETS, t as TokenType, u as aggregateDeltaPoints, v as canonicalEventTraceIdentities, w as canonicalEventsToReadableSpans, x as deriveMetricObservations, y as parentScopeRefOf, z as spanScopeRefOf, A as startOnlySpanAttributes } from './metric-model-B4lIuk6i.js';
26
+ export { C as ContentWithholdingReason, D as DurableLogSpool, a as DurableLogSpoolOptions, b as DurableMetricSpool, c as DurableMetricSpoolOptions, d as DurableSpool, e as DurableSpoolOptions, E as ExportDestinationSinks, f as ExportDestinationsOptions, L as LOG_MAPPING_VERSION, g as LOG_SIGNALS, h as LogContentPolicy, i as LogMappingOptions, j as LogMappingResult, k as LogSignal, l as LogSpoolBatch, m as LogsDeliverability, M as MAX_LOG_BODY_CHARACTERS, n as MAX_LOG_RECORDS_PER_BATCH, o as MAX_LOG_RECORDS_PER_EVENT, p as MCP_TOOL_NAME_PATTERN, q as MetricExportResult, r as MetricSpoolBatch, s as MetricsDeliverability, N as NO_LOG_CONTENT, O as OtlpLogSinkOptions, t as OtlpLogTelemetrySink, u as OtlpMetricSinkOptions, v as OtlpMetricTelemetrySink, w as OtlpTelemetrySink, x as OtlpTraceSinkOptions, S as SerializedLogRecord, y as SerializedSpan, z as SignalFanoutOptions, A as SignalFanoutSink, B as SkippedExportDestination, F as SpoolBatch, G as SpoolDrainResult, H as SpoolDropCounts, I as SpoolDropReason, J as SpoolEnqueueResult, K as SpoolOverflowPolicy, P as SpoolSendOutcome, Q as SpoolStats, R as canonicalEventsToLogRecords, T as createDestinationFanout, U as createExportDestinationSinks, V as createFileDurableLogSpool, W as createFileDurableMetricSpool, X as createFileDurableSpool, Y as createOtlpLogSink, Z as createOtlpMetricSink, _ as createOtlpTraceSink, $ as createSignalFanout, a0 as describeLogsDeliverability, a1 as describeMetricsDeliverability, a2 as exporterPolicyForDestination, a3 as logSignalOf, a4 as logSignalsForLifecycleEvents, a5 as resolveLogsEndpoint, a6 as resolveMetricsEndpoint, a7 as shareCorrelationPerBatch, a8 as spoolQueueNamesFor, a9 as validateMetricSpoolBatch } from './export-destinations-DUeQKr_C.js';
27
27
  export { isPermanentExportFailure } from './telemetry.js';
28
28
  export { DeliveryHealthSnapshot, DeliverySubsystem, HealthTracker, HealthTrackerOptions, OverallHealth, createHealthTracker, summarizeHealth } from './diagnostics.js';
29
29
  export { DeliveryReport, HookProcessInput, HookProcessOutcome, HookRuntime, HookRuntimeDelivery, HookRuntimeOptions, HookShutdownReport, MetricsReport, UsageRollup, createHookRuntime, minimumStaleClaimMillis } from './integration.js';
@@ -42,6 +42,6 @@ import '@opentelemetry/sdk-logs';
42
42
  *
43
43
  * Updated by `scripts/release/sync-version.mjs` during semantic-release.
44
44
  */
45
- declare const VERSION = "0.13.0";
45
+ declare const VERSION = "0.13.1";
46
46
 
47
47
  export { VERSION };
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({
@@ -3508,7 +3511,13 @@ var normalizeClaudeHookPayload = (payload) => {
3508
3511
  if (record === void 0) {
3509
3512
  return payload;
3510
3513
  }
3511
- 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 };
3512
3521
  };
3513
3522
  var applyUsageShape = (record) => {
3514
3523
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -9034,7 +9043,7 @@ import {
9034
9043
  } from "@opentelemetry/semantic-conventions/incubating";
9035
9044
 
9036
9045
  // src/version.ts
9037
- var VERSION = "0.13.0";
9046
+ var VERSION = "0.13.1";
9038
9047
 
9039
9048
  // src/telemetry/export-identity.ts
9040
9049
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9360,7 +9369,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9360
9369
  const resolved = resolvePairing(group, anchor, correlation);
9361
9370
  const traceId = plan.traceId;
9362
9371
  const spanId = plan.spanId;
9363
- 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);
9364
9374
  let name = group.ref.family;
9365
9375
  let kind = SpanKind.INTERNAL;
9366
9376
  let status = { code: SpanStatusCode.UNSET };
@@ -9584,7 +9594,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
9584
9594
  // persist something that should have been persisted.
9585
9595
  correlation === void 0 && correlationAvailable === void 0);
9586
9596
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
9587
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
9597
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
9588
9598
  return {
9589
9599
  group,
9590
9600
  anchor,
@@ -9604,6 +9614,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
9604
9614
  )
9605
9615
  };
9606
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;
9607
9619
  var canonicalEventTraceIdentities = (events, options = {}) => {
9608
9620
  const layout = layoutBatch(events);
9609
9621
  const correlations = indexCorrelations(options.correlations);
@@ -9628,7 +9640,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
9628
9640
  });
9629
9641
  continue;
9630
9642
  }
9631
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
9643
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3) ?? resumedSessionParent(plan.group.ref, plan.correlation);
9632
9644
  identities.set(event3.eventId, {
9633
9645
  traceId: plan.traceId,
9634
9646
  spanId: plan.spanId,
@@ -9711,6 +9723,7 @@ var encodeRecord = (record) => ({
9711
9723
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
9712
9724
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9713
9725
  ...record.exported === true ? { exported: true } : {},
9726
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
9714
9727
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
9715
9728
  ...encodeAttributes(record.attributes)
9716
9729
  }
@@ -9734,6 +9747,7 @@ var decodeRecord = (attributes) => {
9734
9747
  return { kind: "corrupt" };
9735
9748
  }
9736
9749
  const exported = attributes["exported"] === true;
9750
+ const runKey = optionalString(attributes["runKey"]);
9737
9751
  const parentFamily = attributes["parentFamily"];
9738
9752
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
9739
9753
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -9748,6 +9762,7 @@ var decodeRecord = (attributes) => {
9748
9762
  ...endedAt === void 0 ? {} : { endedAt },
9749
9763
  ...parent === void 0 ? {} : { parent },
9750
9764
  ...exported ? { exported: true } : {},
9765
+ ...runKey === void 0 ? {} : { runKey },
9751
9766
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
9752
9767
  }
9753
9768
  };
@@ -9756,13 +9771,15 @@ var factsOf = (record) => ({
9756
9771
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
9757
9772
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9758
9773
  ...record.parent === void 0 ? {} : { parent: record.parent },
9759
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
9774
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
9775
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
9760
9776
  });
9761
9777
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
9762
9778
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
9763
9779
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
9764
9780
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
9765
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
9781
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
9782
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
9766
9783
  });
9767
9784
  var orphanClassificationOf = (reason) => {
9768
9785
  switch (reason) {
@@ -9822,10 +9839,12 @@ var createSpanCorrelator = (deps) => {
9822
9839
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
9823
9840
  }
9824
9841
  }
9842
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
9825
9843
  const fresh = {
9826
9844
  providerId: input.providerId,
9827
9845
  startEventId: input.eventId,
9828
9846
  startedAt: input.occurredAt,
9847
+ ...previouslyExported ? { runKey: input.eventId } : {},
9829
9848
  ...input.parent === void 0 ? {} : { parent: input.parent },
9830
9849
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9831
9850
  };
@@ -10688,7 +10707,7 @@ var createBoundedMemoryStateStore = (options) => {
10688
10707
 
10689
10708
  // src/state/filesystem-store.ts
10690
10709
  import { randomBytes as randomBytes2 } from "crypto";
10691
- 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";
10692
10711
  import * as path5 from "path";
10693
10712
 
10694
10713
  // src/state/keys.ts
@@ -10710,8 +10729,7 @@ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex")
10710
10729
  // src/state/filesystem-store.ts
10711
10730
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
10712
10731
  var sleep = (millis) => new Promise((resolve5) => {
10713
- const timer = setTimeout(resolve5, millis);
10714
- timer.unref?.();
10732
+ setTimeout(resolve5, millis);
10715
10733
  });
10716
10734
  var wrapFsError = (thrown, operation) => {
10717
10735
  if (thrown instanceof Error) {
@@ -10831,14 +10849,29 @@ var createFilesystemStateStore = (options) => {
10831
10849
  }
10832
10850
  }
10833
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
+ }
10834
10858
  try {
10835
- const raw = await readFile(filePath, "utf8");
10836
10859
  const parsed = JSON.parse(raw);
10837
- 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
+ }
10838
10863
  } catch {
10839
- return true;
10864
+ }
10865
+ try {
10866
+ const stats = await stat3(filePath);
10867
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
10868
+ } catch {
10869
+ return "gone";
10840
10870
  }
10841
10871
  })();
10872
+ if (stale === "gone") {
10873
+ continue;
10874
+ }
10842
10875
  if (stale) {
10843
10876
  await unlink(filePath).catch(() => void 0);
10844
10877
  continue;
@@ -10975,7 +11008,7 @@ var createFilesystemStateStore = (options) => {
10975
11008
 
10976
11009
  // src/telemetry/spool-queue.ts
10977
11010
  import { randomBytes as randomBytes3 } from "crypto";
10978
- 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";
10979
11012
  import * as path6 from "path";
10980
11013
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10981
11014
  total: 0,
@@ -11021,7 +11054,7 @@ var readSpoolQueueStats = async (queueDir) => {
11021
11054
  let bytes = 0;
11022
11055
  for (const file of files) {
11023
11056
  try {
11024
- bytes += (await stat3(path6.join(queueDir, file))).size;
11057
+ bytes += (await stat4(path6.join(queueDir, file))).size;
11025
11058
  } catch {
11026
11059
  }
11027
11060
  }
@@ -11034,6 +11067,22 @@ var readSpoolQueueStats = async (queueDir) => {
11034
11067
  };
11035
11068
  };
11036
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
+ };
11037
11086
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
11038
11087
  var createSpoolQueue = (options) => {
11039
11088
  const [providerSegment, installationSegment] = namespaceSegments(options);
@@ -11103,7 +11152,7 @@ var createSpoolQueue = (options) => {
11103
11152
  let bytes = 0;
11104
11153
  if (options.maxBytes !== void 0) {
11105
11154
  try {
11106
- bytes = (await stat3(path6.join(queueDir, name))).size;
11155
+ bytes = (await stat4(path6.join(queueDir, name))).size;
11107
11156
  } catch {
11108
11157
  continue;
11109
11158
  }
@@ -11183,9 +11232,33 @@ var createSpoolQueue = (options) => {
11183
11232
  await rename2(tmp, target);
11184
11233
  return { spooled: true };
11185
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
+ };
11186
11258
  const drain = async (send, drainOptions) => {
11187
11259
  await ensureDirs();
11188
11260
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
11261
+ await releaseStaleClaims();
11189
11262
  let files = await listSorted();
11190
11263
  if (options.maxAgeMillis !== void 0) {
11191
11264
  const now = options.clock.now();
@@ -11208,7 +11281,16 @@ var createSpoolQueue = (options) => {
11208
11281
  if (fileName === void 0) {
11209
11282
  break;
11210
11283
  }
11211
- 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
+ }
11212
11294
  const quarantine = async (rejection) => {
11213
11295
  quarantined += 1;
11214
11296
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -11222,9 +11304,19 @@ var createSpoolQueue = (options) => {
11222
11304
  await unlink2(filePath).catch(() => void 0);
11223
11305
  }
11224
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
+ }
11225
11317
  let parsed;
11226
11318
  try {
11227
- parsed = JSON.parse(await readFile2(filePath, "utf8"));
11319
+ parsed = JSON.parse(text);
11228
11320
  } catch {
11229
11321
  await quarantine("unparseable-json");
11230
11322
  continue;
@@ -11253,6 +11345,7 @@ var createSpoolQueue = (options) => {
11253
11345
  await unlink2(filePath).catch(() => void 0);
11254
11346
  drained += 1;
11255
11347
  } else {
11348
+ await rename2(filePath, queuedPath).catch(() => void 0);
11256
11349
  failed += 1;
11257
11350
  break;
11258
11351
  }
@@ -14517,7 +14610,7 @@ var resolveInstallPath = (location, roots) => path7.resolve(
14517
14610
 
14518
14611
  // src/install/document.ts
14519
14612
  import { randomBytes as randomBytes4 } from "crypto";
14520
- 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";
14521
14614
  import * as path8 from "path";
14522
14615
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14523
14616
  indent: " ",
@@ -14597,7 +14690,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14597
14690
  );
14598
14691
  let existingMode;
14599
14692
  try {
14600
- existingMode = (await stat4(filePath)).mode & 4095;
14693
+ existingMode = (await stat5(filePath)).mode & 4095;
14601
14694
  } catch (thrown) {
14602
14695
  if (!isErrnoException3(thrown, "ENOENT")) {
14603
14696
  throw thrown;
@@ -14622,7 +14715,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14622
14715
 
14623
14716
  // src/install/file-lock.ts
14624
14717
  import { randomBytes as randomBytes5 } from "crypto";
14625
- 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";
14626
14719
  import * as path9 from "path";
14627
14720
  var FileLockTimeoutError = class extends Error {
14628
14721
  constructor(lockPath, timeoutMillis) {
@@ -14687,7 +14780,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
14687
14780
  } catch {
14688
14781
  }
14689
14782
  try {
14690
- const stats = await stat5(lockPath);
14783
+ const stats = await stat6(lockPath);
14691
14784
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
14692
14785
  } catch (thrown) {
14693
14786
  return { stale: !isErrnoException4(thrown, "ENOENT") };