@osfactory/otel-hook 0.13.0 → 0.13.2

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 +51 -3
  2. package/dist/cli.js +907 -164
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config.d.ts +5 -3
  5. package/dist/config.js +39 -5
  6. package/dist/config.js.map +1 -1
  7. package/dist/{destinations-DvqsPulb.d.ts → destinations-C4sSKjDO.d.ts} +1 -1
  8. package/dist/{export-destinations-Bey2djRk.d.ts → export-destinations-BjRXDots.d.ts} +37 -5
  9. package/dist/{hook-D5imE0Qc.d.ts → hook-CKLpgrYP.d.ts} +2 -2
  10. package/dist/index.d.ts +9 -9
  11. package/dist/index.js +921 -182
  12. package/dist/index.js.map +1 -1
  13. package/dist/install.d.ts +1 -1
  14. package/dist/install.js +5 -1
  15. package/dist/install.js.map +1 -1
  16. package/dist/integration.d.ts +15 -8
  17. package/dist/integration.js +998 -160
  18. package/dist/integration.js.map +1 -1
  19. package/dist/lifecycle.d.ts +8 -1
  20. package/dist/lifecycle.js +10 -3
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{metric-model-CFIeUwqd.d.ts → metric-model-B4lIuk6i.d.ts} +8 -0
  23. package/dist/{payload-CdDKeRpH.d.ts → payload-DLK7QaBB.d.ts} +17 -1
  24. package/dist/providers.d.ts +91 -6
  25. package/dist/providers.js +311 -4
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-BKQhhIO3.d.ts → registry-DM-4YvIA.d.ts} +1 -1
  28. package/dist/runtime.d.ts +3 -3
  29. package/dist/runtime.js +23 -3
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/{schema-SpFM6YQY.d.ts → schema-CD61uW99.d.ts} +32 -3
  32. package/dist/state.js +20 -6
  33. package/dist/state.js.map +1 -1
  34. package/dist/telemetry.d.ts +4 -4
  35. package/dist/telemetry.js +865 -472
  36. package/dist/telemetry.js.map +1 -1
  37. package/dist/testing.d.ts +3 -3
  38. package/dist/testing.js +61 -21
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -1360,11 +1360,11 @@ var createPrivacyService = (policyInput) => {
1360
1360
  };
1361
1361
  const flattenToAttributes = (value, prefix) => {
1362
1362
  const attributes = {};
1363
- const walk = (current, path11) => {
1363
+ const walk = (current, path13) => {
1364
1364
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1365
1365
  const primitive = toAttributePrimitive(current);
1366
1366
  if (primitive !== void 0) {
1367
- attributes[path11] = primitive;
1367
+ attributes[path13] = primitive;
1368
1368
  }
1369
1369
  return;
1370
1370
  }
@@ -1383,16 +1383,16 @@ var createPrivacyService = (policyInput) => {
1383
1383
  primitives.push(entryPrimitive);
1384
1384
  }
1385
1385
  if (uniform) {
1386
- attributes[path11] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1386
+ attributes[path13] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1387
1387
  return;
1388
1388
  }
1389
1389
  for (const [index, entry] of current.entries()) {
1390
- walk(entry, `${path11}.${index}`);
1390
+ walk(entry, `${path13}.${index}`);
1391
1391
  }
1392
1392
  return;
1393
1393
  }
1394
1394
  for (const [key, entry] of Object.entries(current)) {
1395
- walk(entry, path11 === "" ? key : `${path11}.${key}`);
1395
+ walk(entry, path13 === "" ? key : `${path13}.${key}`);
1396
1396
  }
1397
1397
  };
1398
1398
  walk(value, prefix);
@@ -2108,8 +2108,26 @@ var exporterPolicySchema = z14.strictObject({
2108
2108
  * Per-destination retry spool bounds, each optional and merged per leaf; any
2109
2109
  * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
2110
2110
  */
2111
- spool: spoolPolicySchema.partial().optional()
2111
+ spool: spoolPolicySchema.partial().optional(),
2112
+ /**
2113
+ * The most time one hook invocation spends trying to reach one endpoint, in
2114
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
2115
+ * included) and the exporter's own retries inside it. A batch that does not
2116
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
2117
+ * the host agent waits for its hooks, so a down collector must not stall it.
2118
+ */
2119
+ exportBudgetMillis: z14.number().int().min(50).max(6e5).optional(),
2120
+ /**
2121
+ * After an endpoint was unreachable (refused, timed out, or answered a
2122
+ * retryable status), every hook spools for it without trying for this long,
2123
+ * in milliseconds; then one hook probes it again. 0 disables the window.
2124
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
2125
+ */
2126
+ endpointDownMillis: z14.number().int().min(0).max(36e5).optional()
2112
2127
  });
2128
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
2129
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
2130
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
2113
2131
  var detectionPolicySchema = z14.strictObject({
2114
2132
  /** Detections below this confidence resolve to the unknown provider. */
2115
2133
  minimumConfidence: detectionConfidenceSchema,
@@ -2126,6 +2144,9 @@ var diagnosticsPolicySchema = z14.strictObject({
2126
2144
  var providersPolicySchema = z14.strictObject({
2127
2145
  claudeCode: z14.strictObject({
2128
2146
  readTranscriptUsage: z14.boolean()
2147
+ }).optional(),
2148
+ codex: z14.strictObject({
2149
+ readRolloutUsage: z14.boolean()
2129
2150
  }).optional()
2130
2151
  });
2131
2152
  var sessionContextPolicySchema = z14.strictObject({
@@ -2155,7 +2176,8 @@ var otelHookConfigPatchSchema = z14.strictObject({
2155
2176
  detection: detectionPolicySchema.partial().optional(),
2156
2177
  diagnostics: diagnosticsPolicySchema.partial().optional(),
2157
2178
  providers: z14.strictObject({
2158
- claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2179
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional(),
2180
+ codex: z14.strictObject({ readRolloutUsage: z14.boolean() }).partial().optional()
2159
2181
  }).partial().optional(),
2160
2182
  sessionContext: sessionContextPolicySchema.partial().optional()
2161
2183
  });
@@ -2182,7 +2204,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2182
2204
  emitErrorEvents: true
2183
2205
  });
2184
2206
  var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2185
- claudeCode: Object.freeze({ readTranscriptUsage: false })
2207
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
2208
+ codex: Object.freeze({ readRolloutUsage: false })
2186
2209
  });
2187
2210
  var DEFAULT_CONFIG = Object.freeze({
2188
2211
  exporter: DEFAULT_EXPORTER_POLICY,
@@ -2192,6 +2215,7 @@ var DEFAULT_CONFIG = Object.freeze({
2192
2215
  providers: DEFAULT_PROVIDERS_POLICY
2193
2216
  });
2194
2217
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2218
+ var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
2195
2219
  var sessionContextDir = (config) => config.sessionContext?.dir;
2196
2220
  var effectiveMetricsPolicy = (exporter) => ({
2197
2221
  ...DEFAULT_METRICS_POLICY,
@@ -2203,12 +2227,12 @@ import { z as z15 } from "zod";
2203
2227
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2204
2228
  var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
2205
2229
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2206
- var mergeLeaf = (target, patch, source, provenance, path11) => {
2230
+ var mergeLeaf = (target, patch, source, provenance, path13) => {
2207
2231
  for (const [key, value] of Object.entries(patch)) {
2208
2232
  if (value === void 0) {
2209
2233
  continue;
2210
2234
  }
2211
- const childPath = path11 === "" ? key : `${path11}.${key}`;
2235
+ const childPath = path13 === "" ? key : `${path13}.${key}`;
2212
2236
  const existing = target[key];
2213
2237
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2214
2238
  const child = { ...existing ?? {} };
@@ -2222,14 +2246,14 @@ var mergeLeaf = (target, patch, source, provenance, path11) => {
2222
2246
  };
2223
2247
  var initialProvenance = (config) => {
2224
2248
  const provenance = {};
2225
- const walk = (value, path11) => {
2249
+ const walk = (value, path13) => {
2226
2250
  if (isPlainObject(value)) {
2227
2251
  for (const [key, child] of Object.entries(value)) {
2228
- walk(child, path11 === "" ? key : `${path11}.${key}`);
2252
+ walk(child, path13 === "" ? key : `${path13}.${key}`);
2229
2253
  }
2230
2254
  return;
2231
2255
  }
2232
- provenance[path11] = "defaults";
2256
+ provenance[path13] = "defaults";
2233
2257
  };
2234
2258
  walk(config, "");
2235
2259
  return provenance;
@@ -2353,7 +2377,7 @@ var describeDestinationAttributes = (config) => {
2353
2377
  return attributes;
2354
2378
  };
2355
2379
  var describeResolvedConfig = (config) => {
2356
- const originOf = (endpoint) => {
2380
+ const originOf2 = (endpoint) => {
2357
2381
  if (endpoint === void 0) {
2358
2382
  return void 0;
2359
2383
  }
@@ -2363,10 +2387,10 @@ var describeResolvedConfig = (config) => {
2363
2387
  return "<unparsable>";
2364
2388
  }
2365
2389
  };
2366
- const endpointOrigin2 = originOf(config.exporter.endpoint);
2367
- const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2390
+ const endpointOrigin2 = originOf2(config.exporter.endpoint);
2391
+ const logsEndpointOrigin = originOf2(config.exporter.logs.endpoint);
2368
2392
  const metrics = effectiveMetricsPolicy(config.exporter);
2369
- const metricsEndpointOrigin = originOf(metrics.endpoint);
2393
+ const metricsEndpointOrigin = originOf2(metrics.endpoint);
2370
2394
  return {
2371
2395
  "exporter.enabled": config.exporter.enabled,
2372
2396
  "exporter.protocol": config.exporter.protocol,
@@ -2486,7 +2510,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
2486
2510
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
2487
2511
  logLevel: "OTEL_HOOK_LOG_LEVEL",
2488
2512
  /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
2489
- claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
2513
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE",
2514
+ /** `providers.codex.readRolloutUsage`; see `providersPolicySchema`. */
2515
+ codexRolloutUsage: "OTEL_HOOK_CODEX_ROLLOUT_USAGE"
2490
2516
  });
2491
2517
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
2492
2518
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -2681,7 +2707,11 @@ var parseEnvironmentConfig = (env) => {
2681
2707
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
2682
2708
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
2683
2709
  const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
2684
- const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
2710
+ const codexRolloutUsage = readBoolean(ENVIRONMENT_VARIABLES.codexRolloutUsage);
2711
+ const providers = {
2712
+ ...claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } },
2713
+ ...codexRolloutUsage === void 0 ? {} : { codex: { readRolloutUsage: codexRolloutUsage } }
2714
+ };
2685
2715
  const patch = {
2686
2716
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
2687
2717
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
@@ -3139,7 +3169,10 @@ var postToolUseFailurePayloadSchema = z17.object({
3139
3169
  hook_event_name: z17.literal("PostToolUseFailure"),
3140
3170
  tool_name: z17.string().min(1),
3141
3171
  tool_input: z17.unknown().optional(),
3142
- tool_error: z17.unknown(),
3172
+ // Optional: a failure that names no message still ends its tool call. The
3173
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
3174
+ // `normalizeClaudeHookPayload`.
3175
+ tool_error: z17.unknown().optional(),
3143
3176
  tool_use_id: z17.string().min(1)
3144
3177
  });
3145
3178
  var permissionRequestPayloadSchema = z17.object({
@@ -3508,7 +3541,13 @@ var normalizeClaudeHookPayload = (payload) => {
3508
3541
  if (record === void 0) {
3509
3542
  return payload;
3510
3543
  }
3511
- return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
3544
+ return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));
3545
+ };
3546
+ var applyToolFailureShape = (record) => {
3547
+ if (record.hook_event_name !== "PostToolUseFailure" || record.tool_error !== void 0 || record.error === void 0) {
3548
+ return record;
3549
+ }
3550
+ return { ...record, tool_error: record.error };
3512
3551
  };
3513
3552
  var applyUsageShape = (record) => {
3514
3553
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -5425,6 +5464,7 @@ var permissionModeSchema = z19.enum([
5425
5464
  var codexUsageSchema = z19.object({
5426
5465
  input_tokens: z19.number().int().min(0).optional(),
5427
5466
  cached_input_tokens: z19.number().int().min(0).optional(),
5467
+ cache_write_input_tokens: z19.number().int().min(0).optional(),
5428
5468
  output_tokens: z19.number().int().min(0).optional(),
5429
5469
  reasoning_output_tokens: z19.number().int().min(0).optional(),
5430
5470
  total_tokens: z19.number().int().min(0).optional()
@@ -5680,6 +5720,10 @@ var codexUsageToReport = (usage, temporality) => ({
5680
5720
  temporality,
5681
5721
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
5682
5722
  ...usage.cached_input_tokens === void 0 ? {} : { cachedInputTokens: usage.cached_input_tokens },
5723
+ ...usage.cache_write_input_tokens === void 0 ? {} : {
5724
+ cacheCreationInputTokens: usage.cache_write_input_tokens,
5725
+ cacheCreationAccounting: "included-in-input"
5726
+ },
5683
5727
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
5684
5728
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
5685
5729
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -5708,8 +5752,9 @@ var CODEX_CAPABILITIES = Object.freeze({
5708
5752
  // turn; see docs/usage-semantics.md.
5709
5753
  cumulativeUsageSeries: "session-lifetime",
5710
5754
  reportsCachedInput: true,
5711
- reportsCacheCreation: false,
5712
- cacheCreationAccounting: "not-reported",
5755
+ // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.
5756
+ reportsCacheCreation: true,
5757
+ cacheCreationAccounting: "included-in-input",
5713
5758
  reportsReasoningOutput: true,
5714
5759
  reportsProviderTotal: true,
5715
5760
  reportsCost: false,
@@ -6068,6 +6113,291 @@ var createCodexAdapter = () => ({
6068
6113
  hookResponse
6069
6114
  });
6070
6115
 
6116
+ // src/providers/codex/rollout-usage.ts
6117
+ import { createHash as createHash3 } from "crypto";
6118
+ import { open as open2, readdir, stat as stat2 } from "fs/promises";
6119
+ import path2 from "path";
6120
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
6121
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
6122
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
6123
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
6124
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
6125
+ var ROLLOUT_LOOKUP_DAYS = 7;
6126
+ var MIN_BYTES = 65536;
6127
+ var MAX_RANGE_BYTES2 = 67108864;
6128
+ var MAX_TAIL_BYTES2 = 16777216;
6129
+ var MIN_TIMEOUT_MILLIS2 = 10;
6130
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
6131
+ var MAX_SETTLE_MILLIS = 1e3;
6132
+ var MAX_MODEL_ID_LENGTH2 = 256;
6133
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
6134
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
6135
+ var clamp2 = (value, fallback, min, max) => {
6136
+ if (value === void 0 || !Number.isFinite(value)) {
6137
+ return fallback;
6138
+ }
6139
+ return Math.min(max, Math.max(min, Math.floor(value)));
6140
+ };
6141
+ var asRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
6142
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path2.isAbsolute(value) && path2.extname(value) === ".jsonl";
6143
+ var sourceDigest2 = (rolloutPath) => createHash3("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
6144
+ var parseUsage = (value) => {
6145
+ const parsed = codexUsageSchema.safeParse(value);
6146
+ if (!parsed.success) {
6147
+ return void 0;
6148
+ }
6149
+ const usage = parsed.data;
6150
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
6151
+ };
6152
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
6153
+ var factsOf = (line) => {
6154
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
6155
+ const contextLine = line.includes('"turn_context"');
6156
+ if (!usageLine && !contextLine) {
6157
+ return void 0;
6158
+ }
6159
+ let parsed;
6160
+ try {
6161
+ parsed = JSON.parse(line);
6162
+ } catch {
6163
+ return void 0;
6164
+ }
6165
+ const record = asRecord8(parsed);
6166
+ const payload = asRecord8(record?.payload);
6167
+ if (record === void 0 || payload === void 0) {
6168
+ return void 0;
6169
+ }
6170
+ if (record.type === "turn_context") {
6171
+ const model = modelOf(payload.model);
6172
+ return model === void 0 ? void 0 : { model };
6173
+ }
6174
+ if (record.type === "event_msg" && payload.type === "token_count") {
6175
+ const info = asRecord8(payload.info) ?? payload;
6176
+ const usage = parseUsage(info.total_token_usage);
6177
+ return usage === void 0 ? void 0 : { usage };
6178
+ }
6179
+ if (record.type === "token_usage_record") {
6180
+ const usage = parseUsage(payload.thread_token_usage);
6181
+ return usage === void 0 ? void 0 : { usage };
6182
+ }
6183
+ return void 0;
6184
+ };
6185
+ var lastSnapshotIn = (lines) => {
6186
+ let usage;
6187
+ let model;
6188
+ for (const line of lines) {
6189
+ const facts = factsOf(line.trim());
6190
+ if (facts === void 0) {
6191
+ continue;
6192
+ }
6193
+ if (facts.model !== void 0) {
6194
+ model = facts.model;
6195
+ }
6196
+ if (facts.usage !== void 0) {
6197
+ usage = facts.usage;
6198
+ }
6199
+ }
6200
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
6201
+ };
6202
+ var readBytes2 = async (handle, start, length) => {
6203
+ const buffer = Buffer.alloc(length);
6204
+ let filled = 0;
6205
+ while (filled < length) {
6206
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
6207
+ if (bytesRead === 0) {
6208
+ break;
6209
+ }
6210
+ filled += bytesRead;
6211
+ }
6212
+ return buffer.subarray(0, filled);
6213
+ };
6214
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
6215
+ let handle;
6216
+ try {
6217
+ const info = await stat2(rolloutPath);
6218
+ if (!info.isFile()) {
6219
+ return { status: "unavailable", reason: "not-a-file" };
6220
+ }
6221
+ handle = await open2(rolloutPath, "r");
6222
+ } catch {
6223
+ return { status: "unavailable", reason: "unreadable" };
6224
+ }
6225
+ try {
6226
+ const { size } = await handle.stat();
6227
+ let start;
6228
+ if (fromOffset === void 0) {
6229
+ start = Math.max(0, size - tailBytes);
6230
+ } else if (size < fromOffset) {
6231
+ return { status: "unavailable", reason: "truncated" };
6232
+ } else if (size - fromOffset > maxRangeBytes) {
6233
+ return { status: "unavailable", reason: "over-cap" };
6234
+ } else {
6235
+ start = fromOffset;
6236
+ }
6237
+ const bytes = await readBytes2(handle, start, size - start);
6238
+ const lastNewline = bytes.lastIndexOf(10);
6239
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
6240
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
6241
+ if (fromOffset === void 0 && start > 0) {
6242
+ lines.shift();
6243
+ }
6244
+ const snapshot = lastSnapshotIn(lines);
6245
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
6246
+ } catch {
6247
+ return { status: "unavailable", reason: "unreadable" };
6248
+ } finally {
6249
+ await handle.close().catch(() => void 0);
6250
+ }
6251
+ };
6252
+ var pad = (value) => String(value).padStart(2, "0");
6253
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
6254
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path2.isAbsolute(sessionsRoot)) {
6255
+ return void 0;
6256
+ }
6257
+ const suffix = `-${sessionId}.jsonl`;
6258
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
6259
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
6260
+ const dir = path2.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
6261
+ let names;
6262
+ try {
6263
+ names = await readdir(dir);
6264
+ } catch {
6265
+ continue;
6266
+ }
6267
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
6268
+ continue;
6269
+ }
6270
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
6271
+ if (match !== void 0) {
6272
+ return path2.join(dir, match);
6273
+ }
6274
+ }
6275
+ return void 0;
6276
+ };
6277
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
6278
+ var withTimeout2 = async (work, timeoutMillis) => {
6279
+ let timer;
6280
+ const timeout = new Promise((resolve5) => {
6281
+ timer = setTimeout(() => {
6282
+ resolve5(TIMED_OUT2);
6283
+ }, timeoutMillis);
6284
+ timer.unref();
6285
+ });
6286
+ try {
6287
+ return await Promise.race([work, timeout]);
6288
+ } finally {
6289
+ clearTimeout(timer);
6290
+ }
6291
+ };
6292
+ var sleep = (millis) => new Promise((resolve5) => {
6293
+ setTimeout(resolve5, millis).unref();
6294
+ });
6295
+ var hasUsage2 = (record) => record.usage !== void 0;
6296
+ var createCodexRolloutUsageEnricher = (options = {}) => {
6297
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
6298
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
6299
+ const timeoutMillis = clamp2(
6300
+ options.timeoutMillis,
6301
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
6302
+ MIN_TIMEOUT_MILLIS2,
6303
+ MAX_TIMEOUT_MILLIS2
6304
+ );
6305
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
6306
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
6307
+ const fileSize = async (rolloutPath) => {
6308
+ try {
6309
+ const info = await stat2(rolloutPath);
6310
+ return info.isFile() ? info.size : void 0;
6311
+ } catch (thrown) {
6312
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
6313
+ }
6314
+ };
6315
+ const resolveRollout = async (record) => {
6316
+ const named = record.transcript_path;
6317
+ if (named !== void 0 && named !== null) {
6318
+ return isRolloutPath(named) ? named : void 0;
6319
+ }
6320
+ const sessionId = record.session_id;
6321
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
6322
+ return void 0;
6323
+ }
6324
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
6325
+ };
6326
+ const enrichWithin = async (input) => {
6327
+ const unchanged = { payload: input.payload };
6328
+ const record = asRecord8(input.payload);
6329
+ const eventName = record?.hook_event_name;
6330
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
6331
+ return unchanged;
6332
+ }
6333
+ const rolloutPath = await resolveRollout(record);
6334
+ if (rolloutPath === void 0) {
6335
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
6336
+ }
6337
+ const source = sourceDigest2(rolloutPath);
6338
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
6339
+ if (eventName === "SessionStart") {
6340
+ if (cursor !== void 0) {
6341
+ return unchanged;
6342
+ }
6343
+ const size = await fileSize(rolloutPath);
6344
+ if (size === void 0) {
6345
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
6346
+ }
6347
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
6348
+ }
6349
+ if (hasUsage2(record)) {
6350
+ const size = await fileSize(rolloutPath);
6351
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
6352
+ }
6353
+ const attach = (snapshot) => ({
6354
+ ...record,
6355
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
6356
+ usage: snapshot.usage
6357
+ });
6358
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
6359
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
6360
+ await sleep(settleMillis);
6361
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
6362
+ }
6363
+ if (read.status === "unavailable") {
6364
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
6365
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
6366
+ }
6367
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
6368
+ if (read.status === "unavailable") {
6369
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
6370
+ }
6371
+ }
6372
+ const next = { source, offset: read.endOffset };
6373
+ if (read.snapshot === void 0) {
6374
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
6375
+ }
6376
+ return {
6377
+ payload: attach(read.snapshot),
6378
+ cursor: next,
6379
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
6380
+ };
6381
+ };
6382
+ const enrich = async (input) => {
6383
+ try {
6384
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
6385
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
6386
+ } catch {
6387
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
6388
+ }
6389
+ };
6390
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
6391
+ };
6392
+ var readCodexRolloutUsage = async (rolloutPath, options = {}) => {
6393
+ if (!isRolloutPath(rolloutPath)) {
6394
+ return void 0;
6395
+ }
6396
+ const tail = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
6397
+ const read = await readRollout(rolloutPath, void 0, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, tail).catch(() => void 0);
6398
+ return read?.status === "found" ? read.snapshot : void 0;
6399
+ };
6400
+
6071
6401
  // src/providers/gemini/delivery.ts
6072
6402
  var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
6073
6403
  SessionStart: "fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one",
@@ -7199,9 +7529,9 @@ var createFixedClock = (options = {}) => {
7199
7529
  };
7200
7530
 
7201
7531
  // src/runtime/ids.ts
7202
- import { createHash as createHash3, randomUUID } from "crypto";
7532
+ import { createHash as createHash4, randomUUID } from "crypto";
7203
7533
  var digest = (namespace, parts) => {
7204
- const hash = createHash3("sha256");
7534
+ const hash = createHash4("sha256");
7205
7535
  hash.update(namespace);
7206
7536
  for (const part of parts) {
7207
7537
  hash.update("\0");
@@ -7437,16 +7767,16 @@ var resolveDeliveryIdentity = (input) => {
7437
7767
  import { z as z24 } from "zod";
7438
7768
 
7439
7769
  // src/runtime/target-resolution.ts
7440
- import * as path2 from "path";
7770
+ import * as path3 from "path";
7441
7771
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
7442
7772
  var absolutePathsOf = (hint) => {
7443
- const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
7773
+ const base = hint.baseDirectory !== void 0 && path3.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
7444
7774
  const resolved = [];
7445
7775
  for (const candidate of hint.paths) {
7446
- if (path2.isAbsolute(candidate)) {
7447
- resolved.push(path2.resolve(candidate));
7776
+ if (path3.isAbsolute(candidate)) {
7777
+ resolved.push(path3.resolve(candidate));
7448
7778
  } else if (base !== void 0) {
7449
- resolved.push(path2.resolve(base, candidate));
7779
+ resolved.push(path3.resolve(base, candidate));
7450
7780
  } else {
7451
7781
  return void 0;
7452
7782
  }
@@ -7604,8 +7934,8 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7604
7934
  };
7605
7935
 
7606
7936
  // src/runtime/session-context.ts
7607
- import { open as open2 } from "fs/promises";
7608
- import * as path3 from "path";
7937
+ import { open as open3 } from "fs/promises";
7938
+ import * as path4 from "path";
7609
7939
  import { z as z23 } from "zod";
7610
7940
  var SESSION_CONTEXT_FILE_VERSION = 1;
7611
7941
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
@@ -7623,10 +7953,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
7623
7953
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
7624
7954
  var sessionContextFilePath = (dir, providerId, sessionId) => {
7625
7955
  const tool = sessionContextAgentTool(providerId);
7626
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
7956
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path4.isAbsolute(dir)) {
7627
7957
  return void 0;
7628
7958
  }
7629
- return path3.join(dir, tool, `${sessionId}.json`);
7959
+ return path4.join(dir, tool, `${sessionId}.json`);
7630
7960
  };
7631
7961
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
7632
7962
  "session.id",
@@ -7722,7 +8052,7 @@ var stampSessionContext = (events, segments) => events.map((event3) => {
7722
8052
  var readBounded = async (file, maxBytes) => {
7723
8053
  let handle;
7724
8054
  try {
7725
- handle = await open2(file, "r");
8055
+ handle = await open3(file, "r");
7726
8056
  } catch {
7727
8057
  return void 0;
7728
8058
  }
@@ -8675,8 +9005,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8675
9005
  };
8676
9006
 
8677
9007
  // src/runtime/git-worktree.ts
8678
- import { lstat, open as open3, stat as stat2 } from "fs/promises";
8679
- import * as path4 from "path";
9008
+ import { lstat, open as open4, stat as stat3 } from "fs/promises";
9009
+ import * as path5 from "path";
8680
9010
  var MAX_WORKTREE_WALK_DEPTH = 128;
8681
9011
  var MAX_GIT_FILE_BYTES = 4096;
8682
9012
  var MAX_CACHE_ENTRIES = 1024;
@@ -8687,7 +9017,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
8687
9017
  var readBounded2 = async (filePath) => {
8688
9018
  let handle;
8689
9019
  try {
8690
- handle = await open3(filePath, "r");
9020
+ handle = await open4(filePath, "r");
8691
9021
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
8692
9022
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
8693
9023
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -8708,7 +9038,7 @@ var parseHeadBranch = (head) => {
8708
9038
  return branch;
8709
9039
  };
8710
9040
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
8711
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
9041
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path5.resolve(base, target);
8712
9042
  var parseGitDirFile = (content, worktreeRoot) => {
8713
9043
  const line = firstLine(content);
8714
9044
  return resolveGitPath(
@@ -8728,26 +9058,26 @@ var isMissing = async (filePath) => {
8728
9058
  };
8729
9059
  var isDirectory = async (directory) => {
8730
9060
  try {
8731
- return (await stat2(directory)).isDirectory();
9061
+ return (await stat3(directory)).isDirectory();
8732
9062
  } catch {
8733
9063
  return false;
8734
9064
  }
8735
9065
  };
8736
9066
  var repositoryOf = async (worktreeRoot, gitDir) => {
8737
- const commonDirFile = path4.join(gitDir, "commondir");
9067
+ const commonDirFile = path5.join(gitDir, "commondir");
8738
9068
  const content = await readBounded2(commonDirFile);
8739
9069
  if (content === void 0) {
8740
9070
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
8741
9071
  }
8742
9072
  const commonDir = parseCommonDirFile(content, gitDir);
8743
- const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
9073
+ const mainRoot = commonDir !== void 0 && path5.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path5.dirname(commonDir) : void 0;
8744
9074
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
8745
9075
  };
8746
9076
  var probeDirectory = async (directory) => {
8747
- const dotGit = path4.join(directory, ".git");
9077
+ const dotGit = path5.join(directory, ".git");
8748
9078
  let info;
8749
9079
  try {
8750
- info = await stat2(dotGit);
9080
+ info = await stat3(dotGit);
8751
9081
  } catch {
8752
9082
  return ABSENT;
8753
9083
  }
@@ -8761,7 +9091,7 @@ var probeDirectory = async (directory) => {
8761
9091
  if (gitDir === void 0) {
8762
9092
  return INVALID;
8763
9093
  }
8764
- const head = await readBounded2(path4.join(gitDir, "HEAD"));
9094
+ const head = await readBounded2(path5.join(gitDir, "HEAD"));
8765
9095
  if (head === void 0) {
8766
9096
  return INVALID;
8767
9097
  }
@@ -8791,10 +9121,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8791
9121
  };
8792
9122
  const locate = async (absolutePath) => {
8793
9123
  try {
8794
- if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
9124
+ if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8795
9125
  return void 0;
8796
9126
  }
8797
- let directory = path4.resolve(absolutePath);
9127
+ let directory = path5.resolve(absolutePath);
8798
9128
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
8799
9129
  const probe = await cachedProbe(directory);
8800
9130
  if (probe.kind === "worktree") {
@@ -8803,7 +9133,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8803
9133
  if (probe.kind === "invalid") {
8804
9134
  return void 0;
8805
9135
  }
8806
- const parent = path4.dirname(directory);
9136
+ const parent = path5.dirname(directory);
8807
9137
  if (parent === directory) {
8808
9138
  return void 0;
8809
9139
  }
@@ -9015,7 +9345,7 @@ var createCallbackDeduplicator = (deps) => {
9015
9345
  };
9016
9346
 
9017
9347
  // src/telemetry/semconv.ts
9018
- import { createHash as createHash4 } from "crypto";
9348
+ import { createHash as createHash5 } from "crypto";
9019
9349
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
9020
9350
  import { millisToHrTime } from "@opentelemetry/core";
9021
9351
  import {
@@ -9034,7 +9364,7 @@ import {
9034
9364
  } from "@opentelemetry/semantic-conventions/incubating";
9035
9365
 
9036
9366
  // src/version.ts
9037
- var VERSION = "0.13.0";
9367
+ var VERSION = "0.13.2";
9038
9368
 
9039
9369
  // src/telemetry/export-identity.ts
9040
9370
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9145,7 +9475,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
9145
9475
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
9146
9476
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
9147
9477
  var FIELD_SEPARATOR = "\0";
9148
- var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
9478
+ var digestHex = (parts, length) => createHash5("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
9149
9479
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
9150
9480
  var familyOf = (type) => {
9151
9481
  switch (type) {
@@ -9360,7 +9690,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9360
9690
  const resolved = resolvePairing(group, anchor, correlation);
9361
9691
  const traceId = plan.traceId;
9362
9692
  const spanId = plan.spanId;
9363
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
9693
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
9694
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
9364
9695
  let name = group.ref.family;
9365
9696
  let kind = SpanKind.INTERNAL;
9366
9697
  let status = { code: SpanStatusCode.UNSET };
@@ -9584,7 +9915,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
9584
9915
  // persist something that should have been persisted.
9585
9916
  correlation === void 0 && correlationAvailable === void 0);
9586
9917
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
9587
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
9918
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
9588
9919
  return {
9589
9920
  group,
9590
9921
  anchor,
@@ -9604,6 +9935,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
9604
9935
  )
9605
9936
  };
9606
9937
  };
9938
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9939
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9607
9940
  var canonicalEventTraceIdentities = (events, options = {}) => {
9608
9941
  const layout = layoutBatch(events);
9609
9942
  const correlations = indexCorrelations(options.correlations);
@@ -9628,7 +9961,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
9628
9961
  });
9629
9962
  continue;
9630
9963
  }
9631
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
9964
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3) ?? resumedSessionParent(plan.group.ref, plan.correlation);
9632
9965
  identities.set(event3.eventId, {
9633
9966
  traceId: plan.traceId,
9634
9967
  spanId: plan.spanId,
@@ -9711,6 +10044,7 @@ var encodeRecord = (record) => ({
9711
10044
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
9712
10045
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9713
10046
  ...record.exported === true ? { exported: true } : {},
10047
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
9714
10048
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
9715
10049
  ...encodeAttributes(record.attributes)
9716
10050
  }
@@ -9734,6 +10068,7 @@ var decodeRecord = (attributes) => {
9734
10068
  return { kind: "corrupt" };
9735
10069
  }
9736
10070
  const exported = attributes["exported"] === true;
10071
+ const runKey = optionalString(attributes["runKey"]);
9737
10072
  const parentFamily = attributes["parentFamily"];
9738
10073
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
9739
10074
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -9748,21 +10083,24 @@ var decodeRecord = (attributes) => {
9748
10083
  ...endedAt === void 0 ? {} : { endedAt },
9749
10084
  ...parent === void 0 ? {} : { parent },
9750
10085
  ...exported ? { exported: true } : {},
10086
+ ...runKey === void 0 ? {} : { runKey },
9751
10087
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
9752
10088
  }
9753
10089
  };
9754
10090
  };
9755
- var factsOf = (record) => ({
10091
+ var factsOf2 = (record) => ({
9756
10092
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
9757
10093
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9758
10094
  ...record.parent === void 0 ? {} : { parent: record.parent },
9759
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
10095
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
10096
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
9760
10097
  });
9761
10098
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
9762
10099
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
9763
10100
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
9764
10101
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
9765
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
10102
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
10103
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
9766
10104
  });
9767
10105
  var orphanClassificationOf = (reason) => {
9768
10106
  switch (reason) {
@@ -9808,7 +10146,7 @@ var createSpanCorrelator = (deps) => {
9808
10146
  return { status: "conflict", reason: "provider-mismatch" };
9809
10147
  }
9810
10148
  if (existing.startEventId === input.eventId) {
9811
- return { status: "duplicate", facts: factsOf(existing) };
10149
+ return { status: "duplicate", facts: factsOf2(existing) };
9812
10150
  }
9813
10151
  if (existing.startEventId === void 0 && existing.endEventId !== void 0) {
9814
10152
  const completed = {
@@ -9819,18 +10157,20 @@ var createSpanCorrelator = (deps) => {
9819
10157
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9820
10158
  };
9821
10159
  await stateStore.write(key, encodeRecord(completed));
9822
- return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
10160
+ return existing.exported === true ? { status: "published", facts: factsOf2(completed) } : { status: "recorded", facts: factsOf2(completed) };
9823
10161
  }
9824
10162
  }
10163
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
9825
10164
  const fresh = {
9826
10165
  providerId: input.providerId,
9827
10166
  startEventId: input.eventId,
9828
10167
  startedAt: input.occurredAt,
10168
+ ...previouslyExported ? { runKey: input.eventId } : {},
9829
10169
  ...input.parent === void 0 ? {} : { parent: input.parent },
9830
10170
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9831
10171
  };
9832
10172
  await stateStore.write(key, encodeRecord(fresh));
9833
- return { status: "recorded", facts: factsOf(fresh) };
10173
+ return { status: "recorded", facts: factsOf2(fresh) };
9834
10174
  });
9835
10175
  const recordEnd = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
9836
10176
  const key = keyFor(input);
@@ -9849,7 +10189,7 @@ var createSpanCorrelator = (deps) => {
9849
10189
  exported: true
9850
10190
  };
9851
10191
  await stateStore.write(key, encodeRecord(endOnly));
9852
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(endOnly) };
10192
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf2(endOnly) };
9853
10193
  }
9854
10194
  const existing = decoded.record;
9855
10195
  if (existing.providerId !== input.providerId) {
@@ -9860,7 +10200,7 @@ var createSpanCorrelator = (deps) => {
9860
10200
  };
9861
10201
  }
9862
10202
  if (existing.endEventId === input.eventId) {
9863
- return { status: "duplicate", facts: factsOf(existing) };
10203
+ return { status: "duplicate", facts: factsOf2(existing) };
9864
10204
  }
9865
10205
  if (existing.endEventId !== void 0) {
9866
10206
  return {
@@ -9877,7 +10217,7 @@ var createSpanCorrelator = (deps) => {
9877
10217
  exported: true
9878
10218
  };
9879
10219
  await stateStore.write(key, encodeRecord(replaced));
9880
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(replaced) };
10220
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf2(replaced) };
9881
10221
  }
9882
10222
  if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {
9883
10223
  await stateStore.delete(key);
@@ -9894,7 +10234,7 @@ var createSpanCorrelator = (deps) => {
9894
10234
  status: "matched",
9895
10235
  startedAt: existing.startedAt,
9896
10236
  durationMillis: Math.max(0, input.occurredAt - existing.startedAt),
9897
- facts: factsOf(closed)
10237
+ facts: factsOf2(closed)
9898
10238
  };
9899
10239
  });
9900
10240
  const correlateGroup = async (group) => {
@@ -10163,7 +10503,7 @@ var createUsageAccumulator = (deps) => {
10163
10503
  };
10164
10504
 
10165
10505
  // src/lifecycle/metric-series.ts
10166
- import { createHash as createHash5 } from "crypto";
10506
+ import { createHash as createHash6 } from "crypto";
10167
10507
 
10168
10508
  // src/telemetry/metric-model.ts
10169
10509
  var TOKEN_USAGE_BUCKETS = Object.freeze([
@@ -10446,7 +10786,7 @@ var TURN_START_SEGMENT = "turn-start";
10446
10786
  var SHARED_SCOPE = "all";
10447
10787
  var SHARED_LOCK = "otelhook.metrics.shared";
10448
10788
  var sessionScope = (sessionId) => `s=${sessionId}`;
10449
- var digest2 = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
10789
+ var digest2 = (identity) => createHash6("sha256").update(identity).digest("base64url").slice(0, 43);
10450
10790
  var toStoredHistogram = (histogram) => ({
10451
10791
  count: histogram.count,
10452
10792
  sum: histogram.sum,
@@ -10688,30 +11028,29 @@ var createBoundedMemoryStateStore = (options) => {
10688
11028
 
10689
11029
  // src/state/filesystem-store.ts
10690
11030
  import { randomBytes as randomBytes2 } from "crypto";
10691
- import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10692
- import * as path5 from "path";
11031
+ import { mkdir, open as open5, readFile, readdir as readdir2, rename, stat as stat4, unlink, writeFile } from "fs/promises";
11032
+ import * as path6 from "path";
10693
11033
 
10694
11034
  // src/state/keys.ts
10695
- import { createHash as createHash6 } from "crypto";
11035
+ import { createHash as createHash7 } from "crypto";
10696
11036
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
10697
11037
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
10698
11038
  var sanitizeSegment = (segment) => {
10699
11039
  if (isSafeSegment(segment)) {
10700
11040
  return segment;
10701
11041
  }
10702
- return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
11042
+ return `h_${createHash7("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
10703
11043
  };
10704
11044
  var namespaceSegments = (namespace) => [
10705
11045
  sanitizeSegment(namespace.providerId),
10706
11046
  sanitizeSegment(namespace.installationId)
10707
11047
  ];
10708
- var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
11048
+ var keyDigest = (key) => createHash7("sha256").update(key, "utf8").digest("hex");
10709
11049
 
10710
11050
  // src/state/filesystem-store.ts
10711
11051
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
10712
- var sleep = (millis) => new Promise((resolve5) => {
10713
- const timer = setTimeout(resolve5, millis);
10714
- timer.unref?.();
11052
+ var sleep2 = (millis) => new Promise((resolve5) => {
11053
+ setTimeout(resolve5, millis);
10715
11054
  });
10716
11055
  var wrapFsError = (thrown, operation) => {
10717
11056
  if (thrown instanceof Error) {
@@ -10721,10 +11060,10 @@ var wrapFsError = (thrown, operation) => {
10721
11060
  };
10722
11061
  var createFilesystemStateStore = (options) => {
10723
11062
  const [providerSegment, installationSegment] = namespaceSegments(options);
10724
- const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
10725
- const recordsDir = path5.join(baseDir, "records");
10726
- const quarantineDir = path5.join(baseDir, "quarantine");
10727
- const locksDir = path5.join(baseDir, "locks");
11063
+ const baseDir = path6.join(options.rootDir, providerSegment, installationSegment);
11064
+ const recordsDir = path6.join(baseDir, "records");
11065
+ const quarantineDir = path6.join(baseDir, "quarantine");
11066
+ const locksDir = path6.join(baseDir, "locks");
10728
11067
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
10729
11068
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
10730
11069
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -10748,11 +11087,11 @@ var createFilesystemStateStore = (options) => {
10748
11087
  throw wrapFsError(thrown, "ensure-dirs");
10749
11088
  }
10750
11089
  };
10751
- const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
10752
- const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10753
- const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
11090
+ const recordPath = (key) => path6.join(recordsDir, `${keyDigest(key)}.json`);
11091
+ const tempPath = (key) => path6.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
11092
+ const lockPath = (sessionId) => path6.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10754
11093
  const quarantine = async (filePath, key, reason) => {
10755
- const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
11094
+ const dest = path6.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10756
11095
  try {
10757
11096
  await rename(filePath, dest);
10758
11097
  } catch {
@@ -10816,7 +11155,7 @@ var createFilesystemStateStore = (options) => {
10816
11155
  const startedAt = options.clock.monotonicMillis();
10817
11156
  for (; ; ) {
10818
11157
  try {
10819
- const handle = await open4(filePath, "wx");
11158
+ const handle = await open5(filePath, "wx");
10820
11159
  try {
10821
11160
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
10822
11161
  } finally {
@@ -10831,14 +11170,29 @@ var createFilesystemStateStore = (options) => {
10831
11170
  }
10832
11171
  }
10833
11172
  const stale = await (async () => {
11173
+ let raw;
11174
+ try {
11175
+ raw = await readFile(filePath, "utf8");
11176
+ } catch (thrown) {
11177
+ return isErrnoException(thrown, "ENOENT") ? "gone" : true;
11178
+ }
10834
11179
  try {
10835
- const raw = await readFile(filePath, "utf8");
10836
11180
  const parsed = JSON.parse(raw);
10837
- return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
11181
+ if (typeof parsed.acquiredAt === "number") {
11182
+ return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
11183
+ }
10838
11184
  } catch {
10839
- return true;
11185
+ }
11186
+ try {
11187
+ const stats = await stat4(filePath);
11188
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
11189
+ } catch {
11190
+ return "gone";
10840
11191
  }
10841
11192
  })();
11193
+ if (stale === "gone") {
11194
+ continue;
11195
+ }
10842
11196
  if (stale) {
10843
11197
  await unlink(filePath).catch(() => void 0);
10844
11198
  continue;
@@ -10846,7 +11200,7 @@ var createFilesystemStateStore = (options) => {
10846
11200
  if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
10847
11201
  throw new StateLockTimeoutError(sessionId, timeoutMillis);
10848
11202
  }
10849
- await sleep(lockPollIntervalMillis);
11203
+ await sleep2(lockPollIntervalMillis);
10850
11204
  }
10851
11205
  };
10852
11206
  return {
@@ -10870,7 +11224,7 @@ var createFilesystemStateStore = (options) => {
10870
11224
  await ensureDirs();
10871
11225
  let entries;
10872
11226
  try {
10873
- entries = await readdir(recordsDir);
11227
+ entries = await readdir2(recordsDir);
10874
11228
  } catch (thrown) {
10875
11229
  if (isErrnoException(thrown, "ENOENT")) {
10876
11230
  return [];
@@ -10884,7 +11238,7 @@ var createFilesystemStateStore = (options) => {
10884
11238
  }
10885
11239
  let raw;
10886
11240
  try {
10887
- raw = await readFile(path5.join(recordsDir, entry), "utf8");
11241
+ raw = await readFile(path6.join(recordsDir, entry), "utf8");
10888
11242
  } catch {
10889
11243
  continue;
10890
11244
  }
@@ -10922,7 +11276,7 @@ var createFilesystemStateStore = (options) => {
10922
11276
  let scanned = 0;
10923
11277
  let entries;
10924
11278
  try {
10925
- entries = await readdir(recordsDir);
11279
+ entries = await readdir2(recordsDir);
10926
11280
  } catch (thrown) {
10927
11281
  if (!isErrnoException(thrown, "ENOENT")) {
10928
11282
  throw wrapFsError(thrown, "prune");
@@ -10937,7 +11291,7 @@ var createFilesystemStateStore = (options) => {
10937
11291
  continue;
10938
11292
  }
10939
11293
  scanned += 1;
10940
- const filePath = path5.join(recordsDir, entry);
11294
+ const filePath = path6.join(recordsDir, entry);
10941
11295
  try {
10942
11296
  const raw = await readFile(filePath, "utf8");
10943
11297
  const envelope = JSON.parse(raw);
@@ -10952,12 +11306,12 @@ var createFilesystemStateStore = (options) => {
10952
11306
  }
10953
11307
  let lockEntries;
10954
11308
  try {
10955
- lockEntries = await readdir(locksDir);
11309
+ lockEntries = await readdir2(locksDir);
10956
11310
  } catch {
10957
11311
  lockEntries = [];
10958
11312
  }
10959
11313
  for (const entry of lockEntries) {
10960
- const filePath = path5.join(locksDir, entry);
11314
+ const filePath = path6.join(locksDir, entry);
10961
11315
  try {
10962
11316
  const raw = await readFile(filePath, "utf8");
10963
11317
  const parsed = JSON.parse(raw);
@@ -10975,8 +11329,8 @@ var createFilesystemStateStore = (options) => {
10975
11329
 
10976
11330
  // src/telemetry/spool-queue.ts
10977
11331
  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";
10979
- import * as path6 from "path";
11332
+ import { mkdir as mkdir2, open as open6, readFile as readFile2, readdir as readdir3, rename as rename2, stat as stat5, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
11333
+ import * as path7 from "path";
10980
11334
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10981
11335
  total: 0,
10982
11336
  age: 0,
@@ -10992,7 +11346,7 @@ var enqueuedAtOf = (fileName) => {
10992
11346
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10993
11347
  var readSpoolDropCounts = async (queueDir) => {
10994
11348
  try {
10995
- const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
11349
+ const parsed = JSON.parse(await readFile2(path7.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10996
11350
  if (typeof parsed !== "object" || parsed === null) {
10997
11351
  return EMPTY_SPOOL_DROP_COUNTS;
10998
11352
  }
@@ -11013,7 +11367,7 @@ var readSpoolDropCounts = async (queueDir) => {
11013
11367
  var readSpoolQueueStats = async (queueDir) => {
11014
11368
  let entries;
11015
11369
  try {
11016
- entries = await readdir2(queueDir);
11370
+ entries = await readdir3(queueDir);
11017
11371
  } catch {
11018
11372
  return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
11019
11373
  }
@@ -11021,7 +11375,7 @@ var readSpoolQueueStats = async (queueDir) => {
11021
11375
  let bytes = 0;
11022
11376
  for (const file of files) {
11023
11377
  try {
11024
- bytes += (await stat3(path6.join(queueDir, file))).size;
11378
+ bytes += (await stat5(path7.join(queueDir, file))).size;
11025
11379
  } catch {
11026
11380
  }
11027
11381
  }
@@ -11034,11 +11388,56 @@ var readSpoolQueueStats = async (queueDir) => {
11034
11388
  };
11035
11389
  };
11036
11390
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
11391
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
11392
+ var CLAIM_SUFFIX = ".claim";
11393
+ var RELEASING_SUFFIX = ".releasing";
11394
+ var isClaimOwnerAlive = (pid) => {
11395
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
11396
+ return true;
11397
+ }
11398
+ if (pid === process.pid) {
11399
+ return true;
11400
+ }
11401
+ try {
11402
+ process.kill(pid, 0);
11403
+ return true;
11404
+ } catch (thrown) {
11405
+ return thrown?.code !== "ESRCH";
11406
+ }
11407
+ };
11037
11408
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
11409
+ var readClaim = async (claimPath) => {
11410
+ try {
11411
+ const parsed = JSON.parse(await readFile2(claimPath, "utf8"));
11412
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
11413
+ } catch {
11414
+ return void 0;
11415
+ }
11416
+ };
11417
+ var releaseClaim = async (claimPath, token) => {
11418
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes3(4).toString("hex")}${RELEASING_SUFFIX}`;
11419
+ for (let attempt = 1; ; attempt += 1) {
11420
+ try {
11421
+ await rename2(claimPath, tombstone);
11422
+ break;
11423
+ } catch (thrown) {
11424
+ if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
11425
+ return;
11426
+ }
11427
+ await new Promise((resolve5) => setTimeout(resolve5, 10 * attempt));
11428
+ }
11429
+ }
11430
+ const captured = await readClaim(tombstone);
11431
+ if (captured !== void 0 && captured.token !== token) {
11432
+ await rename2(tombstone, claimPath).catch(() => void 0);
11433
+ return;
11434
+ }
11435
+ await unlink2(tombstone).catch(() => void 0);
11436
+ };
11038
11437
  var createSpoolQueue = (options) => {
11039
11438
  const [providerSegment, installationSegment] = namespaceSegments(options);
11040
- const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11041
- const corruptDir = path6.join(
11439
+ const queueDir = path7.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11440
+ const corruptDir = path7.join(
11042
11441
  options.rootDir,
11043
11442
  providerSegment,
11044
11443
  installationSegment,
@@ -11064,7 +11463,7 @@ var createSpoolQueue = (options) => {
11064
11463
  const listSorted = async () => {
11065
11464
  let entries;
11066
11465
  try {
11067
- entries = await readdir2(queueDir);
11466
+ entries = await readdir3(queueDir);
11068
11467
  } catch (thrown) {
11069
11468
  if (isErrnoException2(thrown, "ENOENT")) {
11070
11469
  return [];
@@ -11085,9 +11484,9 @@ var createSpoolQueue = (options) => {
11085
11484
  [reason]: current[reason] + dropped,
11086
11485
  lastDroppedAt: options.clock.now()
11087
11486
  };
11088
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11487
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11089
11488
  await writeFile2(tmp, JSON.stringify(next), "utf8");
11090
- await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
11489
+ await rename2(tmp, path7.join(queueDir, SPOOL_DROPS_FILE));
11091
11490
  } catch {
11092
11491
  }
11093
11492
  options.logger?.warn("durable spool dropped batches", {
@@ -11103,7 +11502,7 @@ var createSpoolQueue = (options) => {
11103
11502
  let bytes = 0;
11104
11503
  if (options.maxBytes !== void 0) {
11105
11504
  try {
11106
- bytes = (await stat3(path6.join(queueDir, name))).size;
11505
+ bytes = (await stat5(path7.join(queueDir, name))).size;
11107
11506
  } catch {
11108
11507
  continue;
11109
11508
  }
@@ -11117,7 +11516,7 @@ var createSpoolQueue = (options) => {
11117
11516
  let removed = 0;
11118
11517
  for (const file of files) {
11119
11518
  try {
11120
- await unlink2(path6.join(queueDir, file.name));
11519
+ await unlink2(path7.join(queueDir, file.name));
11121
11520
  removed += 1;
11122
11521
  } catch {
11123
11522
  }
@@ -11177,15 +11576,69 @@ var createSpoolQueue = (options) => {
11177
11576
  }
11178
11577
  }
11179
11578
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
11180
- const target = path6.join(queueDir, fileName);
11181
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11579
+ const target = path7.join(queueDir, fileName);
11580
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11182
11581
  await writeFile2(tmp, serialized, "utf8");
11183
11582
  await rename2(tmp, target);
11184
11583
  return { spooled: true };
11185
11584
  };
11585
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
11586
+ const staleClaim = async (claimPath) => {
11587
+ const claim = await readClaim(claimPath);
11588
+ const now = Date.now();
11589
+ if (claim !== void 0) {
11590
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
11591
+ }
11592
+ try {
11593
+ return now - (await stat5(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
11594
+ } catch {
11595
+ return { stale: false };
11596
+ }
11597
+ };
11598
+ const releaseStaleClaims = async () => {
11599
+ let entries;
11600
+ try {
11601
+ entries = await readdir3(queueDir);
11602
+ } catch {
11603
+ return;
11604
+ }
11605
+ const now = Date.now();
11606
+ for (const entry of entries) {
11607
+ const entryPath = path7.join(queueDir, entry);
11608
+ if (entry.endsWith(CLAIM_SUFFIX)) {
11609
+ const staleness = await staleClaim(entryPath);
11610
+ if (staleness.stale) {
11611
+ await releaseClaim(entryPath, staleness.token);
11612
+ }
11613
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
11614
+ try {
11615
+ if (now - (await stat5(entryPath)).mtimeMs > claimStaleMillis) {
11616
+ await unlink2(entryPath);
11617
+ }
11618
+ } catch {
11619
+ }
11620
+ }
11621
+ }
11622
+ };
11623
+ const claimBatch = async (claimPath) => {
11624
+ const token = randomBytes3(16).toString("hex");
11625
+ try {
11626
+ const handle = await open6(claimPath, "wx");
11627
+ try {
11628
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
11629
+ await handle.writeFile(JSON.stringify(contents), "utf8");
11630
+ } finally {
11631
+ await handle.close();
11632
+ }
11633
+ return token;
11634
+ } catch {
11635
+ return void 0;
11636
+ }
11637
+ };
11186
11638
  const drain = async (send, drainOptions) => {
11187
11639
  await ensureDirs();
11188
11640
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
11641
+ await releaseStaleClaims();
11189
11642
  let files = await listSorted();
11190
11643
  if (options.maxAgeMillis !== void 0) {
11191
11644
  const now = options.clock.now();
@@ -11203,12 +11656,7 @@ var createSpoolQueue = (options) => {
11203
11656
  let failed = 0;
11204
11657
  let quarantined = 0;
11205
11658
  let index = 0;
11206
- for (; index < files.length && index < cap; index += 1) {
11207
- const fileName = files[index];
11208
- if (fileName === void 0) {
11209
- break;
11210
- }
11211
- const filePath = path6.join(queueDir, fileName);
11659
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
11212
11660
  const quarantine = async (rejection) => {
11213
11661
  quarantined += 1;
11214
11662
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -11217,17 +11665,27 @@ var createSpoolQueue = (options) => {
11217
11665
  "spool.queue": options.queueName
11218
11666
  });
11219
11667
  try {
11220
- await rename2(filePath, path6.join(corruptDir, fileName));
11668
+ await rename2(filePath, path7.join(corruptDir, fileName));
11221
11669
  } catch {
11222
11670
  await unlink2(filePath).catch(() => void 0);
11223
11671
  }
11224
11672
  };
11673
+ let text;
11674
+ try {
11675
+ text = await readFile2(filePath, "utf8");
11676
+ } catch (thrown) {
11677
+ if (thrown?.code === "ENOENT") {
11678
+ return "next";
11679
+ }
11680
+ await quarantine("unreadable");
11681
+ return "next";
11682
+ }
11225
11683
  let parsed;
11226
11684
  try {
11227
- parsed = JSON.parse(await readFile2(filePath, "utf8"));
11685
+ parsed = JSON.parse(text);
11228
11686
  } catch {
11229
11687
  await quarantine("unparseable-json");
11230
- continue;
11688
+ return "next";
11231
11689
  }
11232
11690
  const validation = options.validate(parsed, {
11233
11691
  providerId: options.providerId,
@@ -11235,7 +11693,10 @@ var createSpoolQueue = (options) => {
11235
11693
  });
11236
11694
  if ("rejection" in validation) {
11237
11695
  await quarantine(validation.rejection);
11238
- continue;
11696
+ return "next";
11697
+ }
11698
+ if ((await readClaim(claimPath))?.token !== token) {
11699
+ return "next";
11239
11700
  }
11240
11701
  let delivered;
11241
11702
  try {
@@ -11247,13 +11708,34 @@ var createSpoolQueue = (options) => {
11247
11708
  if (await unlink2(filePath).then(() => true, () => false)) {
11248
11709
  await recordDrops("rejected", 1);
11249
11710
  }
11250
- continue;
11711
+ return "next";
11251
11712
  }
11252
11713
  if (delivered) {
11253
11714
  await unlink2(filePath).catch(() => void 0);
11254
11715
  drained += 1;
11255
- } else {
11256
- failed += 1;
11716
+ return "next";
11717
+ }
11718
+ failed += 1;
11719
+ return "stop";
11720
+ };
11721
+ for (; index < files.length && index < cap; index += 1) {
11722
+ const fileName = files[index];
11723
+ if (fileName === void 0) {
11724
+ break;
11725
+ }
11726
+ const filePath = path7.join(queueDir, fileName);
11727
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
11728
+ const token = await claimBatch(claimPath);
11729
+ if (token === void 0) {
11730
+ continue;
11731
+ }
11732
+ let outcome;
11733
+ try {
11734
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
11735
+ } finally {
11736
+ await releaseClaim(claimPath, token);
11737
+ }
11738
+ if (outcome === "stop") {
11257
11739
  break;
11258
11740
  }
11259
11741
  }
@@ -11367,7 +11849,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
11367
11849
  });
11368
11850
 
11369
11851
  // src/telemetry/otlp-sink.ts
11370
- import { ExportResultCode } from "@opentelemetry/core";
11852
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
11371
11853
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
11372
11854
 
11373
11855
  // src/diagnostics/health.ts
@@ -11420,6 +11902,217 @@ var isPermanentExportFailure = (result) => {
11420
11902
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
11421
11903
  };
11422
11904
 
11905
+ // src/telemetry/endpoint-health.ts
11906
+ import { createHash as createHash8, randomBytes as randomBytes4 } from "crypto";
11907
+ import { mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
11908
+ import * as http from "http";
11909
+ import * as https from "https";
11910
+ import path8 from "path";
11911
+ import { ExportResultCode } from "@opentelemetry/core";
11912
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
11913
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
11914
+ "ECONNREFUSED",
11915
+ "ECONNRESET",
11916
+ "ETIMEDOUT",
11917
+ "EPIPE",
11918
+ "EHOSTUNREACH",
11919
+ "ENETUNREACH",
11920
+ "EHOSTDOWN",
11921
+ "ENETDOWN",
11922
+ "EAI_AGAIN",
11923
+ "ENOTFOUND",
11924
+ ENDPOINT_DOWN_ERROR_CODE
11925
+ ]);
11926
+ var isUnreachableExportFailure = (result) => {
11927
+ if (result.code === ExportResultCode.SUCCESS) {
11928
+ return false;
11929
+ }
11930
+ const error = result.error;
11931
+ const code = error?.code;
11932
+ if (typeof code === "string") {
11933
+ return UNREACHABLE_NETWORK_CODES.has(code);
11934
+ }
11935
+ if (code !== void 0) {
11936
+ return false;
11937
+ }
11938
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
11939
+ };
11940
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
11941
+ const target = agent;
11942
+ const original = target.createConnection.bind(agent);
11943
+ target.createConnection = (options, callback) => {
11944
+ const socket = original(options, callback);
11945
+ if (socket !== void 0 && socket.connecting) {
11946
+ const timer = setTimeout(() => {
11947
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
11948
+ socket.destroy(error);
11949
+ }, connectTimeoutMillis);
11950
+ timer.unref();
11951
+ const clear = () => {
11952
+ clearTimeout(timer);
11953
+ };
11954
+ socket.once("connect", clear);
11955
+ socket.once("close", clear);
11956
+ }
11957
+ return socket;
11958
+ };
11959
+ return agent;
11960
+ };
11961
+ var boundedExporterOptions = (exporter) => {
11962
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
11963
+ let agents = {};
11964
+ return {
11965
+ timeoutMillis,
11966
+ httpAgentOptions: (protocol) => {
11967
+ if (protocol === "https:") {
11968
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
11969
+ return agents.https;
11970
+ }
11971
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
11972
+ return agents.http;
11973
+ }
11974
+ };
11975
+ };
11976
+ var parseMark = (raw) => {
11977
+ try {
11978
+ const parsed = JSON.parse(raw);
11979
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
11980
+ downUntil: parsed.downUntil,
11981
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
11982
+ } : void 0;
11983
+ } catch {
11984
+ return void 0;
11985
+ }
11986
+ };
11987
+ var originOf = (url) => {
11988
+ if (url === void 0) {
11989
+ return void 0;
11990
+ }
11991
+ try {
11992
+ return new URL(url).origin;
11993
+ } catch {
11994
+ return void 0;
11995
+ }
11996
+ };
11997
+ var createEndpointHealth = (options) => {
11998
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
11999
+ const gates = /* @__PURE__ */ new Map();
12000
+ const createGate = (origin) => {
12001
+ const digest3 = createHash8("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
12002
+ const dir = options.rootDir === void 0 ? void 0 : path8.join(options.rootDir, "endpoint-health");
12003
+ const file = dir === void 0 ? void 0 : path8.join(dir, `${digest3}.json`);
12004
+ let downUntil = 0;
12005
+ let failures = 0;
12006
+ let marked = false;
12007
+ let loaded;
12008
+ let warned = false;
12009
+ const write = async (mark) => {
12010
+ if (file === void 0 || dir === void 0) {
12011
+ return;
12012
+ }
12013
+ try {
12014
+ await mkdir3(dir, { recursive: true });
12015
+ const tmp = path8.join(dir, `.tmp-${randomBytes4(6).toString("hex")}.json`);
12016
+ await writeFile3(tmp, `${JSON.stringify(mark)}
12017
+ `);
12018
+ await rename3(tmp, file);
12019
+ marked = true;
12020
+ } catch {
12021
+ }
12022
+ };
12023
+ const load = () => {
12024
+ loaded ??= (async () => {
12025
+ if (file === void 0) {
12026
+ return;
12027
+ }
12028
+ let raw;
12029
+ try {
12030
+ raw = await readFile3(file, "utf8");
12031
+ } catch {
12032
+ return;
12033
+ }
12034
+ marked = true;
12035
+ const mark = parseMark(raw);
12036
+ if (mark === void 0) {
12037
+ return;
12038
+ }
12039
+ failures = mark.failures;
12040
+ const now = options.clock.now();
12041
+ if (mark.downUntil > now) {
12042
+ downUntil = mark.downUntil;
12043
+ return;
12044
+ }
12045
+ await write({ downUntil: now + options.probeMillis, failures });
12046
+ })();
12047
+ return loaded;
12048
+ };
12049
+ return {
12050
+ available: async () => {
12051
+ if (downMillis === 0) {
12052
+ return true;
12053
+ }
12054
+ await load();
12055
+ return options.clock.now() >= downUntil;
12056
+ },
12057
+ record: async (result) => {
12058
+ if (downMillis === 0) {
12059
+ return;
12060
+ }
12061
+ if (!isUnreachableExportFailure(result)) {
12062
+ if (!marked && downUntil === 0) {
12063
+ return;
12064
+ }
12065
+ downUntil = 0;
12066
+ failures = 0;
12067
+ marked = false;
12068
+ if (file !== void 0) {
12069
+ await unlink3(file).catch(() => void 0);
12070
+ }
12071
+ return;
12072
+ }
12073
+ failures += 1;
12074
+ downUntil = options.clock.now() + downMillis;
12075
+ if (!warned) {
12076
+ warned = true;
12077
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
12078
+ "export.endpoint_down_millis": downMillis,
12079
+ "export.endpoint_failures": failures
12080
+ });
12081
+ }
12082
+ await write({ downUntil, failures });
12083
+ }
12084
+ };
12085
+ };
12086
+ return {
12087
+ gateFor: (url) => {
12088
+ const origin = originOf(url);
12089
+ if (origin === void 0) {
12090
+ return void 0;
12091
+ }
12092
+ let gate = gates.get(origin);
12093
+ if (gate === void 0) {
12094
+ gate = createGate(origin);
12095
+ gates.set(origin, gate);
12096
+ }
12097
+ return gate;
12098
+ }
12099
+ };
12100
+ };
12101
+ var guardExport = async (gate, send) => {
12102
+ if (gate === void 0) {
12103
+ return send();
12104
+ }
12105
+ if (!await gate.available()) {
12106
+ return {
12107
+ code: ExportResultCode.FAILED,
12108
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
12109
+ };
12110
+ }
12111
+ const result = await send();
12112
+ await gate.record(result).catch(() => void 0);
12113
+ return result;
12114
+ };
12115
+
11423
12116
  // src/telemetry/exporter-resource.ts
11424
12117
  import { resourceFromAttributes } from "@opentelemetry/resources";
11425
12118
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -11559,12 +12252,16 @@ var createOtlpTraceSink = (options) => {
11559
12252
  const exporter = new OTLPTraceExporter({
11560
12253
  url: options.exporter.endpoint,
11561
12254
  headers: { ...options.headers },
11562
- timeoutMillis: options.exporter.timeoutMillis
12255
+ ...boundedExporterOptions(options.exporter)
11563
12256
  });
12257
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
11564
12258
  let shutdownCompleted = false;
11565
- const exportSpans = (spans) => new Promise((resolve5) => {
11566
- exporter.export([...spans], (result) => resolve5(result));
11567
- });
12259
+ const exportSpans = (spans) => guardExport(
12260
+ gate,
12261
+ () => new Promise((resolve5) => {
12262
+ exporter.export([...spans], (result) => resolve5(result));
12263
+ })
12264
+ );
11568
12265
  const toSpoolBatch = (spans, batchResource) => ({
11569
12266
  providerId: options.providerId,
11570
12267
  installationId: options.installationId,
@@ -11577,7 +12274,7 @@ var createOtlpTraceSink = (options) => {
11577
12274
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
11578
12275
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
11579
12276
  const result = await exportSpans(spans);
11580
- if (result.code === ExportResultCode.SUCCESS) {
12277
+ if (result.code === ExportResultCode2.SUCCESS) {
11581
12278
  return true;
11582
12279
  }
11583
12280
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -11616,9 +12313,9 @@ var createOtlpTraceSink = (options) => {
11616
12313
  try {
11617
12314
  result = await exportSpans(batch);
11618
12315
  } catch (thrown) {
11619
- result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
12316
+ result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
11620
12317
  }
11621
- if (result.code === ExportResultCode.SUCCESS) {
12318
+ if (result.code === ExportResultCode2.SUCCESS) {
11622
12319
  accepted += batch.length;
11623
12320
  health.recordSuccess(batch.length, options.clock.now());
11624
12321
  continue;
@@ -11655,6 +12352,9 @@ var createOtlpTraceSink = (options) => {
11655
12352
  if (options.spool === void 0) {
11656
12353
  return { drained: 0, remaining: 0, failed: 0 };
11657
12354
  }
12355
+ if (gate !== void 0 && !await gate.available()) {
12356
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
12357
+ }
11658
12358
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
11659
12359
  if (result.drained > 0) {
11660
12360
  health.recordSuccess(result.drained, options.clock.now());
@@ -12212,7 +12912,7 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
12212
12912
 
12213
12913
  // src/telemetry/otlp-log-sink.ts
12214
12914
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
12215
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
12915
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
12216
12916
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
12217
12917
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
12218
12918
  var resolveLogsEndpoint = (exporter) => {
@@ -12355,12 +13055,16 @@ var createOtlpLogSink = (options) => {
12355
13055
  const exporter = new OTLPLogExporter({
12356
13056
  url: deliverability.endpoint,
12357
13057
  headers: { ...options.headers },
12358
- timeoutMillis: options.exporter.timeoutMillis
13058
+ ...boundedExporterOptions(options.exporter)
12359
13059
  });
13060
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
12360
13061
  let shutdownCompleted = false;
12361
- const exportRecords = (records) => new Promise((resolve5) => {
12362
- exporter.export([...records], (result) => resolve5(result));
12363
- });
13062
+ const exportRecords = (records) => guardExport(
13063
+ gate,
13064
+ () => new Promise((resolve5) => {
13065
+ exporter.export([...records], (result) => resolve5(result));
13066
+ })
13067
+ );
12364
13068
  const toSpoolBatch = (records, batchResource) => ({
12365
13069
  providerId: options.providerId,
12366
13070
  installationId: options.installationId,
@@ -12378,7 +13082,7 @@ var createOtlpLogSink = (options) => {
12378
13082
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
12379
13083
  );
12380
13084
  const result = await exportRecords(records);
12381
- if (result.code === ExportResultCode2.SUCCESS) {
13085
+ if (result.code === ExportResultCode3.SUCCESS) {
12382
13086
  return true;
12383
13087
  }
12384
13088
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -12424,11 +13128,11 @@ var createOtlpLogSink = (options) => {
12424
13128
  result = await exportRecords(batch);
12425
13129
  } catch (thrown) {
12426
13130
  result = {
12427
- code: ExportResultCode2.FAILED,
13131
+ code: ExportResultCode3.FAILED,
12428
13132
  error: thrown instanceof Error ? thrown : new Error("export threw")
12429
13133
  };
12430
13134
  }
12431
- if (result.code === ExportResultCode2.SUCCESS) {
13135
+ if (result.code === ExportResultCode3.SUCCESS) {
12432
13136
  accepted += batch.length;
12433
13137
  health.recordSuccess(batch.length, options.clock.now());
12434
13138
  continue;
@@ -12469,6 +13173,9 @@ var createOtlpLogSink = (options) => {
12469
13173
  if (options.spool === void 0) {
12470
13174
  return { drained: 0, remaining: 0, failed: 0 };
12471
13175
  }
13176
+ if (gate !== void 0 && !await gate.available()) {
13177
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
13178
+ }
12472
13179
  const result = await options.spool.drain(sendSerializedBatch, {
12473
13180
  ...maxBatches === void 0 ? {} : { maxBatches }
12474
13181
  });
@@ -12627,7 +13334,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
12627
13334
 
12628
13335
  // src/telemetry/otlp-metric-sink.ts
12629
13336
  import { ValueType } from "@opentelemetry/api";
12630
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
13337
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
12631
13338
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
12632
13339
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
12633
13340
  import {
@@ -12771,10 +13478,12 @@ var createOtlpMetricSink = (options) => {
12771
13478
  const exporter = new OTLPMetricExporter({
12772
13479
  url: deliverability.endpoint,
12773
13480
  headers: { ...options.headers },
12774
- timeoutMillis: options.exporter.timeoutMillis
13481
+ ...boundedExporterOptions(options.exporter)
12775
13482
  });
13483
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
12776
13484
  let shutdownCompleted = false;
12777
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
13485
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
13486
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
12778
13487
  const payload = {
12779
13488
  resource: batchResource,
12780
13489
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -12783,7 +13492,7 @@ var createOtlpMetricSink = (options) => {
12783
13492
  exporter.export(payload, (result) => resolve5(result));
12784
13493
  } catch (thrown) {
12785
13494
  resolve5({
12786
- code: ExportResultCode3.FAILED,
13495
+ code: ExportResultCode4.FAILED,
12787
13496
  error: thrown instanceof Error ? thrown : new Error("export threw")
12788
13497
  });
12789
13498
  }
@@ -12804,7 +13513,7 @@ var createOtlpMetricSink = (options) => {
12804
13513
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
12805
13514
  );
12806
13515
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
12807
- if (result.code === ExportResultCode3.SUCCESS) {
13516
+ if (result.code === ExportResultCode4.SUCCESS) {
12808
13517
  return true;
12809
13518
  }
12810
13519
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -12815,7 +13524,7 @@ var createOtlpMetricSink = (options) => {
12815
13524
  }
12816
13525
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
12817
13526
  const result = await exportResourceMetrics(points, batchResource, scope);
12818
- if (result.code === ExportResultCode3.SUCCESS) {
13527
+ if (result.code === ExportResultCode4.SUCCESS) {
12819
13528
  health.recordSuccess(points.length, options.clock.now());
12820
13529
  return { accepted: points.length, rejected: 0, errors: [] };
12821
13530
  }
@@ -12855,6 +13564,9 @@ var createOtlpMetricSink = (options) => {
12855
13564
  if (options.spool === void 0) {
12856
13565
  return { drained: 0, remaining: 0, failed: 0 };
12857
13566
  }
13567
+ if (gate !== void 0 && !await gate.available()) {
13568
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
13569
+ }
12858
13570
  const result = await options.spool.drain(sendSerializedBatch, {
12859
13571
  ...maxBatches === void 0 ? {} : { maxBatches }
12860
13572
  });
@@ -12950,6 +13662,13 @@ var createExportDestinationSinks = (options) => {
12950
13662
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
12951
13663
  const destinations = [];
12952
13664
  const skipped = [];
13665
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
13666
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
13667
+ clock: options.clock,
13668
+ ...options.logger === void 0 ? {} : { logger: options.logger },
13669
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
13670
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
13671
+ });
12953
13672
  for (const destination of resolveExportDestinations(options.exporter)) {
12954
13673
  let headers;
12955
13674
  let logHeaders;
@@ -13009,6 +13728,7 @@ var createExportDestinationSinks = (options) => {
13009
13728
  const sinkShared = {
13010
13729
  exporter: policy,
13011
13730
  ...shared,
13731
+ endpointHealth,
13012
13732
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
13013
13733
  ...label === void 0 ? {} : { destination: label }
13014
13734
  };
@@ -13026,6 +13746,7 @@ var createExportDestinationSinks = (options) => {
13026
13746
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
13027
13747
  exporter: policy,
13028
13748
  ...shared,
13749
+ endpointHealth,
13029
13750
  ...label === void 0 ? {} : { destination: label },
13030
13751
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
13031
13752
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -13195,7 +13916,14 @@ var createHookRuntime = (options) => {
13195
13916
  privacy,
13196
13917
  logger,
13197
13918
  installationId: options.installationId,
13198
- payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
13919
+ payloadEnrichers: options.payloadEnrichers ?? [
13920
+ ...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
13921
+ ...readsCodexRolloutUsage(options.config) ? [
13922
+ createCodexRolloutUsageEnricher(
13923
+ options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
13924
+ )
13925
+ ] : []
13926
+ ],
13199
13927
  ...(() => {
13200
13928
  if (options.sessionContextReader === null) {
13201
13929
  return {};
@@ -14442,7 +15170,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
14442
15170
  );
14443
15171
 
14444
15172
  // src/install/scopes.ts
14445
- import * as path7 from "path";
15173
+ import * as path9 from "path";
14446
15174
  var REGISTRATION_SCOPES = Object.freeze([
14447
15175
  "global",
14448
15176
  "project"
@@ -14510,15 +15238,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
14510
15238
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
14511
15239
  (entry) => entry.providerId === providerId && entry.scope === scope
14512
15240
  );
14513
- var resolveInstallPath = (location, roots) => path7.resolve(
15241
+ var resolveInstallPath = (location, roots) => path9.resolve(
14514
15242
  location.scope === "global" ? roots.homeDir : roots.projectDir,
14515
15243
  ...location.segments
14516
15244
  );
14517
15245
 
14518
15246
  // src/install/document.ts
14519
- 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";
14521
- import * as path8 from "path";
15247
+ import { randomBytes as randomBytes5 } from "crypto";
15248
+ import { chmod, mkdir as mkdir4, open as open7, readFile as readFile4, rename as rename4, stat as stat6, unlink as unlink4 } from "fs/promises";
15249
+ import * as path10 from "path";
14522
15250
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14523
15251
  indent: " ",
14524
15252
  eol: "\n",
@@ -14542,7 +15270,7 @@ var renderJsonDocument = (value, format) => {
14542
15270
  var readJsonDocument = async (filePath) => {
14543
15271
  let raw;
14544
15272
  try {
14545
- raw = await readFile3(filePath, "utf8");
15273
+ raw = await readFile4(filePath, "utf8");
14546
15274
  } catch (thrown) {
14547
15275
  if (isErrnoException3(thrown, "ENOENT")) {
14548
15276
  return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
@@ -14574,7 +15302,7 @@ var delay2 = (millis) => new Promise((resolve5) => {
14574
15302
  var renameWithRetry = async (from, to) => {
14575
15303
  for (let attempt = 0; ; attempt += 1) {
14576
15304
  try {
14577
- await rename3(from, to);
15305
+ await rename4(from, to);
14578
15306
  return;
14579
15307
  } catch (thrown) {
14580
15308
  const retryable = isErrnoException3(thrown, "EPERM", "EACCES", "EBUSY");
@@ -14589,15 +15317,15 @@ var renameWithRetry = async (from, to) => {
14589
15317
  var NEW_DOCUMENT_MODE = 384;
14590
15318
  var TEMPORARY_DOCUMENT_MODE = 384;
14591
15319
  var writeDocumentAtomically = async (filePath, contents) => {
14592
- const directory = path8.dirname(filePath);
14593
- await mkdir3(directory, { recursive: true });
14594
- const temporary = path8.join(
15320
+ const directory = path10.dirname(filePath);
15321
+ await mkdir4(directory, { recursive: true });
15322
+ const temporary = path10.join(
14595
15323
  directory,
14596
- `.${path8.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
15324
+ `.${path10.basename(filePath)}.${randomBytes5(6).toString("hex")}.tmp`
14597
15325
  );
14598
15326
  let existingMode;
14599
15327
  try {
14600
- existingMode = (await stat4(filePath)).mode & 4095;
15328
+ existingMode = (await stat6(filePath)).mode & 4095;
14601
15329
  } catch (thrown) {
14602
15330
  if (!isErrnoException3(thrown, "ENOENT")) {
14603
15331
  throw thrown;
@@ -14605,7 +15333,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14605
15333
  }
14606
15334
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
14607
15335
  try {
14608
- const handle = await open5(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
15336
+ const handle = await open7(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14609
15337
  try {
14610
15338
  await handle.writeFile(contents, "utf8");
14611
15339
  await handle.sync();
@@ -14615,19 +15343,19 @@ var writeDocumentAtomically = async (filePath, contents) => {
14615
15343
  }
14616
15344
  await renameWithRetry(temporary, filePath);
14617
15345
  } catch (thrown) {
14618
- await unlink3(temporary).catch(() => void 0);
15346
+ await unlink4(temporary).catch(() => void 0);
14619
15347
  throw thrown;
14620
15348
  }
14621
15349
  };
14622
15350
 
14623
15351
  // src/install/file-lock.ts
14624
- 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";
14626
- import * as path9 from "path";
15352
+ import { randomBytes as randomBytes6 } from "crypto";
15353
+ import { mkdir as mkdir5, open as open8, readFile as readFile5, rename as rename5, stat as stat7, unlink as unlink5 } from "fs/promises";
15354
+ import * as path11 from "path";
14627
15355
  var FileLockTimeoutError = class extends Error {
14628
15356
  constructor(lockPath, timeoutMillis) {
14629
15357
  super(
14630
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path9.basename(lockPath)}`
15358
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path11.basename(lockPath)}`
14631
15359
  );
14632
15360
  this.name = "FileLockTimeoutError";
14633
15361
  }
@@ -14638,7 +15366,7 @@ var isErrnoException4 = (thrown, code) => thrown instanceof Error && thrown.code
14638
15366
  var readLockContents = async (lockPath) => {
14639
15367
  let raw;
14640
15368
  try {
14641
- raw = await readFile4(lockPath, "utf8");
15369
+ raw = await readFile5(lockPath, "utf8");
14642
15370
  } catch {
14643
15371
  return void 0;
14644
15372
  }
@@ -14652,18 +15380,18 @@ var readLockContents = async (lockPath) => {
14652
15380
  var releaseIfOwned = async (lockPath, token) => {
14653
15381
  const tombstone = `${lockPath}.${token}.releasing`;
14654
15382
  try {
14655
- await rename4(lockPath, tombstone);
15383
+ await rename5(lockPath, tombstone);
14656
15384
  } catch {
14657
15385
  return false;
14658
15386
  }
14659
15387
  const captured = await readLockContents(tombstone);
14660
15388
  if (captured !== void 0 && captured.token !== token) {
14661
- await rename4(tombstone, lockPath).catch(async () => {
15389
+ await rename5(tombstone, lockPath).catch(async () => {
14662
15390
  await Promise.resolve();
14663
15391
  });
14664
15392
  return false;
14665
15393
  }
14666
- await unlink4(tombstone).catch(() => void 0);
15394
+ await unlink5(tombstone).catch(() => void 0);
14667
15395
  return true;
14668
15396
  };
14669
15397
  var delay3 = (millis) => new Promise((resolve5) => {
@@ -14672,7 +15400,7 @@ var delay3 = (millis) => new Promise((resolve5) => {
14672
15400
  var isStale = async (lockPath, clock, staleMillis) => {
14673
15401
  let raw;
14674
15402
  try {
14675
- raw = await readFile4(lockPath, "utf8");
15403
+ raw = await readFile5(lockPath, "utf8");
14676
15404
  } catch (thrown) {
14677
15405
  return { stale: !isErrnoException4(thrown, "ENOENT") };
14678
15406
  }
@@ -14687,7 +15415,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
14687
15415
  } catch {
14688
15416
  }
14689
15417
  try {
14690
- const stats = await stat5(lockPath);
15418
+ const stats = await stat7(lockPath);
14691
15419
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
14692
15420
  } catch (thrown) {
14693
15421
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -14699,12 +15427,12 @@ var withFileLock = async (filePath, options, fn) => {
14699
15427
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
14700
15428
  const lockPath = lockPathFor(filePath);
14701
15429
  const startedAt = options.clock.monotonicMillis();
14702
- await mkdir4(path9.dirname(filePath), { recursive: true });
15430
+ await mkdir5(path11.dirname(filePath), { recursive: true });
14703
15431
  for (; ; ) {
14704
- const token = randomBytes5(16).toString("hex");
15432
+ const token = randomBytes6(16).toString("hex");
14705
15433
  let acquired = false;
14706
15434
  try {
14707
- const handle = await open6(lockPath, "wx", 384);
15435
+ const handle = await open8(lockPath, "wx", 384);
14708
15436
  try {
14709
15437
  const contents = {
14710
15438
  token,
@@ -14746,8 +15474,8 @@ var withFileLock = async (filePath, options, fn) => {
14746
15474
  };
14747
15475
 
14748
15476
  // src/install/lifecycle.ts
14749
- import { readFile as readFile5 } from "fs/promises";
14750
- import * as path10 from "path";
15477
+ import { readFile as readFile6 } from "fs/promises";
15478
+ import * as path12 from "path";
14751
15479
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
14752
15480
  var unsupportedOutcome = (providerId, scope, reason) => ({
14753
15481
  providerId,
@@ -14764,7 +15492,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
14764
15492
  var resolveTarget = (providerId, scope, request) => {
14765
15493
  if (request.configFile !== void 0) {
14766
15494
  return {
14767
- configPath: path10.resolve(request.configFile),
15495
+ configPath: path12.resolve(request.configFile),
14768
15496
  evidence: "path supplied by the caller with --settings-file"
14769
15497
  };
14770
15498
  }
@@ -14781,14 +15509,14 @@ var resolveTarget = (providerId, scope, request) => {
14781
15509
  };
14782
15510
  };
14783
15511
  var codexFeatureNote = async (configPath) => {
14784
- const tomlPath = path10.join(path10.dirname(configPath), "config.toml");
15512
+ const tomlPath = path12.join(path12.dirname(configPath), "config.toml");
14785
15513
  let raw;
14786
15514
  try {
14787
- raw = await readFile5(tomlPath, "utf8");
15515
+ raw = await readFile6(tomlPath, "utf8");
14788
15516
  } catch {
14789
15517
  return void 0;
14790
15518
  }
14791
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path10.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
15519
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path12.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14792
15520
  };
14793
15521
  var readState = async (configPath) => {
14794
15522
  const read = await readJsonDocument(configPath);
@@ -14800,12 +15528,12 @@ var readState = async (configPath) => {
14800
15528
  case "unparseable":
14801
15529
  return {
14802
15530
  status: "blocked",
14803
- problem: `${path10.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
15531
+ problem: `${path12.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14804
15532
  };
14805
15533
  case "unreadable":
14806
15534
  return {
14807
15535
  status: "failed",
14808
- problem: `${path10.basename(configPath)} could not be read (${read.detail})`
15536
+ problem: `${path12.basename(configPath)} could not be read (${read.detail})`
14809
15537
  };
14810
15538
  }
14811
15539
  };
@@ -14917,7 +15645,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14917
15645
  missingEvents: [],
14918
15646
  notes,
14919
15647
  problems: planned.conflicts.map(
14920
- (conflict) => `${path10.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
15648
+ (conflict) => `${path12.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
14921
15649
  )
14922
15650
  };
14923
15651
  }
@@ -14928,7 +15656,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14928
15656
  changed: false,
14929
15657
  registeredEvents: [],
14930
15658
  missingEvents: [],
14931
- notes: [...notes, `${path10.basename(configPath)} does not exist; nothing to remove`],
15659
+ notes: [...notes, `${path12.basename(configPath)} does not exist; nothing to remove`],
14932
15660
  problems: []
14933
15661
  };
14934
15662
  }
@@ -14971,7 +15699,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14971
15699
  missingEvents: [],
14972
15700
  notes,
14973
15701
  problems: [
14974
- `could not write ${path10.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
15702
+ `could not write ${path12.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
14975
15703
  ]
14976
15704
  };
14977
15705
  }
@@ -14998,7 +15726,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14998
15726
  missingEvents: [],
14999
15727
  notes,
15000
15728
  problems: [
15001
- thrown instanceof Error ? `${path10.basename(configPath)}: ${thrown.message}` : `${path10.basename(configPath)}: the configuration file could not be locked`
15729
+ thrown instanceof Error ? `${path12.basename(configPath)}: ${thrown.message}` : `${path12.basename(configPath)}: the configuration file could not be locked`
15002
15730
  ]
15003
15731
  };
15004
15732
  }
@@ -15099,6 +15827,7 @@ export {
15099
15827
  CODEX_HOOK_EVENT_NAMES,
15100
15828
  CODEX_PROVIDER_ID,
15101
15829
  CODEX_REGISTRABLE_HOOK_EVENTS,
15830
+ CODEX_ROLLOUT_USAGE_ENRICHER_ID,
15102
15831
  CODEX_UNREGISTERED_HOOK_EVENTS,
15103
15832
  CONFIG_SOURCE_PRECEDENCE,
15104
15833
  CONTENT_HASH_PATTERN,
@@ -15117,13 +15846,19 @@ export {
15117
15846
  DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
15118
15847
  DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
15119
15848
  DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
15849
+ DEFAULT_CODEX_ROLLOUT_RANGE_BYTES,
15850
+ DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS,
15851
+ DEFAULT_CODEX_ROLLOUT_TAIL_BYTES,
15852
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
15120
15853
  DEFAULT_CONFIG,
15121
15854
  DEFAULT_DESTINATION_NAME,
15122
15855
  DEFAULT_DESTINATION_SIGNALS,
15123
15856
  DEFAULT_DETECTION_POLICY,
15124
15857
  DEFAULT_DIAGNOSTICS_POLICY,
15125
15858
  DEFAULT_DOCUMENT_FORMAT,
15859
+ DEFAULT_ENDPOINT_DOWN_MILLIS,
15126
15860
  DEFAULT_EXPORTER_POLICY,
15861
+ DEFAULT_EXPORT_BUDGET_MILLIS,
15127
15862
  DEFAULT_GEMINI_CAPABILITIES,
15128
15863
  DEFAULT_INSTRUMENTATION_SCOPE,
15129
15864
  DEFAULT_LOGS_POLICY,
@@ -15260,6 +15995,7 @@ export {
15260
15995
  createClaudeCodeAdapter,
15261
15996
  createClaudeTranscriptUsageEnricher,
15262
15997
  createCodexAdapter,
15998
+ createCodexRolloutUsageEnricher,
15263
15999
  createCursorAdapter,
15264
16000
  createDefaultProviderRegistry,
15265
16001
  createDestinationFanout,
@@ -15318,6 +16054,7 @@ export {
15318
16054
  detectionPolicySchema,
15319
16055
  diagnosticsPolicySchema,
15320
16056
  durationMillisSchema,
16057
+ effectiveExportTimeoutMillis,
15321
16058
  effectiveMetricsPolicy,
15322
16059
  effectiveSpoolPolicy,
15323
16060
  emptyExtensions,
@@ -15416,6 +16153,7 @@ export {
15416
16153
  readClaudeTranscriptTurn,
15417
16154
  readCodexHookRegistrations,
15418
16155
  readCodexHooksFeatureFlag,
16156
+ readCodexRolloutUsage,
15419
16157
  readCursorHookRegistrations,
15420
16158
  readDeliveryClaim,
15421
16159
  readDeliveryGap,
@@ -15423,6 +16161,7 @@ export {
15423
16161
  readJsonDocument,
15424
16162
  readNestedHookRegistrations,
15425
16163
  readsClaudeTranscriptUsage,
16164
+ readsCodexRolloutUsage,
15426
16165
  removeAntigravityHookRegistration,
15427
16166
  removeClaudeHookRegistration,
15428
16167
  removeCodexHookRegistration,