@osfactory/otel-hook 0.13.1 → 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.
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 },
@@ -5434,6 +5464,7 @@ var permissionModeSchema = z19.enum([
5434
5464
  var codexUsageSchema = z19.object({
5435
5465
  input_tokens: z19.number().int().min(0).optional(),
5436
5466
  cached_input_tokens: z19.number().int().min(0).optional(),
5467
+ cache_write_input_tokens: z19.number().int().min(0).optional(),
5437
5468
  output_tokens: z19.number().int().min(0).optional(),
5438
5469
  reasoning_output_tokens: z19.number().int().min(0).optional(),
5439
5470
  total_tokens: z19.number().int().min(0).optional()
@@ -5689,6 +5720,10 @@ var codexUsageToReport = (usage, temporality) => ({
5689
5720
  temporality,
5690
5721
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
5691
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
+ },
5692
5727
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
5693
5728
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
5694
5729
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -5717,8 +5752,9 @@ var CODEX_CAPABILITIES = Object.freeze({
5717
5752
  // turn; see docs/usage-semantics.md.
5718
5753
  cumulativeUsageSeries: "session-lifetime",
5719
5754
  reportsCachedInput: true,
5720
- reportsCacheCreation: false,
5721
- 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",
5722
5758
  reportsReasoningOutput: true,
5723
5759
  reportsProviderTotal: true,
5724
5760
  reportsCost: false,
@@ -6077,6 +6113,291 @@ var createCodexAdapter = () => ({
6077
6113
  hookResponse
6078
6114
  });
6079
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
+
6080
6401
  // src/providers/gemini/delivery.ts
6081
6402
  var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
6082
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",
@@ -7208,9 +7529,9 @@ var createFixedClock = (options = {}) => {
7208
7529
  };
7209
7530
 
7210
7531
  // src/runtime/ids.ts
7211
- import { createHash as createHash3, randomUUID } from "crypto";
7532
+ import { createHash as createHash4, randomUUID } from "crypto";
7212
7533
  var digest = (namespace, parts) => {
7213
- const hash = createHash3("sha256");
7534
+ const hash = createHash4("sha256");
7214
7535
  hash.update(namespace);
7215
7536
  for (const part of parts) {
7216
7537
  hash.update("\0");
@@ -7446,16 +7767,16 @@ var resolveDeliveryIdentity = (input) => {
7446
7767
  import { z as z24 } from "zod";
7447
7768
 
7448
7769
  // src/runtime/target-resolution.ts
7449
- import * as path2 from "path";
7770
+ import * as path3 from "path";
7450
7771
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
7451
7772
  var absolutePathsOf = (hint) => {
7452
- 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;
7453
7774
  const resolved = [];
7454
7775
  for (const candidate of hint.paths) {
7455
- if (path2.isAbsolute(candidate)) {
7456
- resolved.push(path2.resolve(candidate));
7776
+ if (path3.isAbsolute(candidate)) {
7777
+ resolved.push(path3.resolve(candidate));
7457
7778
  } else if (base !== void 0) {
7458
- resolved.push(path2.resolve(base, candidate));
7779
+ resolved.push(path3.resolve(base, candidate));
7459
7780
  } else {
7460
7781
  return void 0;
7461
7782
  }
@@ -7613,8 +7934,8 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7613
7934
  };
7614
7935
 
7615
7936
  // src/runtime/session-context.ts
7616
- import { open as open2 } from "fs/promises";
7617
- import * as path3 from "path";
7937
+ import { open as open3 } from "fs/promises";
7938
+ import * as path4 from "path";
7618
7939
  import { z as z23 } from "zod";
7619
7940
  var SESSION_CONTEXT_FILE_VERSION = 1;
7620
7941
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
@@ -7632,10 +7953,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
7632
7953
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
7633
7954
  var sessionContextFilePath = (dir, providerId, sessionId) => {
7634
7955
  const tool = sessionContextAgentTool(providerId);
7635
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
7956
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path4.isAbsolute(dir)) {
7636
7957
  return void 0;
7637
7958
  }
7638
- return path3.join(dir, tool, `${sessionId}.json`);
7959
+ return path4.join(dir, tool, `${sessionId}.json`);
7639
7960
  };
7640
7961
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
7641
7962
  "session.id",
@@ -7731,7 +8052,7 @@ var stampSessionContext = (events, segments) => events.map((event3) => {
7731
8052
  var readBounded = async (file, maxBytes) => {
7732
8053
  let handle;
7733
8054
  try {
7734
- handle = await open2(file, "r");
8055
+ handle = await open3(file, "r");
7735
8056
  } catch {
7736
8057
  return void 0;
7737
8058
  }
@@ -8684,8 +9005,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8684
9005
  };
8685
9006
 
8686
9007
  // src/runtime/git-worktree.ts
8687
- import { lstat, open as open3, stat as stat2 } from "fs/promises";
8688
- import * as path4 from "path";
9008
+ import { lstat, open as open4, stat as stat3 } from "fs/promises";
9009
+ import * as path5 from "path";
8689
9010
  var MAX_WORKTREE_WALK_DEPTH = 128;
8690
9011
  var MAX_GIT_FILE_BYTES = 4096;
8691
9012
  var MAX_CACHE_ENTRIES = 1024;
@@ -8696,7 +9017,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
8696
9017
  var readBounded2 = async (filePath) => {
8697
9018
  let handle;
8698
9019
  try {
8699
- handle = await open3(filePath, "r");
9020
+ handle = await open4(filePath, "r");
8700
9021
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
8701
9022
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
8702
9023
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -8717,7 +9038,7 @@ var parseHeadBranch = (head) => {
8717
9038
  return branch;
8718
9039
  };
8719
9040
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
8720
- 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);
8721
9042
  var parseGitDirFile = (content, worktreeRoot) => {
8722
9043
  const line = firstLine(content);
8723
9044
  return resolveGitPath(
@@ -8737,26 +9058,26 @@ var isMissing = async (filePath) => {
8737
9058
  };
8738
9059
  var isDirectory = async (directory) => {
8739
9060
  try {
8740
- return (await stat2(directory)).isDirectory();
9061
+ return (await stat3(directory)).isDirectory();
8741
9062
  } catch {
8742
9063
  return false;
8743
9064
  }
8744
9065
  };
8745
9066
  var repositoryOf = async (worktreeRoot, gitDir) => {
8746
- const commonDirFile = path4.join(gitDir, "commondir");
9067
+ const commonDirFile = path5.join(gitDir, "commondir");
8747
9068
  const content = await readBounded2(commonDirFile);
8748
9069
  if (content === void 0) {
8749
9070
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
8750
9071
  }
8751
9072
  const commonDir = parseCommonDirFile(content, gitDir);
8752
- 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;
8753
9074
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
8754
9075
  };
8755
9076
  var probeDirectory = async (directory) => {
8756
- const dotGit = path4.join(directory, ".git");
9077
+ const dotGit = path5.join(directory, ".git");
8757
9078
  let info;
8758
9079
  try {
8759
- info = await stat2(dotGit);
9080
+ info = await stat3(dotGit);
8760
9081
  } catch {
8761
9082
  return ABSENT;
8762
9083
  }
@@ -8770,7 +9091,7 @@ var probeDirectory = async (directory) => {
8770
9091
  if (gitDir === void 0) {
8771
9092
  return INVALID;
8772
9093
  }
8773
- const head = await readBounded2(path4.join(gitDir, "HEAD"));
9094
+ const head = await readBounded2(path5.join(gitDir, "HEAD"));
8774
9095
  if (head === void 0) {
8775
9096
  return INVALID;
8776
9097
  }
@@ -8800,10 +9121,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8800
9121
  };
8801
9122
  const locate = async (absolutePath) => {
8802
9123
  try {
8803
- if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
9124
+ if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8804
9125
  return void 0;
8805
9126
  }
8806
- let directory = path4.resolve(absolutePath);
9127
+ let directory = path5.resolve(absolutePath);
8807
9128
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
8808
9129
  const probe = await cachedProbe(directory);
8809
9130
  if (probe.kind === "worktree") {
@@ -8812,7 +9133,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8812
9133
  if (probe.kind === "invalid") {
8813
9134
  return void 0;
8814
9135
  }
8815
- const parent = path4.dirname(directory);
9136
+ const parent = path5.dirname(directory);
8816
9137
  if (parent === directory) {
8817
9138
  return void 0;
8818
9139
  }
@@ -9024,7 +9345,7 @@ var createCallbackDeduplicator = (deps) => {
9024
9345
  };
9025
9346
 
9026
9347
  // src/telemetry/semconv.ts
9027
- import { createHash as createHash4 } from "crypto";
9348
+ import { createHash as createHash5 } from "crypto";
9028
9349
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
9029
9350
  import { millisToHrTime } from "@opentelemetry/core";
9030
9351
  import {
@@ -9043,7 +9364,7 @@ import {
9043
9364
  } from "@opentelemetry/semantic-conventions/incubating";
9044
9365
 
9045
9366
  // src/version.ts
9046
- var VERSION = "0.13.1";
9367
+ var VERSION = "0.13.2";
9047
9368
 
9048
9369
  // src/telemetry/export-identity.ts
9049
9370
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9154,7 +9475,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
9154
9475
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
9155
9476
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
9156
9477
  var FIELD_SEPARATOR = "\0";
9157
- 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);
9158
9479
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
9159
9480
  var familyOf = (type) => {
9160
9481
  switch (type) {
@@ -9767,7 +10088,7 @@ var decodeRecord = (attributes) => {
9767
10088
  }
9768
10089
  };
9769
10090
  };
9770
- var factsOf = (record) => ({
10091
+ var factsOf2 = (record) => ({
9771
10092
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
9772
10093
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9773
10094
  ...record.parent === void 0 ? {} : { parent: record.parent },
@@ -9825,7 +10146,7 @@ var createSpanCorrelator = (deps) => {
9825
10146
  return { status: "conflict", reason: "provider-mismatch" };
9826
10147
  }
9827
10148
  if (existing.startEventId === input.eventId) {
9828
- return { status: "duplicate", facts: factsOf(existing) };
10149
+ return { status: "duplicate", facts: factsOf2(existing) };
9829
10150
  }
9830
10151
  if (existing.startEventId === void 0 && existing.endEventId !== void 0) {
9831
10152
  const completed = {
@@ -9836,7 +10157,7 @@ var createSpanCorrelator = (deps) => {
9836
10157
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9837
10158
  };
9838
10159
  await stateStore.write(key, encodeRecord(completed));
9839
- 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) };
9840
10161
  }
9841
10162
  }
9842
10163
  const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
@@ -9849,7 +10170,7 @@ var createSpanCorrelator = (deps) => {
9849
10170
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9850
10171
  };
9851
10172
  await stateStore.write(key, encodeRecord(fresh));
9852
- return { status: "recorded", facts: factsOf(fresh) };
10173
+ return { status: "recorded", facts: factsOf2(fresh) };
9853
10174
  });
9854
10175
  const recordEnd = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
9855
10176
  const key = keyFor(input);
@@ -9868,7 +10189,7 @@ var createSpanCorrelator = (deps) => {
9868
10189
  exported: true
9869
10190
  };
9870
10191
  await stateStore.write(key, encodeRecord(endOnly));
9871
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(endOnly) };
10192
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf2(endOnly) };
9872
10193
  }
9873
10194
  const existing = decoded.record;
9874
10195
  if (existing.providerId !== input.providerId) {
@@ -9879,7 +10200,7 @@ var createSpanCorrelator = (deps) => {
9879
10200
  };
9880
10201
  }
9881
10202
  if (existing.endEventId === input.eventId) {
9882
- return { status: "duplicate", facts: factsOf(existing) };
10203
+ return { status: "duplicate", facts: factsOf2(existing) };
9883
10204
  }
9884
10205
  if (existing.endEventId !== void 0) {
9885
10206
  return {
@@ -9896,7 +10217,7 @@ var createSpanCorrelator = (deps) => {
9896
10217
  exported: true
9897
10218
  };
9898
10219
  await stateStore.write(key, encodeRecord(replaced));
9899
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(replaced) };
10220
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf2(replaced) };
9900
10221
  }
9901
10222
  if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {
9902
10223
  await stateStore.delete(key);
@@ -9913,7 +10234,7 @@ var createSpanCorrelator = (deps) => {
9913
10234
  status: "matched",
9914
10235
  startedAt: existing.startedAt,
9915
10236
  durationMillis: Math.max(0, input.occurredAt - existing.startedAt),
9916
- facts: factsOf(closed)
10237
+ facts: factsOf2(closed)
9917
10238
  };
9918
10239
  });
9919
10240
  const correlateGroup = async (group) => {
@@ -10182,7 +10503,7 @@ var createUsageAccumulator = (deps) => {
10182
10503
  };
10183
10504
 
10184
10505
  // src/lifecycle/metric-series.ts
10185
- import { createHash as createHash5 } from "crypto";
10506
+ import { createHash as createHash6 } from "crypto";
10186
10507
 
10187
10508
  // src/telemetry/metric-model.ts
10188
10509
  var TOKEN_USAGE_BUCKETS = Object.freeze([
@@ -10465,7 +10786,7 @@ var TURN_START_SEGMENT = "turn-start";
10465
10786
  var SHARED_SCOPE = "all";
10466
10787
  var SHARED_LOCK = "otelhook.metrics.shared";
10467
10788
  var sessionScope = (sessionId) => `s=${sessionId}`;
10468
- 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);
10469
10790
  var toStoredHistogram = (histogram) => ({
10470
10791
  count: histogram.count,
10471
10792
  sum: histogram.sum,
@@ -10707,28 +11028,28 @@ var createBoundedMemoryStateStore = (options) => {
10707
11028
 
10708
11029
  // src/state/filesystem-store.ts
10709
11030
  import { randomBytes as randomBytes2 } from "crypto";
10710
- import { mkdir, open as open4, readFile, readdir, rename, stat as stat3, unlink, writeFile } from "fs/promises";
10711
- 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";
10712
11033
 
10713
11034
  // src/state/keys.ts
10714
- import { createHash as createHash6 } from "crypto";
11035
+ import { createHash as createHash7 } from "crypto";
10715
11036
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
10716
11037
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
10717
11038
  var sanitizeSegment = (segment) => {
10718
11039
  if (isSafeSegment(segment)) {
10719
11040
  return segment;
10720
11041
  }
10721
- 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)}`;
10722
11043
  };
10723
11044
  var namespaceSegments = (namespace) => [
10724
11045
  sanitizeSegment(namespace.providerId),
10725
11046
  sanitizeSegment(namespace.installationId)
10726
11047
  ];
10727
- var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
11048
+ var keyDigest = (key) => createHash7("sha256").update(key, "utf8").digest("hex");
10728
11049
 
10729
11050
  // src/state/filesystem-store.ts
10730
11051
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
10731
- var sleep = (millis) => new Promise((resolve5) => {
11052
+ var sleep2 = (millis) => new Promise((resolve5) => {
10732
11053
  setTimeout(resolve5, millis);
10733
11054
  });
10734
11055
  var wrapFsError = (thrown, operation) => {
@@ -10739,10 +11060,10 @@ var wrapFsError = (thrown, operation) => {
10739
11060
  };
10740
11061
  var createFilesystemStateStore = (options) => {
10741
11062
  const [providerSegment, installationSegment] = namespaceSegments(options);
10742
- const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
10743
- const recordsDir = path5.join(baseDir, "records");
10744
- const quarantineDir = path5.join(baseDir, "quarantine");
10745
- 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");
10746
11067
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
10747
11068
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
10748
11069
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -10766,11 +11087,11 @@ var createFilesystemStateStore = (options) => {
10766
11087
  throw wrapFsError(thrown, "ensure-dirs");
10767
11088
  }
10768
11089
  };
10769
- const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
10770
- const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10771
- 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`);
10772
11093
  const quarantine = async (filePath, key, reason) => {
10773
- 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`);
10774
11095
  try {
10775
11096
  await rename(filePath, dest);
10776
11097
  } catch {
@@ -10834,7 +11155,7 @@ var createFilesystemStateStore = (options) => {
10834
11155
  const startedAt = options.clock.monotonicMillis();
10835
11156
  for (; ; ) {
10836
11157
  try {
10837
- const handle = await open4(filePath, "wx");
11158
+ const handle = await open5(filePath, "wx");
10838
11159
  try {
10839
11160
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
10840
11161
  } finally {
@@ -10863,7 +11184,7 @@ var createFilesystemStateStore = (options) => {
10863
11184
  } catch {
10864
11185
  }
10865
11186
  try {
10866
- const stats = await stat3(filePath);
11187
+ const stats = await stat4(filePath);
10867
11188
  return Date.now() - stats.mtimeMs > lockStaleMillis;
10868
11189
  } catch {
10869
11190
  return "gone";
@@ -10879,7 +11200,7 @@ var createFilesystemStateStore = (options) => {
10879
11200
  if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
10880
11201
  throw new StateLockTimeoutError(sessionId, timeoutMillis);
10881
11202
  }
10882
- await sleep(lockPollIntervalMillis);
11203
+ await sleep2(lockPollIntervalMillis);
10883
11204
  }
10884
11205
  };
10885
11206
  return {
@@ -10903,7 +11224,7 @@ var createFilesystemStateStore = (options) => {
10903
11224
  await ensureDirs();
10904
11225
  let entries;
10905
11226
  try {
10906
- entries = await readdir(recordsDir);
11227
+ entries = await readdir2(recordsDir);
10907
11228
  } catch (thrown) {
10908
11229
  if (isErrnoException(thrown, "ENOENT")) {
10909
11230
  return [];
@@ -10917,7 +11238,7 @@ var createFilesystemStateStore = (options) => {
10917
11238
  }
10918
11239
  let raw;
10919
11240
  try {
10920
- raw = await readFile(path5.join(recordsDir, entry), "utf8");
11241
+ raw = await readFile(path6.join(recordsDir, entry), "utf8");
10921
11242
  } catch {
10922
11243
  continue;
10923
11244
  }
@@ -10955,7 +11276,7 @@ var createFilesystemStateStore = (options) => {
10955
11276
  let scanned = 0;
10956
11277
  let entries;
10957
11278
  try {
10958
- entries = await readdir(recordsDir);
11279
+ entries = await readdir2(recordsDir);
10959
11280
  } catch (thrown) {
10960
11281
  if (!isErrnoException(thrown, "ENOENT")) {
10961
11282
  throw wrapFsError(thrown, "prune");
@@ -10970,7 +11291,7 @@ var createFilesystemStateStore = (options) => {
10970
11291
  continue;
10971
11292
  }
10972
11293
  scanned += 1;
10973
- const filePath = path5.join(recordsDir, entry);
11294
+ const filePath = path6.join(recordsDir, entry);
10974
11295
  try {
10975
11296
  const raw = await readFile(filePath, "utf8");
10976
11297
  const envelope = JSON.parse(raw);
@@ -10985,12 +11306,12 @@ var createFilesystemStateStore = (options) => {
10985
11306
  }
10986
11307
  let lockEntries;
10987
11308
  try {
10988
- lockEntries = await readdir(locksDir);
11309
+ lockEntries = await readdir2(locksDir);
10989
11310
  } catch {
10990
11311
  lockEntries = [];
10991
11312
  }
10992
11313
  for (const entry of lockEntries) {
10993
- const filePath = path5.join(locksDir, entry);
11314
+ const filePath = path6.join(locksDir, entry);
10994
11315
  try {
10995
11316
  const raw = await readFile(filePath, "utf8");
10996
11317
  const parsed = JSON.parse(raw);
@@ -11008,8 +11329,8 @@ var createFilesystemStateStore = (options) => {
11008
11329
 
11009
11330
  // src/telemetry/spool-queue.ts
11010
11331
  import { randomBytes as randomBytes3 } from "crypto";
11011
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
11012
- 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";
11013
11334
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
11014
11335
  total: 0,
11015
11336
  age: 0,
@@ -11025,7 +11346,7 @@ var enqueuedAtOf = (fileName) => {
11025
11346
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
11026
11347
  var readSpoolDropCounts = async (queueDir) => {
11027
11348
  try {
11028
- 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"));
11029
11350
  if (typeof parsed !== "object" || parsed === null) {
11030
11351
  return EMPTY_SPOOL_DROP_COUNTS;
11031
11352
  }
@@ -11046,7 +11367,7 @@ var readSpoolDropCounts = async (queueDir) => {
11046
11367
  var readSpoolQueueStats = async (queueDir) => {
11047
11368
  let entries;
11048
11369
  try {
11049
- entries = await readdir2(queueDir);
11370
+ entries = await readdir3(queueDir);
11050
11371
  } catch {
11051
11372
  return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
11052
11373
  }
@@ -11054,7 +11375,7 @@ var readSpoolQueueStats = async (queueDir) => {
11054
11375
  let bytes = 0;
11055
11376
  for (const file of files) {
11056
11377
  try {
11057
- bytes += (await stat4(path6.join(queueDir, file))).size;
11378
+ bytes += (await stat5(path7.join(queueDir, file))).size;
11058
11379
  } catch {
11059
11380
  }
11060
11381
  }
@@ -11068,7 +11389,8 @@ var readSpoolQueueStats = async (queueDir) => {
11068
11389
  };
11069
11390
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
11070
11391
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
11071
- var CLAIM_MARKER = ".claimed-";
11392
+ var CLAIM_SUFFIX = ".claim";
11393
+ var RELEASING_SUFFIX = ".releasing";
11072
11394
  var isClaimOwnerAlive = (pid) => {
11073
11395
  if (!Number.isSafeInteger(pid) || pid <= 0) {
11074
11396
  return true;
@@ -11084,10 +11406,38 @@ var isClaimOwnerAlive = (pid) => {
11084
11406
  }
11085
11407
  };
11086
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
+ };
11087
11437
  var createSpoolQueue = (options) => {
11088
11438
  const [providerSegment, installationSegment] = namespaceSegments(options);
11089
- const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11090
- const corruptDir = path6.join(
11439
+ const queueDir = path7.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11440
+ const corruptDir = path7.join(
11091
11441
  options.rootDir,
11092
11442
  providerSegment,
11093
11443
  installationSegment,
@@ -11113,7 +11463,7 @@ var createSpoolQueue = (options) => {
11113
11463
  const listSorted = async () => {
11114
11464
  let entries;
11115
11465
  try {
11116
- entries = await readdir2(queueDir);
11466
+ entries = await readdir3(queueDir);
11117
11467
  } catch (thrown) {
11118
11468
  if (isErrnoException2(thrown, "ENOENT")) {
11119
11469
  return [];
@@ -11134,9 +11484,9 @@ var createSpoolQueue = (options) => {
11134
11484
  [reason]: current[reason] + dropped,
11135
11485
  lastDroppedAt: options.clock.now()
11136
11486
  };
11137
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11487
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11138
11488
  await writeFile2(tmp, JSON.stringify(next), "utf8");
11139
- await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
11489
+ await rename2(tmp, path7.join(queueDir, SPOOL_DROPS_FILE));
11140
11490
  } catch {
11141
11491
  }
11142
11492
  options.logger?.warn("durable spool dropped batches", {
@@ -11152,7 +11502,7 @@ var createSpoolQueue = (options) => {
11152
11502
  let bytes = 0;
11153
11503
  if (options.maxBytes !== void 0) {
11154
11504
  try {
11155
- bytes = (await stat4(path6.join(queueDir, name))).size;
11505
+ bytes = (await stat5(path7.join(queueDir, name))).size;
11156
11506
  } catch {
11157
11507
  continue;
11158
11508
  }
@@ -11166,7 +11516,7 @@ var createSpoolQueue = (options) => {
11166
11516
  let removed = 0;
11167
11517
  for (const file of files) {
11168
11518
  try {
11169
- await unlink2(path6.join(queueDir, file.name));
11519
+ await unlink2(path7.join(queueDir, file.name));
11170
11520
  removed += 1;
11171
11521
  } catch {
11172
11522
  }
@@ -11226,33 +11576,63 @@ var createSpoolQueue = (options) => {
11226
11576
  }
11227
11577
  }
11228
11578
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
11229
- const target = path6.join(queueDir, fileName);
11230
- 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`);
11231
11581
  await writeFile2(tmp, serialized, "utf8");
11232
11582
  await rename2(tmp, target);
11233
11583
  return { spooled: true };
11234
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
+ };
11235
11598
  const releaseStaleClaims = async () => {
11236
11599
  let entries;
11237
11600
  try {
11238
- entries = await readdir2(queueDir);
11601
+ entries = await readdir3(queueDir);
11239
11602
  } catch {
11240
11603
  return;
11241
11604
  }
11242
11605
  const now = Date.now();
11243
11606
  for (const entry of entries) {
11244
- const marker = entry.lastIndexOf(CLAIM_MARKER);
11245
- if (marker <= 0) {
11246
- continue;
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
+ }
11247
11620
  }
11248
- const claimPath = path6.join(queueDir, entry);
11249
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
11621
+ }
11622
+ };
11623
+ const claimBatch = async (claimPath) => {
11624
+ const token = randomBytes3(16).toString("hex");
11625
+ try {
11626
+ const handle = await open6(claimPath, "wx");
11250
11627
  try {
11251
- if (!isClaimOwnerAlive(owner) || now - (await stat4(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
11252
- await rename2(claimPath, path6.join(queueDir, entry.slice(0, marker)));
11253
- }
11254
- } catch {
11628
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
11629
+ await handle.writeFile(JSON.stringify(contents), "utf8");
11630
+ } finally {
11631
+ await handle.close();
11255
11632
  }
11633
+ return token;
11634
+ } catch {
11635
+ return void 0;
11256
11636
  }
11257
11637
  };
11258
11638
  const drain = async (send, drainOptions) => {
@@ -11276,21 +11656,7 @@ var createSpoolQueue = (options) => {
11276
11656
  let failed = 0;
11277
11657
  let quarantined = 0;
11278
11658
  let index = 0;
11279
- for (; index < files.length && index < cap; index += 1) {
11280
- const fileName = files[index];
11281
- if (fileName === void 0) {
11282
- break;
11283
- }
11284
- const queuedPath = path6.join(queueDir, fileName);
11285
- const filePath = path6.join(
11286
- queueDir,
11287
- `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes3(4).toString("hex")}`
11288
- );
11289
- try {
11290
- await rename2(queuedPath, filePath);
11291
- } catch {
11292
- continue;
11293
- }
11659
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
11294
11660
  const quarantine = async (rejection) => {
11295
11661
  quarantined += 1;
11296
11662
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -11299,7 +11665,7 @@ var createSpoolQueue = (options) => {
11299
11665
  "spool.queue": options.queueName
11300
11666
  });
11301
11667
  try {
11302
- await rename2(filePath, path6.join(corruptDir, fileName));
11668
+ await rename2(filePath, path7.join(corruptDir, fileName));
11303
11669
  } catch {
11304
11670
  await unlink2(filePath).catch(() => void 0);
11305
11671
  }
@@ -11309,17 +11675,17 @@ var createSpoolQueue = (options) => {
11309
11675
  text = await readFile2(filePath, "utf8");
11310
11676
  } catch (thrown) {
11311
11677
  if (thrown?.code === "ENOENT") {
11312
- continue;
11678
+ return "next";
11313
11679
  }
11314
11680
  await quarantine("unreadable");
11315
- continue;
11681
+ return "next";
11316
11682
  }
11317
11683
  let parsed;
11318
11684
  try {
11319
11685
  parsed = JSON.parse(text);
11320
11686
  } catch {
11321
11687
  await quarantine("unparseable-json");
11322
- continue;
11688
+ return "next";
11323
11689
  }
11324
11690
  const validation = options.validate(parsed, {
11325
11691
  providerId: options.providerId,
@@ -11327,7 +11693,10 @@ var createSpoolQueue = (options) => {
11327
11693
  });
11328
11694
  if ("rejection" in validation) {
11329
11695
  await quarantine(validation.rejection);
11330
- continue;
11696
+ return "next";
11697
+ }
11698
+ if ((await readClaim(claimPath))?.token !== token) {
11699
+ return "next";
11331
11700
  }
11332
11701
  let delivered;
11333
11702
  try {
@@ -11339,14 +11708,34 @@ var createSpoolQueue = (options) => {
11339
11708
  if (await unlink2(filePath).then(() => true, () => false)) {
11340
11709
  await recordDrops("rejected", 1);
11341
11710
  }
11342
- continue;
11711
+ return "next";
11343
11712
  }
11344
11713
  if (delivered) {
11345
11714
  await unlink2(filePath).catch(() => void 0);
11346
11715
  drained += 1;
11347
- } else {
11348
- await rename2(filePath, queuedPath).catch(() => void 0);
11349
- 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") {
11350
11739
  break;
11351
11740
  }
11352
11741
  }
@@ -11460,7 +11849,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
11460
11849
  });
11461
11850
 
11462
11851
  // src/telemetry/otlp-sink.ts
11463
- import { ExportResultCode } from "@opentelemetry/core";
11852
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
11464
11853
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
11465
11854
 
11466
11855
  // src/diagnostics/health.ts
@@ -11513,6 +11902,217 @@ var isPermanentExportFailure = (result) => {
11513
11902
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
11514
11903
  };
11515
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
+
11516
12116
  // src/telemetry/exporter-resource.ts
11517
12117
  import { resourceFromAttributes } from "@opentelemetry/resources";
11518
12118
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -11652,12 +12252,16 @@ var createOtlpTraceSink = (options) => {
11652
12252
  const exporter = new OTLPTraceExporter({
11653
12253
  url: options.exporter.endpoint,
11654
12254
  headers: { ...options.headers },
11655
- timeoutMillis: options.exporter.timeoutMillis
12255
+ ...boundedExporterOptions(options.exporter)
11656
12256
  });
12257
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
11657
12258
  let shutdownCompleted = false;
11658
- const exportSpans = (spans) => new Promise((resolve5) => {
11659
- exporter.export([...spans], (result) => resolve5(result));
11660
- });
12259
+ const exportSpans = (spans) => guardExport(
12260
+ gate,
12261
+ () => new Promise((resolve5) => {
12262
+ exporter.export([...spans], (result) => resolve5(result));
12263
+ })
12264
+ );
11661
12265
  const toSpoolBatch = (spans, batchResource) => ({
11662
12266
  providerId: options.providerId,
11663
12267
  installationId: options.installationId,
@@ -11670,7 +12274,7 @@ var createOtlpTraceSink = (options) => {
11670
12274
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
11671
12275
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
11672
12276
  const result = await exportSpans(spans);
11673
- if (result.code === ExportResultCode.SUCCESS) {
12277
+ if (result.code === ExportResultCode2.SUCCESS) {
11674
12278
  return true;
11675
12279
  }
11676
12280
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -11709,9 +12313,9 @@ var createOtlpTraceSink = (options) => {
11709
12313
  try {
11710
12314
  result = await exportSpans(batch);
11711
12315
  } catch (thrown) {
11712
- 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") };
11713
12317
  }
11714
- if (result.code === ExportResultCode.SUCCESS) {
12318
+ if (result.code === ExportResultCode2.SUCCESS) {
11715
12319
  accepted += batch.length;
11716
12320
  health.recordSuccess(batch.length, options.clock.now());
11717
12321
  continue;
@@ -11748,6 +12352,9 @@ var createOtlpTraceSink = (options) => {
11748
12352
  if (options.spool === void 0) {
11749
12353
  return { drained: 0, remaining: 0, failed: 0 };
11750
12354
  }
12355
+ if (gate !== void 0 && !await gate.available()) {
12356
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
12357
+ }
11751
12358
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
11752
12359
  if (result.drained > 0) {
11753
12360
  health.recordSuccess(result.drained, options.clock.now());
@@ -12305,7 +12912,7 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
12305
12912
 
12306
12913
  // src/telemetry/otlp-log-sink.ts
12307
12914
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
12308
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
12915
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
12309
12916
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
12310
12917
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
12311
12918
  var resolveLogsEndpoint = (exporter) => {
@@ -12448,12 +13055,16 @@ var createOtlpLogSink = (options) => {
12448
13055
  const exporter = new OTLPLogExporter({
12449
13056
  url: deliverability.endpoint,
12450
13057
  headers: { ...options.headers },
12451
- timeoutMillis: options.exporter.timeoutMillis
13058
+ ...boundedExporterOptions(options.exporter)
12452
13059
  });
13060
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
12453
13061
  let shutdownCompleted = false;
12454
- const exportRecords = (records) => new Promise((resolve5) => {
12455
- exporter.export([...records], (result) => resolve5(result));
12456
- });
13062
+ const exportRecords = (records) => guardExport(
13063
+ gate,
13064
+ () => new Promise((resolve5) => {
13065
+ exporter.export([...records], (result) => resolve5(result));
13066
+ })
13067
+ );
12457
13068
  const toSpoolBatch = (records, batchResource) => ({
12458
13069
  providerId: options.providerId,
12459
13070
  installationId: options.installationId,
@@ -12471,7 +13082,7 @@ var createOtlpLogSink = (options) => {
12471
13082
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
12472
13083
  );
12473
13084
  const result = await exportRecords(records);
12474
- if (result.code === ExportResultCode2.SUCCESS) {
13085
+ if (result.code === ExportResultCode3.SUCCESS) {
12475
13086
  return true;
12476
13087
  }
12477
13088
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -12517,11 +13128,11 @@ var createOtlpLogSink = (options) => {
12517
13128
  result = await exportRecords(batch);
12518
13129
  } catch (thrown) {
12519
13130
  result = {
12520
- code: ExportResultCode2.FAILED,
13131
+ code: ExportResultCode3.FAILED,
12521
13132
  error: thrown instanceof Error ? thrown : new Error("export threw")
12522
13133
  };
12523
13134
  }
12524
- if (result.code === ExportResultCode2.SUCCESS) {
13135
+ if (result.code === ExportResultCode3.SUCCESS) {
12525
13136
  accepted += batch.length;
12526
13137
  health.recordSuccess(batch.length, options.clock.now());
12527
13138
  continue;
@@ -12562,6 +13173,9 @@ var createOtlpLogSink = (options) => {
12562
13173
  if (options.spool === void 0) {
12563
13174
  return { drained: 0, remaining: 0, failed: 0 };
12564
13175
  }
13176
+ if (gate !== void 0 && !await gate.available()) {
13177
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
13178
+ }
12565
13179
  const result = await options.spool.drain(sendSerializedBatch, {
12566
13180
  ...maxBatches === void 0 ? {} : { maxBatches }
12567
13181
  });
@@ -12720,7 +13334,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
12720
13334
 
12721
13335
  // src/telemetry/otlp-metric-sink.ts
12722
13336
  import { ValueType } from "@opentelemetry/api";
12723
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
13337
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
12724
13338
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
12725
13339
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
12726
13340
  import {
@@ -12864,10 +13478,12 @@ var createOtlpMetricSink = (options) => {
12864
13478
  const exporter = new OTLPMetricExporter({
12865
13479
  url: deliverability.endpoint,
12866
13480
  headers: { ...options.headers },
12867
- timeoutMillis: options.exporter.timeoutMillis
13481
+ ...boundedExporterOptions(options.exporter)
12868
13482
  });
13483
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
12869
13484
  let shutdownCompleted = false;
12870
- 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) => {
12871
13487
  const payload = {
12872
13488
  resource: batchResource,
12873
13489
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -12876,7 +13492,7 @@ var createOtlpMetricSink = (options) => {
12876
13492
  exporter.export(payload, (result) => resolve5(result));
12877
13493
  } catch (thrown) {
12878
13494
  resolve5({
12879
- code: ExportResultCode3.FAILED,
13495
+ code: ExportResultCode4.FAILED,
12880
13496
  error: thrown instanceof Error ? thrown : new Error("export threw")
12881
13497
  });
12882
13498
  }
@@ -12897,7 +13513,7 @@ var createOtlpMetricSink = (options) => {
12897
13513
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
12898
13514
  );
12899
13515
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
12900
- if (result.code === ExportResultCode3.SUCCESS) {
13516
+ if (result.code === ExportResultCode4.SUCCESS) {
12901
13517
  return true;
12902
13518
  }
12903
13519
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -12908,7 +13524,7 @@ var createOtlpMetricSink = (options) => {
12908
13524
  }
12909
13525
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
12910
13526
  const result = await exportResourceMetrics(points, batchResource, scope);
12911
- if (result.code === ExportResultCode3.SUCCESS) {
13527
+ if (result.code === ExportResultCode4.SUCCESS) {
12912
13528
  health.recordSuccess(points.length, options.clock.now());
12913
13529
  return { accepted: points.length, rejected: 0, errors: [] };
12914
13530
  }
@@ -12948,6 +13564,9 @@ var createOtlpMetricSink = (options) => {
12948
13564
  if (options.spool === void 0) {
12949
13565
  return { drained: 0, remaining: 0, failed: 0 };
12950
13566
  }
13567
+ if (gate !== void 0 && !await gate.available()) {
13568
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
13569
+ }
12951
13570
  const result = await options.spool.drain(sendSerializedBatch, {
12952
13571
  ...maxBatches === void 0 ? {} : { maxBatches }
12953
13572
  });
@@ -13043,6 +13662,13 @@ var createExportDestinationSinks = (options) => {
13043
13662
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
13044
13663
  const destinations = [];
13045
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
+ });
13046
13672
  for (const destination of resolveExportDestinations(options.exporter)) {
13047
13673
  let headers;
13048
13674
  let logHeaders;
@@ -13102,6 +13728,7 @@ var createExportDestinationSinks = (options) => {
13102
13728
  const sinkShared = {
13103
13729
  exporter: policy,
13104
13730
  ...shared,
13731
+ endpointHealth,
13105
13732
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
13106
13733
  ...label === void 0 ? {} : { destination: label }
13107
13734
  };
@@ -13119,6 +13746,7 @@ var createExportDestinationSinks = (options) => {
13119
13746
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
13120
13747
  exporter: policy,
13121
13748
  ...shared,
13749
+ endpointHealth,
13122
13750
  ...label === void 0 ? {} : { destination: label },
13123
13751
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
13124
13752
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -13288,7 +13916,14 @@ var createHookRuntime = (options) => {
13288
13916
  privacy,
13289
13917
  logger,
13290
13918
  installationId: options.installationId,
13291
- 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
+ ],
13292
13927
  ...(() => {
13293
13928
  if (options.sessionContextReader === null) {
13294
13929
  return {};
@@ -14535,7 +15170,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
14535
15170
  );
14536
15171
 
14537
15172
  // src/install/scopes.ts
14538
- import * as path7 from "path";
15173
+ import * as path9 from "path";
14539
15174
  var REGISTRATION_SCOPES = Object.freeze([
14540
15175
  "global",
14541
15176
  "project"
@@ -14603,15 +15238,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
14603
15238
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
14604
15239
  (entry) => entry.providerId === providerId && entry.scope === scope
14605
15240
  );
14606
- var resolveInstallPath = (location, roots) => path7.resolve(
15241
+ var resolveInstallPath = (location, roots) => path9.resolve(
14607
15242
  location.scope === "global" ? roots.homeDir : roots.projectDir,
14608
15243
  ...location.segments
14609
15244
  );
14610
15245
 
14611
15246
  // src/install/document.ts
14612
- import { randomBytes as randomBytes4 } from "crypto";
14613
- import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat5, unlink as unlink3 } from "fs/promises";
14614
- 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";
14615
15250
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14616
15251
  indent: " ",
14617
15252
  eol: "\n",
@@ -14635,7 +15270,7 @@ var renderJsonDocument = (value, format) => {
14635
15270
  var readJsonDocument = async (filePath) => {
14636
15271
  let raw;
14637
15272
  try {
14638
- raw = await readFile3(filePath, "utf8");
15273
+ raw = await readFile4(filePath, "utf8");
14639
15274
  } catch (thrown) {
14640
15275
  if (isErrnoException3(thrown, "ENOENT")) {
14641
15276
  return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
@@ -14667,7 +15302,7 @@ var delay2 = (millis) => new Promise((resolve5) => {
14667
15302
  var renameWithRetry = async (from, to) => {
14668
15303
  for (let attempt = 0; ; attempt += 1) {
14669
15304
  try {
14670
- await rename3(from, to);
15305
+ await rename4(from, to);
14671
15306
  return;
14672
15307
  } catch (thrown) {
14673
15308
  const retryable = isErrnoException3(thrown, "EPERM", "EACCES", "EBUSY");
@@ -14682,15 +15317,15 @@ var renameWithRetry = async (from, to) => {
14682
15317
  var NEW_DOCUMENT_MODE = 384;
14683
15318
  var TEMPORARY_DOCUMENT_MODE = 384;
14684
15319
  var writeDocumentAtomically = async (filePath, contents) => {
14685
- const directory = path8.dirname(filePath);
14686
- await mkdir3(directory, { recursive: true });
14687
- const temporary = path8.join(
15320
+ const directory = path10.dirname(filePath);
15321
+ await mkdir4(directory, { recursive: true });
15322
+ const temporary = path10.join(
14688
15323
  directory,
14689
- `.${path8.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
15324
+ `.${path10.basename(filePath)}.${randomBytes5(6).toString("hex")}.tmp`
14690
15325
  );
14691
15326
  let existingMode;
14692
15327
  try {
14693
- existingMode = (await stat5(filePath)).mode & 4095;
15328
+ existingMode = (await stat6(filePath)).mode & 4095;
14694
15329
  } catch (thrown) {
14695
15330
  if (!isErrnoException3(thrown, "ENOENT")) {
14696
15331
  throw thrown;
@@ -14698,7 +15333,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14698
15333
  }
14699
15334
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
14700
15335
  try {
14701
- const handle = await open5(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
15336
+ const handle = await open7(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14702
15337
  try {
14703
15338
  await handle.writeFile(contents, "utf8");
14704
15339
  await handle.sync();
@@ -14708,19 +15343,19 @@ var writeDocumentAtomically = async (filePath, contents) => {
14708
15343
  }
14709
15344
  await renameWithRetry(temporary, filePath);
14710
15345
  } catch (thrown) {
14711
- await unlink3(temporary).catch(() => void 0);
15346
+ await unlink4(temporary).catch(() => void 0);
14712
15347
  throw thrown;
14713
15348
  }
14714
15349
  };
14715
15350
 
14716
15351
  // src/install/file-lock.ts
14717
- import { randomBytes as randomBytes5 } from "crypto";
14718
- import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat6, unlink as unlink4 } from "fs/promises";
14719
- 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";
14720
15355
  var FileLockTimeoutError = class extends Error {
14721
15356
  constructor(lockPath, timeoutMillis) {
14722
15357
  super(
14723
- `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)}`
14724
15359
  );
14725
15360
  this.name = "FileLockTimeoutError";
14726
15361
  }
@@ -14731,7 +15366,7 @@ var isErrnoException4 = (thrown, code) => thrown instanceof Error && thrown.code
14731
15366
  var readLockContents = async (lockPath) => {
14732
15367
  let raw;
14733
15368
  try {
14734
- raw = await readFile4(lockPath, "utf8");
15369
+ raw = await readFile5(lockPath, "utf8");
14735
15370
  } catch {
14736
15371
  return void 0;
14737
15372
  }
@@ -14745,18 +15380,18 @@ var readLockContents = async (lockPath) => {
14745
15380
  var releaseIfOwned = async (lockPath, token) => {
14746
15381
  const tombstone = `${lockPath}.${token}.releasing`;
14747
15382
  try {
14748
- await rename4(lockPath, tombstone);
15383
+ await rename5(lockPath, tombstone);
14749
15384
  } catch {
14750
15385
  return false;
14751
15386
  }
14752
15387
  const captured = await readLockContents(tombstone);
14753
15388
  if (captured !== void 0 && captured.token !== token) {
14754
- await rename4(tombstone, lockPath).catch(async () => {
15389
+ await rename5(tombstone, lockPath).catch(async () => {
14755
15390
  await Promise.resolve();
14756
15391
  });
14757
15392
  return false;
14758
15393
  }
14759
- await unlink4(tombstone).catch(() => void 0);
15394
+ await unlink5(tombstone).catch(() => void 0);
14760
15395
  return true;
14761
15396
  };
14762
15397
  var delay3 = (millis) => new Promise((resolve5) => {
@@ -14765,7 +15400,7 @@ var delay3 = (millis) => new Promise((resolve5) => {
14765
15400
  var isStale = async (lockPath, clock, staleMillis) => {
14766
15401
  let raw;
14767
15402
  try {
14768
- raw = await readFile4(lockPath, "utf8");
15403
+ raw = await readFile5(lockPath, "utf8");
14769
15404
  } catch (thrown) {
14770
15405
  return { stale: !isErrnoException4(thrown, "ENOENT") };
14771
15406
  }
@@ -14780,7 +15415,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
14780
15415
  } catch {
14781
15416
  }
14782
15417
  try {
14783
- const stats = await stat6(lockPath);
15418
+ const stats = await stat7(lockPath);
14784
15419
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
14785
15420
  } catch (thrown) {
14786
15421
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -14792,12 +15427,12 @@ var withFileLock = async (filePath, options, fn) => {
14792
15427
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
14793
15428
  const lockPath = lockPathFor(filePath);
14794
15429
  const startedAt = options.clock.monotonicMillis();
14795
- await mkdir4(path9.dirname(filePath), { recursive: true });
15430
+ await mkdir5(path11.dirname(filePath), { recursive: true });
14796
15431
  for (; ; ) {
14797
- const token = randomBytes5(16).toString("hex");
15432
+ const token = randomBytes6(16).toString("hex");
14798
15433
  let acquired = false;
14799
15434
  try {
14800
- const handle = await open6(lockPath, "wx", 384);
15435
+ const handle = await open8(lockPath, "wx", 384);
14801
15436
  try {
14802
15437
  const contents = {
14803
15438
  token,
@@ -14839,8 +15474,8 @@ var withFileLock = async (filePath, options, fn) => {
14839
15474
  };
14840
15475
 
14841
15476
  // src/install/lifecycle.ts
14842
- import { readFile as readFile5 } from "fs/promises";
14843
- import * as path10 from "path";
15477
+ import { readFile as readFile6 } from "fs/promises";
15478
+ import * as path12 from "path";
14844
15479
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
14845
15480
  var unsupportedOutcome = (providerId, scope, reason) => ({
14846
15481
  providerId,
@@ -14857,7 +15492,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
14857
15492
  var resolveTarget = (providerId, scope, request) => {
14858
15493
  if (request.configFile !== void 0) {
14859
15494
  return {
14860
- configPath: path10.resolve(request.configFile),
15495
+ configPath: path12.resolve(request.configFile),
14861
15496
  evidence: "path supplied by the caller with --settings-file"
14862
15497
  };
14863
15498
  }
@@ -14874,14 +15509,14 @@ var resolveTarget = (providerId, scope, request) => {
14874
15509
  };
14875
15510
  };
14876
15511
  var codexFeatureNote = async (configPath) => {
14877
- const tomlPath = path10.join(path10.dirname(configPath), "config.toml");
15512
+ const tomlPath = path12.join(path12.dirname(configPath), "config.toml");
14878
15513
  let raw;
14879
15514
  try {
14880
- raw = await readFile5(tomlPath, "utf8");
15515
+ raw = await readFile6(tomlPath, "utf8");
14881
15516
  } catch {
14882
15517
  return void 0;
14883
15518
  }
14884
- 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;
14885
15520
  };
14886
15521
  var readState = async (configPath) => {
14887
15522
  const read = await readJsonDocument(configPath);
@@ -14893,12 +15528,12 @@ var readState = async (configPath) => {
14893
15528
  case "unparseable":
14894
15529
  return {
14895
15530
  status: "blocked",
14896
- 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`
14897
15532
  };
14898
15533
  case "unreadable":
14899
15534
  return {
14900
15535
  status: "failed",
14901
- problem: `${path10.basename(configPath)} could not be read (${read.detail})`
15536
+ problem: `${path12.basename(configPath)} could not be read (${read.detail})`
14902
15537
  };
14903
15538
  }
14904
15539
  };
@@ -15010,7 +15645,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15010
15645
  missingEvents: [],
15011
15646
  notes,
15012
15647
  problems: planned.conflicts.map(
15013
- (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`
15014
15649
  )
15015
15650
  };
15016
15651
  }
@@ -15021,7 +15656,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15021
15656
  changed: false,
15022
15657
  registeredEvents: [],
15023
15658
  missingEvents: [],
15024
- notes: [...notes, `${path10.basename(configPath)} does not exist; nothing to remove`],
15659
+ notes: [...notes, `${path12.basename(configPath)} does not exist; nothing to remove`],
15025
15660
  problems: []
15026
15661
  };
15027
15662
  }
@@ -15064,7 +15699,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15064
15699
  missingEvents: [],
15065
15700
  notes,
15066
15701
  problems: [
15067
- `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})`
15068
15703
  ]
15069
15704
  };
15070
15705
  }
@@ -15091,7 +15726,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15091
15726
  missingEvents: [],
15092
15727
  notes,
15093
15728
  problems: [
15094
- 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`
15095
15730
  ]
15096
15731
  };
15097
15732
  }
@@ -15192,6 +15827,7 @@ export {
15192
15827
  CODEX_HOOK_EVENT_NAMES,
15193
15828
  CODEX_PROVIDER_ID,
15194
15829
  CODEX_REGISTRABLE_HOOK_EVENTS,
15830
+ CODEX_ROLLOUT_USAGE_ENRICHER_ID,
15195
15831
  CODEX_UNREGISTERED_HOOK_EVENTS,
15196
15832
  CONFIG_SOURCE_PRECEDENCE,
15197
15833
  CONTENT_HASH_PATTERN,
@@ -15210,13 +15846,19 @@ export {
15210
15846
  DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
15211
15847
  DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
15212
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,
15213
15853
  DEFAULT_CONFIG,
15214
15854
  DEFAULT_DESTINATION_NAME,
15215
15855
  DEFAULT_DESTINATION_SIGNALS,
15216
15856
  DEFAULT_DETECTION_POLICY,
15217
15857
  DEFAULT_DIAGNOSTICS_POLICY,
15218
15858
  DEFAULT_DOCUMENT_FORMAT,
15859
+ DEFAULT_ENDPOINT_DOWN_MILLIS,
15219
15860
  DEFAULT_EXPORTER_POLICY,
15861
+ DEFAULT_EXPORT_BUDGET_MILLIS,
15220
15862
  DEFAULT_GEMINI_CAPABILITIES,
15221
15863
  DEFAULT_INSTRUMENTATION_SCOPE,
15222
15864
  DEFAULT_LOGS_POLICY,
@@ -15353,6 +15995,7 @@ export {
15353
15995
  createClaudeCodeAdapter,
15354
15996
  createClaudeTranscriptUsageEnricher,
15355
15997
  createCodexAdapter,
15998
+ createCodexRolloutUsageEnricher,
15356
15999
  createCursorAdapter,
15357
16000
  createDefaultProviderRegistry,
15358
16001
  createDestinationFanout,
@@ -15411,6 +16054,7 @@ export {
15411
16054
  detectionPolicySchema,
15412
16055
  diagnosticsPolicySchema,
15413
16056
  durationMillisSchema,
16057
+ effectiveExportTimeoutMillis,
15414
16058
  effectiveMetricsPolicy,
15415
16059
  effectiveSpoolPolicy,
15416
16060
  emptyExtensions,
@@ -15509,6 +16153,7 @@ export {
15509
16153
  readClaudeTranscriptTurn,
15510
16154
  readCodexHookRegistrations,
15511
16155
  readCodexHooksFeatureFlag,
16156
+ readCodexRolloutUsage,
15512
16157
  readCursorHookRegistrations,
15513
16158
  readDeliveryClaim,
15514
16159
  readDeliveryGap,
@@ -15516,6 +16161,7 @@ export {
15516
16161
  readJsonDocument,
15517
16162
  readNestedHookRegistrations,
15518
16163
  readsClaudeTranscriptUsage,
16164
+ readsCodexRolloutUsage,
15519
16165
  removeAntigravityHookRegistration,
15520
16166
  removeClaudeHookRegistration,
15521
16167
  removeCodexHookRegistration,