@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/cli.js CHANGED
@@ -360,6 +360,7 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
360
360
  "--no-metrics",
361
361
  "--no-metrics-session-id",
362
362
  "--claude-transcript-usage",
363
+ "--codex-rollout-usage",
363
364
  "--include-experimental",
364
365
  "--no-experimental",
365
366
  "--dry-run",
@@ -567,6 +568,7 @@ var parsePolicy = (tokens, errors) => {
567
568
  ...metricsTemporality === void 0 ? {} : { metricsTemporality },
568
569
  ...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
569
570
  ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {},
571
+ ...tokens.booleans.has("--codex-rollout-usage") ? { codexRolloutUsage: true } : {},
570
572
  ...sessionContextDir2 === void 0 || !isAbsolute(sessionContextDir2) ? {} : { sessionContextDir: sessionContextDir2 }
571
573
  };
572
574
  };
@@ -628,6 +630,7 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
628
630
  "--metrics-temporality",
629
631
  "--no-metrics-session-id",
630
632
  "--claude-transcript-usage",
633
+ "--codex-rollout-usage",
631
634
  "--session-context-dir",
632
635
  "--max-input-bytes",
633
636
  "--no-export",
@@ -664,6 +667,7 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
664
667
  "--metrics-temporality",
665
668
  "--no-metrics-session-id",
666
669
  "--claude-transcript-usage",
670
+ "--codex-rollout-usage",
667
671
  "--session-context-dir",
668
672
  "--include-experimental",
669
673
  "--no-experimental"
@@ -921,6 +925,10 @@ Exporter and runtime policy (never identity):
921
925
  payload names (bounded) for the turn's model and
922
926
  summed token usage. Off by default; also
923
927
  OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
928
+ --codex-rollout-usage Codex only: at Stop, read the session's rollout
929
+ (transcript_path; bounded, from a per-session
930
+ cursor) for the running token total. Off by
931
+ default; also OTEL_HOOK_CODEX_ROLLOUT_USAGE=1
924
932
  --session-context-dir <dir>
925
933
  absolute directory of session context files
926
934
  (<dir>/<agent-tool>/<session-id>.json); the
@@ -1428,7 +1436,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
1428
1436
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
1429
1437
  logLevel: "OTEL_HOOK_LOG_LEVEL",
1430
1438
  /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
1431
- claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
1439
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE",
1440
+ /** `providers.codex.readRolloutUsage`; see `providersPolicySchema`. */
1441
+ codexRolloutUsage: "OTEL_HOOK_CODEX_ROLLOUT_USAGE"
1432
1442
  });
1433
1443
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
1434
1444
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -1623,7 +1633,11 @@ var parseEnvironmentConfig = (env) => {
1623
1633
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
1624
1634
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
1625
1635
  const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
1626
- const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
1636
+ const codexRolloutUsage = readBoolean(ENVIRONMENT_VARIABLES.codexRolloutUsage);
1637
+ const providers = {
1638
+ ...claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } },
1639
+ ...codexRolloutUsage === void 0 ? {} : { codex: { readRolloutUsage: codexRolloutUsage } }
1640
+ };
1627
1641
  const patch = {
1628
1642
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
1629
1643
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
@@ -1928,8 +1942,26 @@ var exporterPolicySchema = z7.strictObject({
1928
1942
  * Per-destination retry spool bounds, each optional and merged per leaf; any
1929
1943
  * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
1930
1944
  */
1931
- spool: spoolPolicySchema.partial().optional()
1945
+ spool: spoolPolicySchema.partial().optional(),
1946
+ /**
1947
+ * The most time one hook invocation spends trying to reach one endpoint, in
1948
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
1949
+ * included) and the exporter's own retries inside it. A batch that does not
1950
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
1951
+ * the host agent waits for its hooks, so a down collector must not stall it.
1952
+ */
1953
+ exportBudgetMillis: z7.number().int().min(50).max(6e5).optional(),
1954
+ /**
1955
+ * After an endpoint was unreachable (refused, timed out, or answered a
1956
+ * retryable status), every hook spools for it without trying for this long,
1957
+ * in milliseconds; then one hook probes it again. 0 disables the window.
1958
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
1959
+ */
1960
+ endpointDownMillis: z7.number().int().min(0).max(36e5).optional()
1932
1961
  });
1962
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
1963
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
1964
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
1933
1965
  var detectionPolicySchema = z7.strictObject({
1934
1966
  /** Detections below this confidence resolve to the unknown provider. */
1935
1967
  minimumConfidence: detectionConfidenceSchema,
@@ -1946,6 +1978,9 @@ var diagnosticsPolicySchema = z7.strictObject({
1946
1978
  var providersPolicySchema = z7.strictObject({
1947
1979
  claudeCode: z7.strictObject({
1948
1980
  readTranscriptUsage: z7.boolean()
1981
+ }).optional(),
1982
+ codex: z7.strictObject({
1983
+ readRolloutUsage: z7.boolean()
1949
1984
  }).optional()
1950
1985
  });
1951
1986
  var sessionContextPolicySchema = z7.strictObject({
@@ -1975,7 +2010,8 @@ var otelHookConfigPatchSchema = z7.strictObject({
1975
2010
  detection: detectionPolicySchema.partial().optional(),
1976
2011
  diagnostics: diagnosticsPolicySchema.partial().optional(),
1977
2012
  providers: z7.strictObject({
1978
- claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
2013
+ claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional(),
2014
+ codex: z7.strictObject({ readRolloutUsage: z7.boolean() }).partial().optional()
1979
2015
  }).partial().optional(),
1980
2016
  sessionContext: sessionContextPolicySchema.partial().optional()
1981
2017
  });
@@ -2002,7 +2038,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2002
2038
  emitErrorEvents: true
2003
2039
  });
2004
2040
  var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2005
- claudeCode: Object.freeze({ readTranscriptUsage: false })
2041
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
2042
+ codex: Object.freeze({ readRolloutUsage: false })
2006
2043
  });
2007
2044
  var DEFAULT_CONFIG = Object.freeze({
2008
2045
  exporter: DEFAULT_EXPORTER_POLICY,
@@ -2012,6 +2049,7 @@ var DEFAULT_CONFIG = Object.freeze({
2012
2049
  providers: DEFAULT_PROVIDERS_POLICY
2013
2050
  });
2014
2051
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2052
+ var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
2015
2053
  var sessionContextDir = (config) => config.sessionContext?.dir;
2016
2054
  var effectiveMetricsPolicy = (exporter) => ({
2017
2055
  ...DEFAULT_METRICS_POLICY,
@@ -2022,12 +2060,12 @@ var effectiveMetricsPolicy = (exporter) => ({
2022
2060
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2023
2061
  var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
2024
2062
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2025
- var mergeLeaf = (target, patch, source, provenance, path15) => {
2063
+ var mergeLeaf = (target, patch, source, provenance, path17) => {
2026
2064
  for (const [key, value] of Object.entries(patch)) {
2027
2065
  if (value === void 0) {
2028
2066
  continue;
2029
2067
  }
2030
- const childPath = path15 === "" ? key : `${path15}.${key}`;
2068
+ const childPath = path17 === "" ? key : `${path17}.${key}`;
2031
2069
  const existing = target[key];
2032
2070
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2033
2071
  const child = { ...existing ?? {} };
@@ -2041,14 +2079,14 @@ var mergeLeaf = (target, patch, source, provenance, path15) => {
2041
2079
  };
2042
2080
  var initialProvenance = (config) => {
2043
2081
  const provenance = {};
2044
- const walk = (value, path15) => {
2082
+ const walk = (value, path17) => {
2045
2083
  if (isPlainObject(value)) {
2046
2084
  for (const [key, child] of Object.entries(value)) {
2047
- walk(child, path15 === "" ? key : `${path15}.${key}`);
2085
+ walk(child, path17 === "" ? key : `${path17}.${key}`);
2048
2086
  }
2049
2087
  return;
2050
2088
  }
2051
- provenance[path15] = "defaults";
2089
+ provenance[path17] = "defaults";
2052
2090
  };
2053
2091
  walk(config, "");
2054
2092
  return provenance;
@@ -2172,7 +2210,7 @@ var describeDestinationAttributes = (config) => {
2172
2210
  return attributes;
2173
2211
  };
2174
2212
  var describeResolvedConfig = (config) => {
2175
- const originOf = (endpoint) => {
2213
+ const originOf2 = (endpoint) => {
2176
2214
  if (endpoint === void 0) {
2177
2215
  return void 0;
2178
2216
  }
@@ -2182,10 +2220,10 @@ var describeResolvedConfig = (config) => {
2182
2220
  return "<unparsable>";
2183
2221
  }
2184
2222
  };
2185
- const endpointOrigin2 = originOf(config.exporter.endpoint);
2186
- const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2223
+ const endpointOrigin2 = originOf2(config.exporter.endpoint);
2224
+ const logsEndpointOrigin = originOf2(config.exporter.logs.endpoint);
2187
2225
  const metrics = effectiveMetricsPolicy(config.exporter);
2188
- const metricsEndpointOrigin = originOf(metrics.endpoint);
2226
+ const metricsEndpointOrigin = originOf2(metrics.endpoint);
2189
2227
  return {
2190
2228
  "exporter.enabled": config.exporter.enabled,
2191
2229
  "exporter.protocol": config.exporter.protocol,
@@ -3128,7 +3166,12 @@ var policyFlagsToPatch = (policy) => {
3128
3166
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
3129
3167
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
3130
3168
  ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
3131
- ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {},
3169
+ ...policy.claudeTranscriptUsage === true || policy.codexRolloutUsage === true ? {
3170
+ providers: {
3171
+ ...policy.claudeTranscriptUsage === true ? { claudeCode: { readTranscriptUsage: true } } : {},
3172
+ ...policy.codexRolloutUsage === true ? { codex: { readRolloutUsage: true } } : {}
3173
+ }
3174
+ } : {},
3132
3175
  ...policy.sessionContextDir === void 0 ? {} : { sessionContext: { dir: policy.sessionContextDir } }
3133
3176
  };
3134
3177
  };
@@ -3219,7 +3262,7 @@ var readIdentityFile = readJsonFile;
3219
3262
 
3220
3263
  // src/cli/doctor.ts
3221
3264
  import { readdir as readdir3, stat as stat3 } from "fs/promises";
3222
- import * as path4 from "path";
3265
+ import * as path5 from "path";
3223
3266
 
3224
3267
  // src/diagnostics/health.ts
3225
3268
  var createHealthTracker = (subsystem, options = {}) => {
@@ -3483,11 +3526,11 @@ var createPrivacyService = (policyInput) => {
3483
3526
  };
3484
3527
  const flattenToAttributes = (value, prefix) => {
3485
3528
  const attributes = {};
3486
- const walk = (current, path15) => {
3529
+ const walk = (current, path17) => {
3487
3530
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3488
3531
  const primitive = toAttributePrimitive(current);
3489
3532
  if (primitive !== void 0) {
3490
- attributes[path15] = primitive;
3533
+ attributes[path17] = primitive;
3491
3534
  }
3492
3535
  return;
3493
3536
  }
@@ -3506,16 +3549,16 @@ var createPrivacyService = (policyInput) => {
3506
3549
  primitives.push(entryPrimitive);
3507
3550
  }
3508
3551
  if (uniform) {
3509
- attributes[path15] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3552
+ attributes[path17] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3510
3553
  return;
3511
3554
  }
3512
3555
  for (const [index, entry] of current.entries()) {
3513
- walk(entry, `${path15}.${index}`);
3556
+ walk(entry, `${path17}.${index}`);
3514
3557
  }
3515
3558
  return;
3516
3559
  }
3517
3560
  for (const [key, entry] of Object.entries(current)) {
3518
- walk(entry, path15 === "" ? key : `${path15}.${key}`);
3561
+ walk(entry, path17 === "" ? key : `${path17}.${key}`);
3519
3562
  }
3520
3563
  };
3521
3564
  walk(value, prefix);
@@ -5197,6 +5240,7 @@ var permissionModeSchema = z20.enum([
5197
5240
  var codexUsageSchema = z20.object({
5198
5241
  input_tokens: z20.number().int().min(0).optional(),
5199
5242
  cached_input_tokens: z20.number().int().min(0).optional(),
5243
+ cache_write_input_tokens: z20.number().int().min(0).optional(),
5200
5244
  output_tokens: z20.number().int().min(0).optional(),
5201
5245
  reasoning_output_tokens: z20.number().int().min(0).optional(),
5202
5246
  total_tokens: z20.number().int().min(0).optional()
@@ -5452,6 +5496,10 @@ var codexUsageToReport = (usage, temporality) => ({
5452
5496
  temporality,
5453
5497
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
5454
5498
  ...usage.cached_input_tokens === void 0 ? {} : { cachedInputTokens: usage.cached_input_tokens },
5499
+ ...usage.cache_write_input_tokens === void 0 ? {} : {
5500
+ cacheCreationInputTokens: usage.cache_write_input_tokens,
5501
+ cacheCreationAccounting: "included-in-input"
5502
+ },
5455
5503
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
5456
5504
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
5457
5505
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -5480,8 +5528,9 @@ var CODEX_CAPABILITIES = Object.freeze({
5480
5528
  // turn; see docs/usage-semantics.md.
5481
5529
  cumulativeUsageSeries: "session-lifetime",
5482
5530
  reportsCachedInput: true,
5483
- reportsCacheCreation: false,
5484
- cacheCreationAccounting: "not-reported",
5531
+ // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.
5532
+ reportsCacheCreation: true,
5533
+ cacheCreationAccounting: "included-in-input",
5485
5534
  reportsReasoningOutput: true,
5486
5535
  reportsProviderTotal: true,
5487
5536
  reportsCost: false,
@@ -8066,7 +8115,7 @@ var createFilesystemStateStore = (options) => {
8066
8115
 
8067
8116
  // src/telemetry/spool-queue.ts
8068
8117
  import { randomBytes as randomBytes2 } from "crypto";
8069
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8118
+ import { mkdir as mkdir2, open as open2, readFile as readFile3, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8070
8119
  import * as path3 from "path";
8071
8120
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
8072
8121
  total: 0,
@@ -8126,7 +8175,8 @@ var readSpoolQueueStats = async (queueDir) => {
8126
8175
  };
8127
8176
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
8128
8177
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
8129
- var CLAIM_MARKER = ".claimed-";
8178
+ var CLAIM_SUFFIX = ".claim";
8179
+ var RELEASING_SUFFIX = ".releasing";
8130
8180
  var isClaimOwnerAlive = (pid) => {
8131
8181
  if (!Number.isSafeInteger(pid) || pid <= 0) {
8132
8182
  return true;
@@ -8142,6 +8192,34 @@ var isClaimOwnerAlive = (pid) => {
8142
8192
  }
8143
8193
  };
8144
8194
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
8195
+ var readClaim = async (claimPath) => {
8196
+ try {
8197
+ const parsed = JSON.parse(await readFile3(claimPath, "utf8"));
8198
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
8199
+ } catch {
8200
+ return void 0;
8201
+ }
8202
+ };
8203
+ var releaseClaim = async (claimPath, token) => {
8204
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes2(4).toString("hex")}${RELEASING_SUFFIX}`;
8205
+ for (let attempt = 1; ; attempt += 1) {
8206
+ try {
8207
+ await rename2(claimPath, tombstone);
8208
+ break;
8209
+ } catch (thrown) {
8210
+ if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
8211
+ return;
8212
+ }
8213
+ await new Promise((resolve8) => setTimeout(resolve8, 10 * attempt));
8214
+ }
8215
+ }
8216
+ const captured = await readClaim(tombstone);
8217
+ if (captured !== void 0 && captured.token !== token) {
8218
+ await rename2(tombstone, claimPath).catch(() => void 0);
8219
+ return;
8220
+ }
8221
+ await unlink2(tombstone).catch(() => void 0);
8222
+ };
8145
8223
  var createSpoolQueue = (options) => {
8146
8224
  const [providerSegment, installationSegment] = namespaceSegments(options);
8147
8225
  const queueDir = path3.join(options.rootDir, providerSegment, installationSegment, options.queueName);
@@ -8290,6 +8368,19 @@ var createSpoolQueue = (options) => {
8290
8368
  await rename2(tmp, target);
8291
8369
  return { spooled: true };
8292
8370
  };
8371
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
8372
+ const staleClaim = async (claimPath) => {
8373
+ const claim = await readClaim(claimPath);
8374
+ const now = Date.now();
8375
+ if (claim !== void 0) {
8376
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
8377
+ }
8378
+ try {
8379
+ return now - (await stat2(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
8380
+ } catch {
8381
+ return { stale: false };
8382
+ }
8383
+ };
8293
8384
  const releaseStaleClaims = async () => {
8294
8385
  let entries;
8295
8386
  try {
@@ -8299,18 +8390,35 @@ var createSpoolQueue = (options) => {
8299
8390
  }
8300
8391
  const now = Date.now();
8301
8392
  for (const entry of entries) {
8302
- const marker = entry.lastIndexOf(CLAIM_MARKER);
8303
- if (marker <= 0) {
8304
- continue;
8393
+ const entryPath = path3.join(queueDir, entry);
8394
+ if (entry.endsWith(CLAIM_SUFFIX)) {
8395
+ const staleness = await staleClaim(entryPath);
8396
+ if (staleness.stale) {
8397
+ await releaseClaim(entryPath, staleness.token);
8398
+ }
8399
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
8400
+ try {
8401
+ if (now - (await stat2(entryPath)).mtimeMs > claimStaleMillis) {
8402
+ await unlink2(entryPath);
8403
+ }
8404
+ } catch {
8405
+ }
8305
8406
  }
8306
- const claimPath = path3.join(queueDir, entry);
8307
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
8407
+ }
8408
+ };
8409
+ const claimBatch = async (claimPath) => {
8410
+ const token = randomBytes2(16).toString("hex");
8411
+ try {
8412
+ const handle = await open2(claimPath, "wx");
8308
8413
  try {
8309
- if (!isClaimOwnerAlive(owner) || now - (await stat2(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
8310
- await rename2(claimPath, path3.join(queueDir, entry.slice(0, marker)));
8311
- }
8312
- } catch {
8414
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
8415
+ await handle.writeFile(JSON.stringify(contents), "utf8");
8416
+ } finally {
8417
+ await handle.close();
8313
8418
  }
8419
+ return token;
8420
+ } catch {
8421
+ return void 0;
8314
8422
  }
8315
8423
  };
8316
8424
  const drain = async (send, drainOptions) => {
@@ -8334,21 +8442,7 @@ var createSpoolQueue = (options) => {
8334
8442
  let failed = 0;
8335
8443
  let quarantined = 0;
8336
8444
  let index = 0;
8337
- for (; index < files.length && index < cap; index += 1) {
8338
- const fileName = files[index];
8339
- if (fileName === void 0) {
8340
- break;
8341
- }
8342
- const queuedPath = path3.join(queueDir, fileName);
8343
- const filePath = path3.join(
8344
- queueDir,
8345
- `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes2(4).toString("hex")}`
8346
- );
8347
- try {
8348
- await rename2(queuedPath, filePath);
8349
- } catch {
8350
- continue;
8351
- }
8445
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
8352
8446
  const quarantine = async (rejection) => {
8353
8447
  quarantined += 1;
8354
8448
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -8367,17 +8461,17 @@ var createSpoolQueue = (options) => {
8367
8461
  text = await readFile3(filePath, "utf8");
8368
8462
  } catch (thrown) {
8369
8463
  if (thrown?.code === "ENOENT") {
8370
- continue;
8464
+ return "next";
8371
8465
  }
8372
8466
  await quarantine("unreadable");
8373
- continue;
8467
+ return "next";
8374
8468
  }
8375
8469
  let parsed;
8376
8470
  try {
8377
8471
  parsed = JSON.parse(text);
8378
8472
  } catch {
8379
8473
  await quarantine("unparseable-json");
8380
- continue;
8474
+ return "next";
8381
8475
  }
8382
8476
  const validation = options.validate(parsed, {
8383
8477
  providerId: options.providerId,
@@ -8385,7 +8479,10 @@ var createSpoolQueue = (options) => {
8385
8479
  });
8386
8480
  if ("rejection" in validation) {
8387
8481
  await quarantine(validation.rejection);
8388
- continue;
8482
+ return "next";
8483
+ }
8484
+ if ((await readClaim(claimPath))?.token !== token) {
8485
+ return "next";
8389
8486
  }
8390
8487
  let delivered;
8391
8488
  try {
@@ -8397,14 +8494,34 @@ var createSpoolQueue = (options) => {
8397
8494
  if (await unlink2(filePath).then(() => true, () => false)) {
8398
8495
  await recordDrops("rejected", 1);
8399
8496
  }
8400
- continue;
8497
+ return "next";
8401
8498
  }
8402
8499
  if (delivered) {
8403
8500
  await unlink2(filePath).catch(() => void 0);
8404
8501
  drained += 1;
8405
- } else {
8406
- await rename2(filePath, queuedPath).catch(() => void 0);
8407
- failed += 1;
8502
+ return "next";
8503
+ }
8504
+ failed += 1;
8505
+ return "stop";
8506
+ };
8507
+ for (; index < files.length && index < cap; index += 1) {
8508
+ const fileName = files[index];
8509
+ if (fileName === void 0) {
8510
+ break;
8511
+ }
8512
+ const filePath = path3.join(queueDir, fileName);
8513
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
8514
+ const token = await claimBatch(claimPath);
8515
+ if (token === void 0) {
8516
+ continue;
8517
+ }
8518
+ let outcome;
8519
+ try {
8520
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
8521
+ } finally {
8522
+ await releaseClaim(claimPath, token);
8523
+ }
8524
+ if (outcome === "stop") {
8408
8525
  break;
8409
8526
  }
8410
8527
  }
@@ -8621,7 +8738,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
8621
8738
 
8622
8739
  // src/telemetry/otlp-log-sink.ts
8623
8740
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
8624
- import { ExportResultCode } from "@opentelemetry/core";
8741
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
8625
8742
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
8626
8743
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
8627
8744
 
@@ -8632,6 +8749,217 @@ var isPermanentExportFailure = (result) => {
8632
8749
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
8633
8750
  };
8634
8751
 
8752
+ // src/telemetry/endpoint-health.ts
8753
+ import { createHash as createHash3, randomBytes as randomBytes3 } from "crypto";
8754
+ import { mkdir as mkdir3, readFile as readFile4, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
8755
+ import * as http from "http";
8756
+ import * as https from "https";
8757
+ import path4 from "path";
8758
+ import { ExportResultCode } from "@opentelemetry/core";
8759
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
8760
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
8761
+ "ECONNREFUSED",
8762
+ "ECONNRESET",
8763
+ "ETIMEDOUT",
8764
+ "EPIPE",
8765
+ "EHOSTUNREACH",
8766
+ "ENETUNREACH",
8767
+ "EHOSTDOWN",
8768
+ "ENETDOWN",
8769
+ "EAI_AGAIN",
8770
+ "ENOTFOUND",
8771
+ ENDPOINT_DOWN_ERROR_CODE
8772
+ ]);
8773
+ var isUnreachableExportFailure = (result) => {
8774
+ if (result.code === ExportResultCode.SUCCESS) {
8775
+ return false;
8776
+ }
8777
+ const error = result.error;
8778
+ const code = error?.code;
8779
+ if (typeof code === "string") {
8780
+ return UNREACHABLE_NETWORK_CODES.has(code);
8781
+ }
8782
+ if (code !== void 0) {
8783
+ return false;
8784
+ }
8785
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
8786
+ };
8787
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
8788
+ const target = agent;
8789
+ const original = target.createConnection.bind(agent);
8790
+ target.createConnection = (options, callback) => {
8791
+ const socket = original(options, callback);
8792
+ if (socket !== void 0 && socket.connecting) {
8793
+ const timer = setTimeout(() => {
8794
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
8795
+ socket.destroy(error);
8796
+ }, connectTimeoutMillis);
8797
+ timer.unref();
8798
+ const clear = () => {
8799
+ clearTimeout(timer);
8800
+ };
8801
+ socket.once("connect", clear);
8802
+ socket.once("close", clear);
8803
+ }
8804
+ return socket;
8805
+ };
8806
+ return agent;
8807
+ };
8808
+ var boundedExporterOptions = (exporter) => {
8809
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
8810
+ let agents = {};
8811
+ return {
8812
+ timeoutMillis,
8813
+ httpAgentOptions: (protocol) => {
8814
+ if (protocol === "https:") {
8815
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
8816
+ return agents.https;
8817
+ }
8818
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
8819
+ return agents.http;
8820
+ }
8821
+ };
8822
+ };
8823
+ var parseMark = (raw) => {
8824
+ try {
8825
+ const parsed = JSON.parse(raw);
8826
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
8827
+ downUntil: parsed.downUntil,
8828
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
8829
+ } : void 0;
8830
+ } catch {
8831
+ return void 0;
8832
+ }
8833
+ };
8834
+ var originOf = (url) => {
8835
+ if (url === void 0) {
8836
+ return void 0;
8837
+ }
8838
+ try {
8839
+ return new URL(url).origin;
8840
+ } catch {
8841
+ return void 0;
8842
+ }
8843
+ };
8844
+ var createEndpointHealth = (options) => {
8845
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
8846
+ const gates = /* @__PURE__ */ new Map();
8847
+ const createGate = (origin) => {
8848
+ const digest3 = createHash3("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
8849
+ const dir = options.rootDir === void 0 ? void 0 : path4.join(options.rootDir, "endpoint-health");
8850
+ const file = dir === void 0 ? void 0 : path4.join(dir, `${digest3}.json`);
8851
+ let downUntil = 0;
8852
+ let failures = 0;
8853
+ let marked = false;
8854
+ let loaded;
8855
+ let warned = false;
8856
+ const write = async (mark) => {
8857
+ if (file === void 0 || dir === void 0) {
8858
+ return;
8859
+ }
8860
+ try {
8861
+ await mkdir3(dir, { recursive: true });
8862
+ const tmp = path4.join(dir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
8863
+ await writeFile3(tmp, `${JSON.stringify(mark)}
8864
+ `);
8865
+ await rename3(tmp, file);
8866
+ marked = true;
8867
+ } catch {
8868
+ }
8869
+ };
8870
+ const load = () => {
8871
+ loaded ??= (async () => {
8872
+ if (file === void 0) {
8873
+ return;
8874
+ }
8875
+ let raw;
8876
+ try {
8877
+ raw = await readFile4(file, "utf8");
8878
+ } catch {
8879
+ return;
8880
+ }
8881
+ marked = true;
8882
+ const mark = parseMark(raw);
8883
+ if (mark === void 0) {
8884
+ return;
8885
+ }
8886
+ failures = mark.failures;
8887
+ const now = options.clock.now();
8888
+ if (mark.downUntil > now) {
8889
+ downUntil = mark.downUntil;
8890
+ return;
8891
+ }
8892
+ await write({ downUntil: now + options.probeMillis, failures });
8893
+ })();
8894
+ return loaded;
8895
+ };
8896
+ return {
8897
+ available: async () => {
8898
+ if (downMillis === 0) {
8899
+ return true;
8900
+ }
8901
+ await load();
8902
+ return options.clock.now() >= downUntil;
8903
+ },
8904
+ record: async (result) => {
8905
+ if (downMillis === 0) {
8906
+ return;
8907
+ }
8908
+ if (!isUnreachableExportFailure(result)) {
8909
+ if (!marked && downUntil === 0) {
8910
+ return;
8911
+ }
8912
+ downUntil = 0;
8913
+ failures = 0;
8914
+ marked = false;
8915
+ if (file !== void 0) {
8916
+ await unlink3(file).catch(() => void 0);
8917
+ }
8918
+ return;
8919
+ }
8920
+ failures += 1;
8921
+ downUntil = options.clock.now() + downMillis;
8922
+ if (!warned) {
8923
+ warned = true;
8924
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
8925
+ "export.endpoint_down_millis": downMillis,
8926
+ "export.endpoint_failures": failures
8927
+ });
8928
+ }
8929
+ await write({ downUntil, failures });
8930
+ }
8931
+ };
8932
+ };
8933
+ return {
8934
+ gateFor: (url) => {
8935
+ const origin = originOf(url);
8936
+ if (origin === void 0) {
8937
+ return void 0;
8938
+ }
8939
+ let gate = gates.get(origin);
8940
+ if (gate === void 0) {
8941
+ gate = createGate(origin);
8942
+ gates.set(origin, gate);
8943
+ }
8944
+ return gate;
8945
+ }
8946
+ };
8947
+ };
8948
+ var guardExport = async (gate, send) => {
8949
+ if (gate === void 0) {
8950
+ return send();
8951
+ }
8952
+ if (!await gate.available()) {
8953
+ return {
8954
+ code: ExportResultCode.FAILED,
8955
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
8956
+ };
8957
+ }
8958
+ const result = await send();
8959
+ await gate.record(result).catch(() => void 0);
8960
+ return result;
8961
+ };
8962
+
8635
8963
  // src/telemetry/exporter-resource.ts
8636
8964
  import { resourceFromAttributes } from "@opentelemetry/resources";
8637
8965
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -8802,7 +9130,7 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8802
9130
  };
8803
9131
 
8804
9132
  // src/telemetry/semconv.ts
8805
- import { createHash as createHash3 } from "crypto";
9133
+ import { createHash as createHash4 } from "crypto";
8806
9134
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
8807
9135
  import { millisToHrTime } from "@opentelemetry/core";
8808
9136
  import {
@@ -8821,7 +9149,7 @@ import {
8821
9149
  } from "@opentelemetry/semantic-conventions/incubating";
8822
9150
 
8823
9151
  // src/version.ts
8824
- var VERSION = "0.13.1";
9152
+ var VERSION = "0.13.2";
8825
9153
 
8826
9154
  // src/telemetry/semconv.ts
8827
9155
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8842,7 +9170,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
8842
9170
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
8843
9171
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
8844
9172
  var FIELD_SEPARATOR = "\0";
8845
- var digestHex = (parts, length) => createHash3("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
9173
+ var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
8846
9174
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
8847
9175
  var familyOf = (type) => {
8848
9176
  switch (type) {
@@ -9848,12 +10176,16 @@ var createOtlpLogSink = (options) => {
9848
10176
  const exporter = new OTLPLogExporter({
9849
10177
  url: deliverability.endpoint,
9850
10178
  headers: { ...options.headers },
9851
- timeoutMillis: options.exporter.timeoutMillis
10179
+ ...boundedExporterOptions(options.exporter)
9852
10180
  });
10181
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
9853
10182
  let shutdownCompleted = false;
9854
- const exportRecords = (records) => new Promise((resolve8) => {
9855
- exporter.export([...records], (result) => resolve8(result));
9856
- });
10183
+ const exportRecords = (records) => guardExport(
10184
+ gate,
10185
+ () => new Promise((resolve8) => {
10186
+ exporter.export([...records], (result) => resolve8(result));
10187
+ })
10188
+ );
9857
10189
  const toSpoolBatch = (records, batchResource) => ({
9858
10190
  providerId: options.providerId,
9859
10191
  installationId: options.installationId,
@@ -9871,7 +10203,7 @@ var createOtlpLogSink = (options) => {
9871
10203
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
9872
10204
  );
9873
10205
  const result = await exportRecords(records);
9874
- if (result.code === ExportResultCode.SUCCESS) {
10206
+ if (result.code === ExportResultCode2.SUCCESS) {
9875
10207
  return true;
9876
10208
  }
9877
10209
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -9917,11 +10249,11 @@ var createOtlpLogSink = (options) => {
9917
10249
  result = await exportRecords(batch);
9918
10250
  } catch (thrown) {
9919
10251
  result = {
9920
- code: ExportResultCode.FAILED,
10252
+ code: ExportResultCode2.FAILED,
9921
10253
  error: thrown instanceof Error ? thrown : new Error("export threw")
9922
10254
  };
9923
10255
  }
9924
- if (result.code === ExportResultCode.SUCCESS) {
10256
+ if (result.code === ExportResultCode2.SUCCESS) {
9925
10257
  accepted += batch.length;
9926
10258
  health.recordSuccess(batch.length, options.clock.now());
9927
10259
  continue;
@@ -9962,6 +10294,9 @@ var createOtlpLogSink = (options) => {
9962
10294
  if (options.spool === void 0) {
9963
10295
  return { drained: 0, remaining: 0, failed: 0 };
9964
10296
  }
10297
+ if (gate !== void 0 && !await gate.available()) {
10298
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
10299
+ }
9965
10300
  const result = await options.spool.drain(sendSerializedBatch, {
9966
10301
  ...maxBatches === void 0 ? {} : { maxBatches }
9967
10302
  });
@@ -9998,7 +10333,7 @@ var createOtlpLogSink = (options) => {
9998
10333
  };
9999
10334
 
10000
10335
  // src/telemetry/otlp-sink.ts
10001
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
10336
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
10002
10337
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
10003
10338
  var chunk2 = (items, size) => {
10004
10339
  if (size <= 0 || items.length <= size) {
@@ -10076,12 +10411,16 @@ var createOtlpTraceSink = (options) => {
10076
10411
  const exporter = new OTLPTraceExporter({
10077
10412
  url: options.exporter.endpoint,
10078
10413
  headers: { ...options.headers },
10079
- timeoutMillis: options.exporter.timeoutMillis
10414
+ ...boundedExporterOptions(options.exporter)
10080
10415
  });
10416
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
10081
10417
  let shutdownCompleted = false;
10082
- const exportSpans = (spans) => new Promise((resolve8) => {
10083
- exporter.export([...spans], (result) => resolve8(result));
10084
- });
10418
+ const exportSpans = (spans) => guardExport(
10419
+ gate,
10420
+ () => new Promise((resolve8) => {
10421
+ exporter.export([...spans], (result) => resolve8(result));
10422
+ })
10423
+ );
10085
10424
  const toSpoolBatch = (spans, batchResource) => ({
10086
10425
  providerId: options.providerId,
10087
10426
  installationId: options.installationId,
@@ -10094,7 +10433,7 @@ var createOtlpTraceSink = (options) => {
10094
10433
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
10095
10434
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
10096
10435
  const result = await exportSpans(spans);
10097
- if (result.code === ExportResultCode2.SUCCESS) {
10436
+ if (result.code === ExportResultCode3.SUCCESS) {
10098
10437
  return true;
10099
10438
  }
10100
10439
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -10133,9 +10472,9 @@ var createOtlpTraceSink = (options) => {
10133
10472
  try {
10134
10473
  result = await exportSpans(batch);
10135
10474
  } catch (thrown) {
10136
- result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
10475
+ result = { code: ExportResultCode3.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
10137
10476
  }
10138
- if (result.code === ExportResultCode2.SUCCESS) {
10477
+ if (result.code === ExportResultCode3.SUCCESS) {
10139
10478
  accepted += batch.length;
10140
10479
  health.recordSuccess(batch.length, options.clock.now());
10141
10480
  continue;
@@ -10172,6 +10511,9 @@ var createOtlpTraceSink = (options) => {
10172
10511
  if (options.spool === void 0) {
10173
10512
  return { drained: 0, remaining: 0, failed: 0 };
10174
10513
  }
10514
+ if (gate !== void 0 && !await gate.available()) {
10515
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
10516
+ }
10175
10517
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
10176
10518
  if (result.drained > 0) {
10177
10519
  health.recordSuccess(result.drained, options.clock.now());
@@ -10562,7 +10904,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
10562
10904
 
10563
10905
  // src/telemetry/otlp-metric-sink.ts
10564
10906
  import { ValueType } from "@opentelemetry/api";
10565
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10907
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10566
10908
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
10567
10909
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
10568
10910
  import {
@@ -10706,10 +11048,12 @@ var createOtlpMetricSink = (options) => {
10706
11048
  const exporter = new OTLPMetricExporter({
10707
11049
  url: deliverability.endpoint,
10708
11050
  headers: { ...options.headers },
10709
- timeoutMillis: options.exporter.timeoutMillis
11051
+ ...boundedExporterOptions(options.exporter)
10710
11052
  });
11053
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
10711
11054
  let shutdownCompleted = false;
10712
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
11055
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
11056
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
10713
11057
  const payload = {
10714
11058
  resource: batchResource,
10715
11059
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -10718,7 +11062,7 @@ var createOtlpMetricSink = (options) => {
10718
11062
  exporter.export(payload, (result) => resolve8(result));
10719
11063
  } catch (thrown) {
10720
11064
  resolve8({
10721
- code: ExportResultCode3.FAILED,
11065
+ code: ExportResultCode4.FAILED,
10722
11066
  error: thrown instanceof Error ? thrown : new Error("export threw")
10723
11067
  });
10724
11068
  }
@@ -10739,7 +11083,7 @@ var createOtlpMetricSink = (options) => {
10739
11083
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
10740
11084
  );
10741
11085
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
10742
- if (result.code === ExportResultCode3.SUCCESS) {
11086
+ if (result.code === ExportResultCode4.SUCCESS) {
10743
11087
  return true;
10744
11088
  }
10745
11089
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -10750,7 +11094,7 @@ var createOtlpMetricSink = (options) => {
10750
11094
  }
10751
11095
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
10752
11096
  const result = await exportResourceMetrics(points, batchResource, scope);
10753
- if (result.code === ExportResultCode3.SUCCESS) {
11097
+ if (result.code === ExportResultCode4.SUCCESS) {
10754
11098
  health.recordSuccess(points.length, options.clock.now());
10755
11099
  return { accepted: points.length, rejected: 0, errors: [] };
10756
11100
  }
@@ -10790,6 +11134,9 @@ var createOtlpMetricSink = (options) => {
10790
11134
  if (options.spool === void 0) {
10791
11135
  return { drained: 0, remaining: 0, failed: 0 };
10792
11136
  }
11137
+ if (gate !== void 0 && !await gate.available()) {
11138
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
11139
+ }
10793
11140
  const result = await options.spool.drain(sendSerializedBatch, {
10794
11141
  ...maxBatches === void 0 ? {} : { maxBatches }
10795
11142
  });
@@ -10927,6 +11274,13 @@ var createExportDestinationSinks = (options) => {
10927
11274
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
10928
11275
  const destinations = [];
10929
11276
  const skipped = [];
11277
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
11278
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
11279
+ clock: options.clock,
11280
+ ...options.logger === void 0 ? {} : { logger: options.logger },
11281
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
11282
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
11283
+ });
10930
11284
  for (const destination of resolveExportDestinations(options.exporter)) {
10931
11285
  let headers;
10932
11286
  let logHeaders;
@@ -10986,6 +11340,7 @@ var createExportDestinationSinks = (options) => {
10986
11340
  const sinkShared = {
10987
11341
  exporter: policy,
10988
11342
  ...shared,
11343
+ endpointHealth,
10989
11344
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
10990
11345
  ...label === void 0 ? {} : { destination: label }
10991
11346
  };
@@ -11003,6 +11358,7 @@ var createExportDestinationSinks = (options) => {
11003
11358
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
11004
11359
  exporter: policy,
11005
11360
  ...shared,
11361
+ endpointHealth,
11006
11362
  ...label === void 0 ? {} : { destination: label },
11007
11363
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
11008
11364
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -11185,7 +11541,7 @@ var collectDoctorReport = async (command, io) => {
11185
11541
  checks.push({
11186
11542
  name: "session-context",
11187
11543
  ok: true,
11188
- detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path4.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11544
+ detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path5.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11189
11545
  });
11190
11546
  const providers = describeProviderCatalog({
11191
11547
  includeExperimental: command.policy.includeExperimental ?? true
@@ -11283,7 +11639,7 @@ var inspectQueue = async (spool, queueName) => {
11283
11639
  const installation = sanitizeSegment(spool.installationId);
11284
11640
  const stats = await Promise.all(
11285
11641
  namespaces.map(
11286
- (namespace) => readSpoolQueueStats(path4.join(spool.rootDir, namespace, installation, queueName))
11642
+ (namespace) => readSpoolQueueStats(path5.join(spool.rootDir, namespace, installation, queueName))
11287
11643
  )
11288
11644
  );
11289
11645
  return stats.length === 0 ? { batches: 0, bytes: 0, dropped: EMPTY_SPOOL_DROP_COUNTS } : sumSpoolStats(stats);
@@ -12228,7 +12584,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
12228
12584
  );
12229
12585
 
12230
12586
  // src/install/scopes.ts
12231
- import * as path5 from "path";
12587
+ import * as path6 from "path";
12232
12588
  var REGISTRATION_SCOPES = Object.freeze([
12233
12589
  "global",
12234
12590
  "project"
@@ -12296,15 +12652,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
12296
12652
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
12297
12653
  (entry) => entry.providerId === providerId && entry.scope === scope
12298
12654
  );
12299
- var resolveInstallPath = (location, roots) => path5.resolve(
12655
+ var resolveInstallPath = (location, roots) => path6.resolve(
12300
12656
  location.scope === "global" ? roots.homeDir : roots.projectDir,
12301
12657
  ...location.segments
12302
12658
  );
12303
12659
 
12304
12660
  // src/install/document.ts
12305
- import { randomBytes as randomBytes3 } from "crypto";
12306
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
12307
- import * as path6 from "path";
12661
+ import { randomBytes as randomBytes4 } from "crypto";
12662
+ import { chmod, mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12663
+ import * as path7 from "path";
12308
12664
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12309
12665
  indent: " ",
12310
12666
  eol: "\n",
@@ -12328,7 +12684,7 @@ var renderJsonDocument = (value, format) => {
12328
12684
  var readJsonDocument = async (filePath) => {
12329
12685
  let raw;
12330
12686
  try {
12331
- raw = await readFile4(filePath, "utf8");
12687
+ raw = await readFile5(filePath, "utf8");
12332
12688
  } catch (thrown) {
12333
12689
  if (isErrnoException3(thrown, "ENOENT")) {
12334
12690
  return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
@@ -12360,7 +12716,7 @@ var delay = (millis) => new Promise((resolve8) => {
12360
12716
  var renameWithRetry = async (from, to) => {
12361
12717
  for (let attempt = 0; ; attempt += 1) {
12362
12718
  try {
12363
- await rename3(from, to);
12719
+ await rename4(from, to);
12364
12720
  return;
12365
12721
  } catch (thrown) {
12366
12722
  const retryable = isErrnoException3(thrown, "EPERM", "EACCES", "EBUSY");
@@ -12375,11 +12731,11 @@ var renameWithRetry = async (from, to) => {
12375
12731
  var NEW_DOCUMENT_MODE = 384;
12376
12732
  var TEMPORARY_DOCUMENT_MODE = 384;
12377
12733
  var writeDocumentAtomically = async (filePath, contents) => {
12378
- const directory = path6.dirname(filePath);
12379
- await mkdir3(directory, { recursive: true });
12380
- const temporary = path6.join(
12734
+ const directory = path7.dirname(filePath);
12735
+ await mkdir4(directory, { recursive: true });
12736
+ const temporary = path7.join(
12381
12737
  directory,
12382
- `.${path6.basename(filePath)}.${randomBytes3(6).toString("hex")}.tmp`
12738
+ `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
12383
12739
  );
12384
12740
  let existingMode;
12385
12741
  try {
@@ -12391,7 +12747,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12391
12747
  }
12392
12748
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
12393
12749
  try {
12394
- const handle = await open2(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12750
+ const handle = await open3(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12395
12751
  try {
12396
12752
  await handle.writeFile(contents, "utf8");
12397
12753
  await handle.sync();
@@ -12401,19 +12757,19 @@ var writeDocumentAtomically = async (filePath, contents) => {
12401
12757
  }
12402
12758
  await renameWithRetry(temporary, filePath);
12403
12759
  } catch (thrown) {
12404
- await unlink3(temporary).catch(() => void 0);
12760
+ await unlink4(temporary).catch(() => void 0);
12405
12761
  throw thrown;
12406
12762
  }
12407
12763
  };
12408
12764
 
12409
12765
  // src/install/file-lock.ts
12410
- import { randomBytes as randomBytes4 } from "crypto";
12411
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
12412
- import * as path7 from "path";
12766
+ import { randomBytes as randomBytes5 } from "crypto";
12767
+ import { mkdir as mkdir5, open as open4, readFile as readFile6, rename as rename5, stat as stat5, unlink as unlink5 } from "fs/promises";
12768
+ import * as path8 from "path";
12413
12769
  var FileLockTimeoutError = class extends Error {
12414
12770
  constructor(lockPath, timeoutMillis) {
12415
12771
  super(
12416
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path7.basename(lockPath)}`
12772
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
12417
12773
  );
12418
12774
  this.name = "FileLockTimeoutError";
12419
12775
  }
@@ -12424,7 +12780,7 @@ var isErrnoException4 = (thrown, code) => thrown instanceof Error && thrown.code
12424
12780
  var readLockContents = async (lockPath) => {
12425
12781
  let raw;
12426
12782
  try {
12427
- raw = await readFile5(lockPath, "utf8");
12783
+ raw = await readFile6(lockPath, "utf8");
12428
12784
  } catch {
12429
12785
  return void 0;
12430
12786
  }
@@ -12438,18 +12794,18 @@ var readLockContents = async (lockPath) => {
12438
12794
  var releaseIfOwned = async (lockPath, token) => {
12439
12795
  const tombstone = `${lockPath}.${token}.releasing`;
12440
12796
  try {
12441
- await rename4(lockPath, tombstone);
12797
+ await rename5(lockPath, tombstone);
12442
12798
  } catch {
12443
12799
  return false;
12444
12800
  }
12445
12801
  const captured = await readLockContents(tombstone);
12446
12802
  if (captured !== void 0 && captured.token !== token) {
12447
- await rename4(tombstone, lockPath).catch(async () => {
12803
+ await rename5(tombstone, lockPath).catch(async () => {
12448
12804
  await Promise.resolve();
12449
12805
  });
12450
12806
  return false;
12451
12807
  }
12452
- await unlink4(tombstone).catch(() => void 0);
12808
+ await unlink5(tombstone).catch(() => void 0);
12453
12809
  return true;
12454
12810
  };
12455
12811
  var delay2 = (millis) => new Promise((resolve8) => {
@@ -12458,7 +12814,7 @@ var delay2 = (millis) => new Promise((resolve8) => {
12458
12814
  var isStale = async (lockPath, clock, staleMillis) => {
12459
12815
  let raw;
12460
12816
  try {
12461
- raw = await readFile5(lockPath, "utf8");
12817
+ raw = await readFile6(lockPath, "utf8");
12462
12818
  } catch (thrown) {
12463
12819
  return { stale: !isErrnoException4(thrown, "ENOENT") };
12464
12820
  }
@@ -12485,12 +12841,12 @@ var withFileLock = async (filePath, options, fn) => {
12485
12841
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
12486
12842
  const lockPath = lockPathFor(filePath);
12487
12843
  const startedAt = options.clock.monotonicMillis();
12488
- await mkdir4(path7.dirname(filePath), { recursive: true });
12844
+ await mkdir5(path8.dirname(filePath), { recursive: true });
12489
12845
  for (; ; ) {
12490
- const token = randomBytes4(16).toString("hex");
12846
+ const token = randomBytes5(16).toString("hex");
12491
12847
  let acquired = false;
12492
12848
  try {
12493
- const handle = await open3(lockPath, "wx", 384);
12849
+ const handle = await open4(lockPath, "wx", 384);
12494
12850
  try {
12495
12851
  const contents = {
12496
12852
  token,
@@ -12532,8 +12888,8 @@ var withFileLock = async (filePath, options, fn) => {
12532
12888
  };
12533
12889
 
12534
12890
  // src/install/lifecycle.ts
12535
- import { readFile as readFile6 } from "fs/promises";
12536
- import * as path8 from "path";
12891
+ import { readFile as readFile7 } from "fs/promises";
12892
+ import * as path9 from "path";
12537
12893
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
12538
12894
  var unsupportedOutcome = (providerId, scope, reason) => ({
12539
12895
  providerId,
@@ -12550,7 +12906,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
12550
12906
  var resolveTarget = (providerId, scope, request) => {
12551
12907
  if (request.configFile !== void 0) {
12552
12908
  return {
12553
- configPath: path8.resolve(request.configFile),
12909
+ configPath: path9.resolve(request.configFile),
12554
12910
  evidence: "path supplied by the caller with --settings-file"
12555
12911
  };
12556
12912
  }
@@ -12567,14 +12923,14 @@ var resolveTarget = (providerId, scope, request) => {
12567
12923
  };
12568
12924
  };
12569
12925
  var codexFeatureNote = async (configPath) => {
12570
- const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
12926
+ const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
12571
12927
  let raw;
12572
12928
  try {
12573
- raw = await readFile6(tomlPath, "utf8");
12929
+ raw = await readFile7(tomlPath, "utf8");
12574
12930
  } catch {
12575
12931
  return void 0;
12576
12932
  }
12577
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path8.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
12933
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
12578
12934
  };
12579
12935
  var readState = async (configPath) => {
12580
12936
  const read = await readJsonDocument(configPath);
@@ -12586,12 +12942,12 @@ var readState = async (configPath) => {
12586
12942
  case "unparseable":
12587
12943
  return {
12588
12944
  status: "blocked",
12589
- problem: `${path8.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
12945
+ problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
12590
12946
  };
12591
12947
  case "unreadable":
12592
12948
  return {
12593
12949
  status: "failed",
12594
- problem: `${path8.basename(configPath)} could not be read (${read.detail})`
12950
+ problem: `${path9.basename(configPath)} could not be read (${read.detail})`
12595
12951
  };
12596
12952
  }
12597
12953
  };
@@ -12703,7 +13059,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12703
13059
  missingEvents: [],
12704
13060
  notes,
12705
13061
  problems: planned.conflicts.map(
12706
- (conflict) => `${path8.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
13062
+ (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
12707
13063
  )
12708
13064
  };
12709
13065
  }
@@ -12714,7 +13070,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12714
13070
  changed: false,
12715
13071
  registeredEvents: [],
12716
13072
  missingEvents: [],
12717
- notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
13073
+ notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
12718
13074
  problems: []
12719
13075
  };
12720
13076
  }
@@ -12757,7 +13113,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12757
13113
  missingEvents: [],
12758
13114
  notes,
12759
13115
  problems: [
12760
- `could not write ${path8.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
13116
+ `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
12761
13117
  ]
12762
13118
  };
12763
13119
  }
@@ -12784,7 +13140,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12784
13140
  missingEvents: [],
12785
13141
  notes,
12786
13142
  problems: [
12787
- thrown instanceof Error ? `${path8.basename(configPath)}: ${thrown.message}` : `${path8.basename(configPath)}: the configuration file could not be locked`
13143
+ thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
12788
13144
  ]
12789
13145
  };
12790
13146
  }
@@ -12880,9 +13236,9 @@ var runProvidersCommand = (command, io) => {
12880
13236
 
12881
13237
  // src/cli/registration.ts
12882
13238
  import * as os2 from "os";
12883
- import * as path9 from "path";
12884
- var resolveProjectDir = (command, io) => path9.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
12885
- var resolveHomeDir = (command, io) => path9.resolve(command.homeDir ?? io.homeDir ?? os2.homedir());
13239
+ import * as path10 from "path";
13240
+ var resolveProjectDir = (command, io) => path10.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
13241
+ var resolveHomeDir = (command, io) => path10.resolve(command.homeDir ?? io.homeDir ?? os2.homedir());
12886
13242
  var collectRegistrationReport = async (command, io) => runRegistrationLifecycle({
12887
13243
  action: command.name,
12888
13244
  // A bare `diagnose` sweeps the providers this tool can locate by itself.
@@ -12963,10 +13319,10 @@ var runRegistrationCommand = async (command, io) => {
12963
13319
  };
12964
13320
 
12965
13321
  // src/cli/run.ts
12966
- import * as path14 from "path";
13322
+ import * as path16 from "path";
12967
13323
 
12968
13324
  // src/lifecycle/dedup.ts
12969
- import { randomBytes as randomBytes5 } from "crypto";
13325
+ import { randomBytes as randomBytes6 } from "crypto";
12970
13326
 
12971
13327
  // src/lifecycle/keys.ts
12972
13328
  var LIFECYCLE_PREFIX = "lifecycle";
@@ -13020,7 +13376,7 @@ var ownerOf = (record) => {
13020
13376
  const owner = record.value.attributes.owner;
13021
13377
  return typeof owner === "string" && owner.length > 0 ? owner : void 0;
13022
13378
  };
13023
- var newOwnerToken = () => randomBytes5(12).toString("hex");
13379
+ var newOwnerToken = () => randomBytes6(12).toString("hex");
13024
13380
  var claimedAtOf = (record) => {
13025
13381
  if (record?.value.kind !== "attributes") {
13026
13382
  return void 0;
@@ -13163,12 +13519,12 @@ var createCallbackDeduplicator = (deps) => {
13163
13519
  };
13164
13520
 
13165
13521
  // src/lifecycle/metric-series.ts
13166
- import { createHash as createHash4 } from "crypto";
13522
+ import { createHash as createHash5 } from "crypto";
13167
13523
  var TURN_START_SEGMENT = "turn-start";
13168
13524
  var SHARED_SCOPE = "all";
13169
13525
  var SHARED_LOCK = "otelhook.metrics.shared";
13170
13526
  var sessionScope = (sessionId) => `s=${sessionId}`;
13171
- var digest = (identity) => createHash4("sha256").update(identity).digest("base64url").slice(0, 43);
13527
+ var digest = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
13172
13528
  var toStoredHistogram = (histogram) => ({
13173
13529
  count: histogram.count,
13174
13530
  sum: histogram.sum,
@@ -13855,9 +14211,9 @@ var createUsageAccumulator = (deps) => {
13855
14211
  };
13856
14212
 
13857
14213
  // src/providers/claude/transcript.ts
13858
- import { createHash as createHash5 } from "crypto";
13859
- import { open as open4, stat as stat6 } from "fs/promises";
13860
- import path10 from "path";
14214
+ import { createHash as createHash6 } from "crypto";
14215
+ import { open as open5, stat as stat6 } from "fs/promises";
14216
+ import path11 from "path";
13861
14217
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13862
14218
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
13863
14219
  var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
@@ -13878,7 +14234,7 @@ var clamp = (value, fallback, min, max) => {
13878
14234
  return Math.min(max, Math.max(min, Math.floor(value)));
13879
14235
  };
13880
14236
  var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13881
- var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
14237
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path11.isAbsolute(transcriptPath) && path11.extname(transcriptPath) === ".jsonl";
13882
14238
  var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
13883
14239
  var assistantRecordOf = (line, agentId) => {
13884
14240
  if (!line.includes('"assistant"')) {
@@ -13958,7 +14314,7 @@ var withRegularFile = async (transcriptPath, body) => {
13958
14314
  }
13959
14315
  let handle;
13960
14316
  try {
13961
- handle = await open4(transcriptPath, "r");
14317
+ handle = await open5(transcriptPath, "r");
13962
14318
  } catch {
13963
14319
  return { status: "unavailable", reason: "unreadable" };
13964
14320
  }
@@ -14078,7 +14434,7 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
14078
14434
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
14079
14435
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
14080
14436
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
14081
- var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
14437
+ var sourceDigest = (transcriptPath) => createHash6("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
14082
14438
  var SUBAGENT_STOP = "SubagentStop";
14083
14439
  var agentIdOf = (record) => {
14084
14440
  const agentId = record.agent_id ?? record.agentId;
@@ -14091,7 +14447,7 @@ var subagentCursorScope = (payload) => {
14091
14447
  return void 0;
14092
14448
  }
14093
14449
  const agentId = agentIdOf(record);
14094
- return agentId === void 0 ? void 0 : `agent-${createHash5("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14450
+ return agentId === void 0 ? void 0 : `agent-${createHash6("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14095
14451
  };
14096
14452
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
14097
14453
  const fileSize = async (transcriptPath) => {
@@ -14193,6 +14549,283 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
14193
14549
  });
14194
14550
  };
14195
14551
 
14552
+ // src/providers/codex/rollout-usage.ts
14553
+ import { createHash as createHash7 } from "crypto";
14554
+ import { open as open6, readdir as readdir4, stat as stat7 } from "fs/promises";
14555
+ import path12 from "path";
14556
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
14557
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
14558
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
14559
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
14560
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
14561
+ var ROLLOUT_LOOKUP_DAYS = 7;
14562
+ var MIN_BYTES = 65536;
14563
+ var MAX_RANGE_BYTES2 = 67108864;
14564
+ var MAX_TAIL_BYTES2 = 16777216;
14565
+ var MIN_TIMEOUT_MILLIS2 = 10;
14566
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
14567
+ var MAX_SETTLE_MILLIS = 1e3;
14568
+ var MAX_MODEL_ID_LENGTH2 = 256;
14569
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
14570
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
14571
+ var clamp2 = (value, fallback, min, max) => {
14572
+ if (value === void 0 || !Number.isFinite(value)) {
14573
+ return fallback;
14574
+ }
14575
+ return Math.min(max, Math.max(min, Math.floor(value)));
14576
+ };
14577
+ var asRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
14578
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path12.isAbsolute(value) && path12.extname(value) === ".jsonl";
14579
+ var sourceDigest2 = (rolloutPath) => createHash7("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
14580
+ var parseUsage = (value) => {
14581
+ const parsed = codexUsageSchema.safeParse(value);
14582
+ if (!parsed.success) {
14583
+ return void 0;
14584
+ }
14585
+ const usage = parsed.data;
14586
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
14587
+ };
14588
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
14589
+ var factsOf2 = (line) => {
14590
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
14591
+ const contextLine = line.includes('"turn_context"');
14592
+ if (!usageLine && !contextLine) {
14593
+ return void 0;
14594
+ }
14595
+ let parsed;
14596
+ try {
14597
+ parsed = JSON.parse(line);
14598
+ } catch {
14599
+ return void 0;
14600
+ }
14601
+ const record = asRecord8(parsed);
14602
+ const payload = asRecord8(record?.payload);
14603
+ if (record === void 0 || payload === void 0) {
14604
+ return void 0;
14605
+ }
14606
+ if (record.type === "turn_context") {
14607
+ const model = modelOf(payload.model);
14608
+ return model === void 0 ? void 0 : { model };
14609
+ }
14610
+ if (record.type === "event_msg" && payload.type === "token_count") {
14611
+ const info = asRecord8(payload.info) ?? payload;
14612
+ const usage = parseUsage(info.total_token_usage);
14613
+ return usage === void 0 ? void 0 : { usage };
14614
+ }
14615
+ if (record.type === "token_usage_record") {
14616
+ const usage = parseUsage(payload.thread_token_usage);
14617
+ return usage === void 0 ? void 0 : { usage };
14618
+ }
14619
+ return void 0;
14620
+ };
14621
+ var lastSnapshotIn = (lines) => {
14622
+ let usage;
14623
+ let model;
14624
+ for (const line of lines) {
14625
+ const facts = factsOf2(line.trim());
14626
+ if (facts === void 0) {
14627
+ continue;
14628
+ }
14629
+ if (facts.model !== void 0) {
14630
+ model = facts.model;
14631
+ }
14632
+ if (facts.usage !== void 0) {
14633
+ usage = facts.usage;
14634
+ }
14635
+ }
14636
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
14637
+ };
14638
+ var readBytes2 = async (handle, start, length) => {
14639
+ const buffer = Buffer.alloc(length);
14640
+ let filled = 0;
14641
+ while (filled < length) {
14642
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
14643
+ if (bytesRead === 0) {
14644
+ break;
14645
+ }
14646
+ filled += bytesRead;
14647
+ }
14648
+ return buffer.subarray(0, filled);
14649
+ };
14650
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
14651
+ let handle;
14652
+ try {
14653
+ const info = await stat7(rolloutPath);
14654
+ if (!info.isFile()) {
14655
+ return { status: "unavailable", reason: "not-a-file" };
14656
+ }
14657
+ handle = await open6(rolloutPath, "r");
14658
+ } catch {
14659
+ return { status: "unavailable", reason: "unreadable" };
14660
+ }
14661
+ try {
14662
+ const { size } = await handle.stat();
14663
+ let start;
14664
+ if (fromOffset === void 0) {
14665
+ start = Math.max(0, size - tailBytes);
14666
+ } else if (size < fromOffset) {
14667
+ return { status: "unavailable", reason: "truncated" };
14668
+ } else if (size - fromOffset > maxRangeBytes) {
14669
+ return { status: "unavailable", reason: "over-cap" };
14670
+ } else {
14671
+ start = fromOffset;
14672
+ }
14673
+ const bytes = await readBytes2(handle, start, size - start);
14674
+ const lastNewline = bytes.lastIndexOf(10);
14675
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
14676
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
14677
+ if (fromOffset === void 0 && start > 0) {
14678
+ lines.shift();
14679
+ }
14680
+ const snapshot = lastSnapshotIn(lines);
14681
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
14682
+ } catch {
14683
+ return { status: "unavailable", reason: "unreadable" };
14684
+ } finally {
14685
+ await handle.close().catch(() => void 0);
14686
+ }
14687
+ };
14688
+ var pad = (value) => String(value).padStart(2, "0");
14689
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
14690
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path12.isAbsolute(sessionsRoot)) {
14691
+ return void 0;
14692
+ }
14693
+ const suffix = `-${sessionId}.jsonl`;
14694
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
14695
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
14696
+ const dir = path12.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
14697
+ let names;
14698
+ try {
14699
+ names = await readdir4(dir);
14700
+ } catch {
14701
+ continue;
14702
+ }
14703
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
14704
+ continue;
14705
+ }
14706
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
14707
+ if (match !== void 0) {
14708
+ return path12.join(dir, match);
14709
+ }
14710
+ }
14711
+ return void 0;
14712
+ };
14713
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
14714
+ var withTimeout2 = async (work, timeoutMillis) => {
14715
+ let timer;
14716
+ const timeout = new Promise((resolve8) => {
14717
+ timer = setTimeout(() => {
14718
+ resolve8(TIMED_OUT2);
14719
+ }, timeoutMillis);
14720
+ timer.unref();
14721
+ });
14722
+ try {
14723
+ return await Promise.race([work, timeout]);
14724
+ } finally {
14725
+ clearTimeout(timer);
14726
+ }
14727
+ };
14728
+ var sleep2 = (millis) => new Promise((resolve8) => {
14729
+ setTimeout(resolve8, millis).unref();
14730
+ });
14731
+ var hasUsage2 = (record) => record.usage !== void 0;
14732
+ var createCodexRolloutUsageEnricher = (options = {}) => {
14733
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
14734
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
14735
+ const timeoutMillis = clamp2(
14736
+ options.timeoutMillis,
14737
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
14738
+ MIN_TIMEOUT_MILLIS2,
14739
+ MAX_TIMEOUT_MILLIS2
14740
+ );
14741
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
14742
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
14743
+ const fileSize = async (rolloutPath) => {
14744
+ try {
14745
+ const info = await stat7(rolloutPath);
14746
+ return info.isFile() ? info.size : void 0;
14747
+ } catch (thrown) {
14748
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
14749
+ }
14750
+ };
14751
+ const resolveRollout = async (record) => {
14752
+ const named = record.transcript_path;
14753
+ if (named !== void 0 && named !== null) {
14754
+ return isRolloutPath(named) ? named : void 0;
14755
+ }
14756
+ const sessionId = record.session_id;
14757
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
14758
+ return void 0;
14759
+ }
14760
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
14761
+ };
14762
+ const enrichWithin = async (input) => {
14763
+ const unchanged = { payload: input.payload };
14764
+ const record = asRecord8(input.payload);
14765
+ const eventName = record?.hook_event_name;
14766
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
14767
+ return unchanged;
14768
+ }
14769
+ const rolloutPath = await resolveRollout(record);
14770
+ if (rolloutPath === void 0) {
14771
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
14772
+ }
14773
+ const source = sourceDigest2(rolloutPath);
14774
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
14775
+ if (eventName === "SessionStart") {
14776
+ if (cursor !== void 0) {
14777
+ return unchanged;
14778
+ }
14779
+ const size = await fileSize(rolloutPath);
14780
+ if (size === void 0) {
14781
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
14782
+ }
14783
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
14784
+ }
14785
+ if (hasUsage2(record)) {
14786
+ const size = await fileSize(rolloutPath);
14787
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
14788
+ }
14789
+ const attach = (snapshot) => ({
14790
+ ...record,
14791
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
14792
+ usage: snapshot.usage
14793
+ });
14794
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
14795
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
14796
+ await sleep2(settleMillis);
14797
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
14798
+ }
14799
+ if (read.status === "unavailable") {
14800
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
14801
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
14802
+ }
14803
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
14804
+ if (read.status === "unavailable") {
14805
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
14806
+ }
14807
+ }
14808
+ const next = { source, offset: read.endOffset };
14809
+ if (read.snapshot === void 0) {
14810
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
14811
+ }
14812
+ return {
14813
+ payload: attach(read.snapshot),
14814
+ cursor: next,
14815
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
14816
+ };
14817
+ };
14818
+ const enrich = async (input) => {
14819
+ try {
14820
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
14821
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
14822
+ } catch {
14823
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
14824
+ }
14825
+ };
14826
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
14827
+ };
14828
+
14196
14829
  // src/runtime/hook.ts
14197
14830
  import { z as z24 } from "zod";
14198
14831
 
@@ -14226,9 +14859,9 @@ var resolveDeliveryIdentity = (input) => {
14226
14859
  };
14227
14860
 
14228
14861
  // src/runtime/ids.ts
14229
- import { createHash as createHash6, randomUUID } from "crypto";
14862
+ import { createHash as createHash8, randomUUID } from "crypto";
14230
14863
  var digest2 = (namespace, parts) => {
14231
- const hash = createHash6("sha256");
14864
+ const hash = createHash8("sha256");
14232
14865
  hash.update(namespace);
14233
14866
  for (const part of parts) {
14234
14867
  hash.update("\0");
@@ -14267,16 +14900,16 @@ var createDeterministicIdGenerator = (options = {}) => {
14267
14900
  };
14268
14901
 
14269
14902
  // src/runtime/target-resolution.ts
14270
- import * as path11 from "path";
14903
+ import * as path13 from "path";
14271
14904
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
14272
14905
  var absolutePathsOf = (hint) => {
14273
- const base = hint.baseDirectory !== void 0 && path11.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
14906
+ const base = hint.baseDirectory !== void 0 && path13.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
14274
14907
  const resolved = [];
14275
14908
  for (const candidate of hint.paths) {
14276
- if (path11.isAbsolute(candidate)) {
14277
- resolved.push(path11.resolve(candidate));
14909
+ if (path13.isAbsolute(candidate)) {
14910
+ resolved.push(path13.resolve(candidate));
14278
14911
  } else if (base !== void 0) {
14279
- resolved.push(path11.resolve(base, candidate));
14912
+ resolved.push(path13.resolve(base, candidate));
14280
14913
  } else {
14281
14914
  return void 0;
14282
14915
  }
@@ -14355,8 +14988,8 @@ var resolveEventTargets = async (input) => {
14355
14988
  };
14356
14989
 
14357
14990
  // src/runtime/session-context.ts
14358
- import { open as open5 } from "fs/promises";
14359
- import * as path12 from "path";
14991
+ import { open as open7 } from "fs/promises";
14992
+ import * as path14 from "path";
14360
14993
  import { z as z23 } from "zod";
14361
14994
  var SESSION_CONTEXT_FILE_VERSION = 1;
14362
14995
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
@@ -14374,10 +15007,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
14374
15007
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
14375
15008
  var sessionContextFilePath = (dir, providerId, sessionId) => {
14376
15009
  const tool = sessionContextAgentTool(providerId);
14377
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path12.isAbsolute(dir)) {
15010
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path14.isAbsolute(dir)) {
14378
15011
  return void 0;
14379
15012
  }
14380
- return path12.join(dir, tool, `${sessionId}.json`);
15013
+ return path14.join(dir, tool, `${sessionId}.json`);
14381
15014
  };
14382
15015
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
14383
15016
  "session.id",
@@ -14473,7 +15106,7 @@ var stampSessionContext = (events, segments) => events.map((event3) => {
14473
15106
  var readBounded = async (file, maxBytes) => {
14474
15107
  let handle;
14475
15108
  try {
14476
- handle = await open5(file, "r");
15109
+ handle = await open7(file, "r");
14477
15110
  } catch {
14478
15111
  return void 0;
14479
15112
  }
@@ -15426,8 +16059,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
15426
16059
  };
15427
16060
 
15428
16061
  // src/runtime/git-worktree.ts
15429
- import { lstat, open as open6, stat as stat7 } from "fs/promises";
15430
- import * as path13 from "path";
16062
+ import { lstat, open as open8, stat as stat8 } from "fs/promises";
16063
+ import * as path15 from "path";
15431
16064
  var MAX_WORKTREE_WALK_DEPTH = 128;
15432
16065
  var MAX_GIT_FILE_BYTES = 4096;
15433
16066
  var MAX_CACHE_ENTRIES = 1024;
@@ -15438,7 +16071,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
15438
16071
  var readBounded2 = async (filePath) => {
15439
16072
  let handle;
15440
16073
  try {
15441
- handle = await open6(filePath, "r");
16074
+ handle = await open8(filePath, "r");
15442
16075
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
15443
16076
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
15444
16077
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -15459,7 +16092,7 @@ var parseHeadBranch = (head) => {
15459
16092
  return branch;
15460
16093
  };
15461
16094
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
15462
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path13.resolve(base, target);
16095
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path15.resolve(base, target);
15463
16096
  var parseGitDirFile = (content, worktreeRoot) => {
15464
16097
  const line = firstLine(content);
15465
16098
  return resolveGitPath(
@@ -15479,26 +16112,26 @@ var isMissing = async (filePath) => {
15479
16112
  };
15480
16113
  var isDirectory = async (directory) => {
15481
16114
  try {
15482
- return (await stat7(directory)).isDirectory();
16115
+ return (await stat8(directory)).isDirectory();
15483
16116
  } catch {
15484
16117
  return false;
15485
16118
  }
15486
16119
  };
15487
16120
  var repositoryOf = async (worktreeRoot, gitDir) => {
15488
- const commonDirFile = path13.join(gitDir, "commondir");
16121
+ const commonDirFile = path15.join(gitDir, "commondir");
15489
16122
  const content = await readBounded2(commonDirFile);
15490
16123
  if (content === void 0) {
15491
16124
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
15492
16125
  }
15493
16126
  const commonDir = parseCommonDirFile(content, gitDir);
15494
- const mainRoot = commonDir !== void 0 && path13.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path13.dirname(commonDir) : void 0;
16127
+ const mainRoot = commonDir !== void 0 && path15.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path15.dirname(commonDir) : void 0;
15495
16128
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
15496
16129
  };
15497
16130
  var probeDirectory = async (directory) => {
15498
- const dotGit = path13.join(directory, ".git");
16131
+ const dotGit = path15.join(directory, ".git");
15499
16132
  let info;
15500
16133
  try {
15501
- info = await stat7(dotGit);
16134
+ info = await stat8(dotGit);
15502
16135
  } catch {
15503
16136
  return ABSENT;
15504
16137
  }
@@ -15512,7 +16145,7 @@ var probeDirectory = async (directory) => {
15512
16145
  if (gitDir === void 0) {
15513
16146
  return INVALID;
15514
16147
  }
15515
- const head = await readBounded2(path13.join(gitDir, "HEAD"));
16148
+ const head = await readBounded2(path15.join(gitDir, "HEAD"));
15516
16149
  if (head === void 0) {
15517
16150
  return INVALID;
15518
16151
  }
@@ -15542,10 +16175,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15542
16175
  };
15543
16176
  const locate = async (absolutePath) => {
15544
16177
  try {
15545
- if (!path13.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16178
+ if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15546
16179
  return void 0;
15547
16180
  }
15548
- let directory = path13.resolve(absolutePath);
16181
+ let directory = path15.resolve(absolutePath);
15549
16182
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
15550
16183
  const probe = await cachedProbe(directory);
15551
16184
  if (probe.kind === "worktree") {
@@ -15554,7 +16187,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15554
16187
  if (probe.kind === "invalid") {
15555
16188
  return void 0;
15556
16189
  }
15557
- const parent = path13.dirname(directory);
16190
+ const parent = path15.dirname(directory);
15558
16191
  if (parent === directory) {
15559
16192
  return void 0;
15560
16193
  }
@@ -15680,7 +16313,14 @@ var createHookRuntime = (options) => {
15680
16313
  privacy,
15681
16314
  logger,
15682
16315
  installationId: options.installationId,
15683
- payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
16316
+ payloadEnrichers: options.payloadEnrichers ?? [
16317
+ ...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
16318
+ ...readsCodexRolloutUsage(options.config) ? [
16319
+ createCodexRolloutUsageEnricher(
16320
+ options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
16321
+ )
16322
+ ] : []
16323
+ ],
15684
16324
  ...(() => {
15685
16325
  if (options.sessionContextReader === null) {
15686
16326
  return {};
@@ -16222,6 +16862,14 @@ var readBoundedJson = async (stream, maxBytes) => {
16222
16862
  };
16223
16863
 
16224
16864
  // src/cli/run.ts
16865
+ var codexSessionsRoot = (env) => {
16866
+ const codexHome = env.CODEX_HOME;
16867
+ if (codexHome !== void 0 && codexHome.length > 0) {
16868
+ return path16.isAbsolute(codexHome) ? path16.join(codexHome, "sessions") : void 0;
16869
+ }
16870
+ const home = env.HOME;
16871
+ return home !== void 0 && path16.isAbsolute(home) ? path16.join(home, ".codex", "sessions") : void 0;
16872
+ };
16225
16873
  var MAX_LOGGED_DIAGNOSTICS = 16;
16226
16874
  var logDiagnostics = (logger, diagnostics) => {
16227
16875
  for (const info of diagnostics.slice(0, MAX_LOGGED_DIAGNOSTICS)) {
@@ -16356,13 +17004,13 @@ var runHookCommand = async (command, io) => {
16356
17004
  }
16357
17005
  const identityClaims = [];
16358
17006
  if (command.identity.identityFile !== void 0) {
16359
- const read = await readIdentityFile(path14.resolve(command.identity.identityFile));
17007
+ const read = await readIdentityFile(path16.resolve(command.identity.identityFile));
16360
17008
  if ("error" in read) {
16361
17009
  logDiagnostics(logger, [read.error]);
16362
17010
  } else {
16363
17011
  const fromFile = claimFromIdentityFile(
16364
17012
  read.value,
16365
- path14.basename(command.identity.identityFile)
17013
+ path16.basename(command.identity.identityFile)
16366
17014
  );
16367
17015
  logDiagnostics(logger, fromFile.errors);
16368
17016
  identityClaims.push(...fromFile.claims);
@@ -16372,6 +17020,7 @@ var runHookCommand = async (command, io) => {
16372
17020
  logDiagnostics(logger, fromFlags.errors);
16373
17021
  identityClaims.push(...fromFlags.claims);
16374
17022
  const headers = resolveCliExporterHeaders(command.policy, io);
17023
+ const codexSessions = codexSessionsRoot(io.env);
16375
17024
  const runtime = createHookRuntime({
16376
17025
  // Detection policy narrowed to the selected adapter; everything else is the
16377
17026
  // resolved configuration exactly as it stands.
@@ -16391,6 +17040,7 @@ var runHookCommand = async (command, io) => {
16391
17040
  privacy,
16392
17041
  ...command.policy.flushTimeoutMillis === void 0 ? {} : { flushTimeoutMillis: command.policy.flushTimeoutMillis },
16393
17042
  ...command.policy.spoolDisabled === true ? { enableSpool: false } : {},
17043
+ ...codexSessions === void 0 ? {} : { codexSessionsRoot: codexSessions },
16394
17044
  ...command.requireCallbackId === true ? { requireCallbackId: true } : {},
16395
17045
  ...command.noDeriveCallbackId === true ? { deriveDeliveryIdentity: false } : {}
16396
17046
  });