@osfactory/otel-hook 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +51 -3
  2. package/dist/cli.js +907 -164
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config.d.ts +5 -3
  5. package/dist/config.js +39 -5
  6. package/dist/config.js.map +1 -1
  7. package/dist/{destinations-DvqsPulb.d.ts → destinations-C4sSKjDO.d.ts} +1 -1
  8. package/dist/{export-destinations-Bey2djRk.d.ts → export-destinations-BjRXDots.d.ts} +37 -5
  9. package/dist/{hook-D5imE0Qc.d.ts → hook-CKLpgrYP.d.ts} +2 -2
  10. package/dist/index.d.ts +9 -9
  11. package/dist/index.js +921 -182
  12. package/dist/index.js.map +1 -1
  13. package/dist/install.d.ts +1 -1
  14. package/dist/install.js +5 -1
  15. package/dist/install.js.map +1 -1
  16. package/dist/integration.d.ts +15 -8
  17. package/dist/integration.js +998 -160
  18. package/dist/integration.js.map +1 -1
  19. package/dist/lifecycle.d.ts +8 -1
  20. package/dist/lifecycle.js +10 -3
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{metric-model-CFIeUwqd.d.ts → metric-model-B4lIuk6i.d.ts} +8 -0
  23. package/dist/{payload-CdDKeRpH.d.ts → payload-DLK7QaBB.d.ts} +17 -1
  24. package/dist/providers.d.ts +91 -6
  25. package/dist/providers.js +311 -4
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-BKQhhIO3.d.ts → registry-DM-4YvIA.d.ts} +1 -1
  28. package/dist/runtime.d.ts +3 -3
  29. package/dist/runtime.js +23 -3
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/{schema-SpFM6YQY.d.ts → schema-CD61uW99.d.ts} +32 -3
  32. package/dist/state.js +20 -6
  33. package/dist/state.js.map +1 -1
  34. package/dist/telemetry.d.ts +4 -4
  35. package/dist/telemetry.js +865 -472
  36. package/dist/telemetry.js.map +1 -1
  37. package/dist/testing.d.ts +3 -3
  38. package/dist/testing.js +61 -21
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +2 -1
package/dist/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
  };
@@ -3218,8 +3261,8 @@ var createCliLogger = (io, level) => createStderrLogger({
3218
3261
  var readIdentityFile = readJsonFile;
3219
3262
 
3220
3263
  // src/cli/doctor.ts
3221
- import { readdir as readdir3, stat as stat2 } from "fs/promises";
3222
- import * as path4 from "path";
3264
+ import { readdir as readdir3, stat as stat3 } from "fs/promises";
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);
@@ -4243,7 +4286,10 @@ var postToolUseFailurePayloadSchema = z19.object({
4243
4286
  hook_event_name: z19.literal("PostToolUseFailure"),
4244
4287
  tool_name: z19.string().min(1),
4245
4288
  tool_input: z19.unknown().optional(),
4246
- tool_error: z19.unknown(),
4289
+ // Optional: a failure that names no message still ends its tool call. The
4290
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
4291
+ // `normalizeClaudeHookPayload`.
4292
+ tool_error: z19.unknown().optional(),
4247
4293
  tool_use_id: z19.string().min(1)
4248
4294
  });
4249
4295
  var permissionRequestPayloadSchema = z19.object({
@@ -4612,7 +4658,13 @@ var normalizeClaudeHookPayload = (payload) => {
4612
4658
  if (record === void 0) {
4613
4659
  return payload;
4614
4660
  }
4615
- return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
4661
+ return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));
4662
+ };
4663
+ var applyToolFailureShape = (record) => {
4664
+ if (record.hook_event_name !== "PostToolUseFailure" || record.tool_error !== void 0 || record.error === void 0) {
4665
+ return record;
4666
+ }
4667
+ return { ...record, tool_error: record.error };
4616
4668
  };
4617
4669
  var applyUsageShape = (record) => {
4618
4670
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -5188,6 +5240,7 @@ var permissionModeSchema = z20.enum([
5188
5240
  var codexUsageSchema = z20.object({
5189
5241
  input_tokens: z20.number().int().min(0).optional(),
5190
5242
  cached_input_tokens: z20.number().int().min(0).optional(),
5243
+ cache_write_input_tokens: z20.number().int().min(0).optional(),
5191
5244
  output_tokens: z20.number().int().min(0).optional(),
5192
5245
  reasoning_output_tokens: z20.number().int().min(0).optional(),
5193
5246
  total_tokens: z20.number().int().min(0).optional()
@@ -5443,6 +5496,10 @@ var codexUsageToReport = (usage, temporality) => ({
5443
5496
  temporality,
5444
5497
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
5445
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
+ },
5446
5503
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
5447
5504
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
5448
5505
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -5471,8 +5528,9 @@ var CODEX_CAPABILITIES = Object.freeze({
5471
5528
  // turn; see docs/usage-semantics.md.
5472
5529
  cumulativeUsageSeries: "session-lifetime",
5473
5530
  reportsCachedInput: true,
5474
- reportsCacheCreation: false,
5475
- 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",
5476
5534
  reportsReasoningOutput: true,
5477
5535
  reportsProviderTotal: true,
5478
5536
  reportsCost: false,
@@ -7677,7 +7735,7 @@ var createSystemClock = () => ({
7677
7735
 
7678
7736
  // src/state/filesystem-store.ts
7679
7737
  import { randomBytes } from "crypto";
7680
- import { mkdir, open, readFile as readFile2, readdir, rename, unlink, writeFile } from "fs/promises";
7738
+ import { mkdir, open, readFile as readFile2, readdir, rename, stat, unlink, writeFile } from "fs/promises";
7681
7739
  import * as path2 from "path";
7682
7740
 
7683
7741
  // src/state/async-lock.ts
@@ -7778,8 +7836,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7778
7836
  // src/state/filesystem-store.ts
7779
7837
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
7780
7838
  var sleep = (millis) => new Promise((resolve8) => {
7781
- const timer = setTimeout(resolve8, millis);
7782
- timer.unref?.();
7839
+ setTimeout(resolve8, millis);
7783
7840
  });
7784
7841
  var wrapFsError = (thrown, operation) => {
7785
7842
  if (thrown instanceof Error) {
@@ -7899,14 +7956,29 @@ var createFilesystemStateStore = (options) => {
7899
7956
  }
7900
7957
  }
7901
7958
  const stale = await (async () => {
7959
+ let raw;
7960
+ try {
7961
+ raw = await readFile2(filePath, "utf8");
7962
+ } catch (thrown) {
7963
+ return isErrnoException(thrown, "ENOENT") ? "gone" : true;
7964
+ }
7902
7965
  try {
7903
- const raw = await readFile2(filePath, "utf8");
7904
7966
  const parsed = JSON.parse(raw);
7905
- return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
7967
+ if (typeof parsed.acquiredAt === "number") {
7968
+ return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
7969
+ }
7906
7970
  } catch {
7907
- return true;
7971
+ }
7972
+ try {
7973
+ const stats = await stat(filePath);
7974
+ return Date.now() - stats.mtimeMs > lockStaleMillis;
7975
+ } catch {
7976
+ return "gone";
7908
7977
  }
7909
7978
  })();
7979
+ if (stale === "gone") {
7980
+ continue;
7981
+ }
7910
7982
  if (stale) {
7911
7983
  await unlink(filePath).catch(() => void 0);
7912
7984
  continue;
@@ -8043,7 +8115,7 @@ var createFilesystemStateStore = (options) => {
8043
8115
 
8044
8116
  // src/telemetry/spool-queue.ts
8045
8117
  import { randomBytes as randomBytes2 } from "crypto";
8046
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, stat, 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";
8047
8119
  import * as path3 from "path";
8048
8120
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
8049
8121
  total: 0,
@@ -8089,7 +8161,7 @@ var readSpoolQueueStats = async (queueDir) => {
8089
8161
  let bytes = 0;
8090
8162
  for (const file of files) {
8091
8163
  try {
8092
- bytes += (await stat(path3.join(queueDir, file))).size;
8164
+ bytes += (await stat2(path3.join(queueDir, file))).size;
8093
8165
  } catch {
8094
8166
  }
8095
8167
  }
@@ -8102,7 +8174,52 @@ var readSpoolQueueStats = async (queueDir) => {
8102
8174
  };
8103
8175
  };
8104
8176
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
8177
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
8178
+ var CLAIM_SUFFIX = ".claim";
8179
+ var RELEASING_SUFFIX = ".releasing";
8180
+ var isClaimOwnerAlive = (pid) => {
8181
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
8182
+ return true;
8183
+ }
8184
+ if (pid === process.pid) {
8185
+ return true;
8186
+ }
8187
+ try {
8188
+ process.kill(pid, 0);
8189
+ return true;
8190
+ } catch (thrown) {
8191
+ return thrown?.code !== "ESRCH";
8192
+ }
8193
+ };
8105
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
+ };
8106
8223
  var createSpoolQueue = (options) => {
8107
8224
  const [providerSegment, installationSegment] = namespaceSegments(options);
8108
8225
  const queueDir = path3.join(options.rootDir, providerSegment, installationSegment, options.queueName);
@@ -8171,7 +8288,7 @@ var createSpoolQueue = (options) => {
8171
8288
  let bytes = 0;
8172
8289
  if (options.maxBytes !== void 0) {
8173
8290
  try {
8174
- bytes = (await stat(path3.join(queueDir, name))).size;
8291
+ bytes = (await stat2(path3.join(queueDir, name))).size;
8175
8292
  } catch {
8176
8293
  continue;
8177
8294
  }
@@ -8251,9 +8368,63 @@ var createSpoolQueue = (options) => {
8251
8368
  await rename2(tmp, target);
8252
8369
  return { spooled: true };
8253
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
+ };
8384
+ const releaseStaleClaims = async () => {
8385
+ let entries;
8386
+ try {
8387
+ entries = await readdir2(queueDir);
8388
+ } catch {
8389
+ return;
8390
+ }
8391
+ const now = Date.now();
8392
+ for (const entry of entries) {
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
+ }
8406
+ }
8407
+ }
8408
+ };
8409
+ const claimBatch = async (claimPath) => {
8410
+ const token = randomBytes2(16).toString("hex");
8411
+ try {
8412
+ const handle = await open2(claimPath, "wx");
8413
+ try {
8414
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
8415
+ await handle.writeFile(JSON.stringify(contents), "utf8");
8416
+ } finally {
8417
+ await handle.close();
8418
+ }
8419
+ return token;
8420
+ } catch {
8421
+ return void 0;
8422
+ }
8423
+ };
8254
8424
  const drain = async (send, drainOptions) => {
8255
8425
  await ensureDirs();
8256
8426
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
8427
+ await releaseStaleClaims();
8257
8428
  let files = await listSorted();
8258
8429
  if (options.maxAgeMillis !== void 0) {
8259
8430
  const now = options.clock.now();
@@ -8271,12 +8442,7 @@ var createSpoolQueue = (options) => {
8271
8442
  let failed = 0;
8272
8443
  let quarantined = 0;
8273
8444
  let index = 0;
8274
- for (; index < files.length && index < cap; index += 1) {
8275
- const fileName = files[index];
8276
- if (fileName === void 0) {
8277
- break;
8278
- }
8279
- const filePath = path3.join(queueDir, fileName);
8445
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
8280
8446
  const quarantine = async (rejection) => {
8281
8447
  quarantined += 1;
8282
8448
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -8290,12 +8456,22 @@ var createSpoolQueue = (options) => {
8290
8456
  await unlink2(filePath).catch(() => void 0);
8291
8457
  }
8292
8458
  };
8459
+ let text;
8460
+ try {
8461
+ text = await readFile3(filePath, "utf8");
8462
+ } catch (thrown) {
8463
+ if (thrown?.code === "ENOENT") {
8464
+ return "next";
8465
+ }
8466
+ await quarantine("unreadable");
8467
+ return "next";
8468
+ }
8293
8469
  let parsed;
8294
8470
  try {
8295
- parsed = JSON.parse(await readFile3(filePath, "utf8"));
8471
+ parsed = JSON.parse(text);
8296
8472
  } catch {
8297
8473
  await quarantine("unparseable-json");
8298
- continue;
8474
+ return "next";
8299
8475
  }
8300
8476
  const validation = options.validate(parsed, {
8301
8477
  providerId: options.providerId,
@@ -8303,7 +8479,10 @@ var createSpoolQueue = (options) => {
8303
8479
  });
8304
8480
  if ("rejection" in validation) {
8305
8481
  await quarantine(validation.rejection);
8306
- continue;
8482
+ return "next";
8483
+ }
8484
+ if ((await readClaim(claimPath))?.token !== token) {
8485
+ return "next";
8307
8486
  }
8308
8487
  let delivered;
8309
8488
  try {
@@ -8315,13 +8494,34 @@ var createSpoolQueue = (options) => {
8315
8494
  if (await unlink2(filePath).then(() => true, () => false)) {
8316
8495
  await recordDrops("rejected", 1);
8317
8496
  }
8318
- continue;
8497
+ return "next";
8319
8498
  }
8320
8499
  if (delivered) {
8321
8500
  await unlink2(filePath).catch(() => void 0);
8322
8501
  drained += 1;
8323
- } else {
8324
- 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") {
8325
8525
  break;
8326
8526
  }
8327
8527
  }
@@ -8538,7 +8738,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
8538
8738
 
8539
8739
  // src/telemetry/otlp-log-sink.ts
8540
8740
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
8541
- import { ExportResultCode } from "@opentelemetry/core";
8741
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
8542
8742
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
8543
8743
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
8544
8744
 
@@ -8549,6 +8749,217 @@ var isPermanentExportFailure = (result) => {
8549
8749
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
8550
8750
  };
8551
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
+
8552
8963
  // src/telemetry/exporter-resource.ts
8553
8964
  import { resourceFromAttributes } from "@opentelemetry/resources";
8554
8965
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -8719,7 +9130,7 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8719
9130
  };
8720
9131
 
8721
9132
  // src/telemetry/semconv.ts
8722
- import { createHash as createHash3 } from "crypto";
9133
+ import { createHash as createHash4 } from "crypto";
8723
9134
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
8724
9135
  import { millisToHrTime } from "@opentelemetry/core";
8725
9136
  import {
@@ -8738,7 +9149,7 @@ import {
8738
9149
  } from "@opentelemetry/semantic-conventions/incubating";
8739
9150
 
8740
9151
  // src/version.ts
8741
- var VERSION = "0.13.0";
9152
+ var VERSION = "0.13.2";
8742
9153
 
8743
9154
  // src/telemetry/semconv.ts
8744
9155
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8759,7 +9170,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
8759
9170
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
8760
9171
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
8761
9172
  var FIELD_SEPARATOR = "\0";
8762
- 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);
8763
9174
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
8764
9175
  var familyOf = (type) => {
8765
9176
  switch (type) {
@@ -8974,7 +9385,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8974
9385
  const resolved = resolvePairing(group, anchor, correlation);
8975
9386
  const traceId = plan.traceId;
8976
9387
  const spanId = plan.spanId;
8977
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
9388
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
9389
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
8978
9390
  let name = group.ref.family;
8979
9391
  let kind = SpanKind.INTERNAL;
8980
9392
  let status = { code: SpanStatusCode.UNSET };
@@ -9198,7 +9610,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
9198
9610
  // persist something that should have been persisted.
9199
9611
  correlation === void 0 && correlationAvailable === void 0);
9200
9612
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
9201
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
9613
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
9202
9614
  return {
9203
9615
  group,
9204
9616
  anchor,
@@ -9218,6 +9630,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
9218
9630
  )
9219
9631
  };
9220
9632
  };
9633
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9634
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9221
9635
  var canonicalEventTraceIdentities = (events, options = {}) => {
9222
9636
  const layout = layoutBatch(events);
9223
9637
  const correlations = indexCorrelations(options.correlations);
@@ -9242,7 +9656,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
9242
9656
  });
9243
9657
  continue;
9244
9658
  }
9245
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
9659
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3) ?? resumedSessionParent(plan.group.ref, plan.correlation);
9246
9660
  identities.set(event3.eventId, {
9247
9661
  traceId: plan.traceId,
9248
9662
  spanId: plan.spanId,
@@ -9762,12 +10176,16 @@ var createOtlpLogSink = (options) => {
9762
10176
  const exporter = new OTLPLogExporter({
9763
10177
  url: deliverability.endpoint,
9764
10178
  headers: { ...options.headers },
9765
- timeoutMillis: options.exporter.timeoutMillis
10179
+ ...boundedExporterOptions(options.exporter)
9766
10180
  });
10181
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
9767
10182
  let shutdownCompleted = false;
9768
- const exportRecords = (records) => new Promise((resolve8) => {
9769
- exporter.export([...records], (result) => resolve8(result));
9770
- });
10183
+ const exportRecords = (records) => guardExport(
10184
+ gate,
10185
+ () => new Promise((resolve8) => {
10186
+ exporter.export([...records], (result) => resolve8(result));
10187
+ })
10188
+ );
9771
10189
  const toSpoolBatch = (records, batchResource) => ({
9772
10190
  providerId: options.providerId,
9773
10191
  installationId: options.installationId,
@@ -9785,7 +10203,7 @@ var createOtlpLogSink = (options) => {
9785
10203
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
9786
10204
  );
9787
10205
  const result = await exportRecords(records);
9788
- if (result.code === ExportResultCode.SUCCESS) {
10206
+ if (result.code === ExportResultCode2.SUCCESS) {
9789
10207
  return true;
9790
10208
  }
9791
10209
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -9831,11 +10249,11 @@ var createOtlpLogSink = (options) => {
9831
10249
  result = await exportRecords(batch);
9832
10250
  } catch (thrown) {
9833
10251
  result = {
9834
- code: ExportResultCode.FAILED,
10252
+ code: ExportResultCode2.FAILED,
9835
10253
  error: thrown instanceof Error ? thrown : new Error("export threw")
9836
10254
  };
9837
10255
  }
9838
- if (result.code === ExportResultCode.SUCCESS) {
10256
+ if (result.code === ExportResultCode2.SUCCESS) {
9839
10257
  accepted += batch.length;
9840
10258
  health.recordSuccess(batch.length, options.clock.now());
9841
10259
  continue;
@@ -9876,6 +10294,9 @@ var createOtlpLogSink = (options) => {
9876
10294
  if (options.spool === void 0) {
9877
10295
  return { drained: 0, remaining: 0, failed: 0 };
9878
10296
  }
10297
+ if (gate !== void 0 && !await gate.available()) {
10298
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
10299
+ }
9879
10300
  const result = await options.spool.drain(sendSerializedBatch, {
9880
10301
  ...maxBatches === void 0 ? {} : { maxBatches }
9881
10302
  });
@@ -9912,7 +10333,7 @@ var createOtlpLogSink = (options) => {
9912
10333
  };
9913
10334
 
9914
10335
  // src/telemetry/otlp-sink.ts
9915
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
10336
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
9916
10337
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
9917
10338
  var chunk2 = (items, size) => {
9918
10339
  if (size <= 0 || items.length <= size) {
@@ -9990,12 +10411,16 @@ var createOtlpTraceSink = (options) => {
9990
10411
  const exporter = new OTLPTraceExporter({
9991
10412
  url: options.exporter.endpoint,
9992
10413
  headers: { ...options.headers },
9993
- timeoutMillis: options.exporter.timeoutMillis
10414
+ ...boundedExporterOptions(options.exporter)
9994
10415
  });
10416
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
9995
10417
  let shutdownCompleted = false;
9996
- const exportSpans = (spans) => new Promise((resolve8) => {
9997
- exporter.export([...spans], (result) => resolve8(result));
9998
- });
10418
+ const exportSpans = (spans) => guardExport(
10419
+ gate,
10420
+ () => new Promise((resolve8) => {
10421
+ exporter.export([...spans], (result) => resolve8(result));
10422
+ })
10423
+ );
9999
10424
  const toSpoolBatch = (spans, batchResource) => ({
10000
10425
  providerId: options.providerId,
10001
10426
  installationId: options.installationId,
@@ -10008,7 +10433,7 @@ var createOtlpTraceSink = (options) => {
10008
10433
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
10009
10434
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
10010
10435
  const result = await exportSpans(spans);
10011
- if (result.code === ExportResultCode2.SUCCESS) {
10436
+ if (result.code === ExportResultCode3.SUCCESS) {
10012
10437
  return true;
10013
10438
  }
10014
10439
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -10047,9 +10472,9 @@ var createOtlpTraceSink = (options) => {
10047
10472
  try {
10048
10473
  result = await exportSpans(batch);
10049
10474
  } catch (thrown) {
10050
- 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") };
10051
10476
  }
10052
- if (result.code === ExportResultCode2.SUCCESS) {
10477
+ if (result.code === ExportResultCode3.SUCCESS) {
10053
10478
  accepted += batch.length;
10054
10479
  health.recordSuccess(batch.length, options.clock.now());
10055
10480
  continue;
@@ -10086,6 +10511,9 @@ var createOtlpTraceSink = (options) => {
10086
10511
  if (options.spool === void 0) {
10087
10512
  return { drained: 0, remaining: 0, failed: 0 };
10088
10513
  }
10514
+ if (gate !== void 0 && !await gate.available()) {
10515
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
10516
+ }
10089
10517
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
10090
10518
  if (result.drained > 0) {
10091
10519
  health.recordSuccess(result.drained, options.clock.now());
@@ -10476,7 +10904,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
10476
10904
 
10477
10905
  // src/telemetry/otlp-metric-sink.ts
10478
10906
  import { ValueType } from "@opentelemetry/api";
10479
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10907
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10480
10908
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
10481
10909
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
10482
10910
  import {
@@ -10620,10 +11048,12 @@ var createOtlpMetricSink = (options) => {
10620
11048
  const exporter = new OTLPMetricExporter({
10621
11049
  url: deliverability.endpoint,
10622
11050
  headers: { ...options.headers },
10623
- timeoutMillis: options.exporter.timeoutMillis
11051
+ ...boundedExporterOptions(options.exporter)
10624
11052
  });
11053
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
10625
11054
  let shutdownCompleted = false;
10626
- 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) => {
10627
11057
  const payload = {
10628
11058
  resource: batchResource,
10629
11059
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -10632,7 +11062,7 @@ var createOtlpMetricSink = (options) => {
10632
11062
  exporter.export(payload, (result) => resolve8(result));
10633
11063
  } catch (thrown) {
10634
11064
  resolve8({
10635
- code: ExportResultCode3.FAILED,
11065
+ code: ExportResultCode4.FAILED,
10636
11066
  error: thrown instanceof Error ? thrown : new Error("export threw")
10637
11067
  });
10638
11068
  }
@@ -10653,7 +11083,7 @@ var createOtlpMetricSink = (options) => {
10653
11083
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
10654
11084
  );
10655
11085
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
10656
- if (result.code === ExportResultCode3.SUCCESS) {
11086
+ if (result.code === ExportResultCode4.SUCCESS) {
10657
11087
  return true;
10658
11088
  }
10659
11089
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -10664,7 +11094,7 @@ var createOtlpMetricSink = (options) => {
10664
11094
  }
10665
11095
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
10666
11096
  const result = await exportResourceMetrics(points, batchResource, scope);
10667
- if (result.code === ExportResultCode3.SUCCESS) {
11097
+ if (result.code === ExportResultCode4.SUCCESS) {
10668
11098
  health.recordSuccess(points.length, options.clock.now());
10669
11099
  return { accepted: points.length, rejected: 0, errors: [] };
10670
11100
  }
@@ -10704,6 +11134,9 @@ var createOtlpMetricSink = (options) => {
10704
11134
  if (options.spool === void 0) {
10705
11135
  return { drained: 0, remaining: 0, failed: 0 };
10706
11136
  }
11137
+ if (gate !== void 0 && !await gate.available()) {
11138
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
11139
+ }
10707
11140
  const result = await options.spool.drain(sendSerializedBatch, {
10708
11141
  ...maxBatches === void 0 ? {} : { maxBatches }
10709
11142
  });
@@ -10841,6 +11274,13 @@ var createExportDestinationSinks = (options) => {
10841
11274
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
10842
11275
  const destinations = [];
10843
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
+ });
10844
11284
  for (const destination of resolveExportDestinations(options.exporter)) {
10845
11285
  let headers;
10846
11286
  let logHeaders;
@@ -10900,6 +11340,7 @@ var createExportDestinationSinks = (options) => {
10900
11340
  const sinkShared = {
10901
11341
  exporter: policy,
10902
11342
  ...shared,
11343
+ endpointHealth,
10903
11344
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
10904
11345
  ...label === void 0 ? {} : { destination: label }
10905
11346
  };
@@ -10917,6 +11358,7 @@ var createExportDestinationSinks = (options) => {
10917
11358
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
10918
11359
  exporter: policy,
10919
11360
  ...shared,
11361
+ endpointHealth,
10920
11362
  ...label === void 0 ? {} : { destination: label },
10921
11363
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
10922
11364
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -11091,7 +11533,7 @@ var collectDoctorReport = async (command, io) => {
11091
11533
  let contextDirExists = false;
11092
11534
  if (contextDir !== void 0) {
11093
11535
  try {
11094
- contextDirExists = (await stat2(contextDir)).isDirectory();
11536
+ contextDirExists = (await stat3(contextDir)).isDirectory();
11095
11537
  } catch {
11096
11538
  contextDirExists = false;
11097
11539
  }
@@ -11099,7 +11541,7 @@ var collectDoctorReport = async (command, io) => {
11099
11541
  checks.push({
11100
11542
  name: "session-context",
11101
11543
  ok: true,
11102
- 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)"}`
11103
11545
  });
11104
11546
  const providers = describeProviderCatalog({
11105
11547
  includeExperimental: command.policy.includeExperimental ?? true
@@ -11197,7 +11639,7 @@ var inspectQueue = async (spool, queueName) => {
11197
11639
  const installation = sanitizeSegment(spool.installationId);
11198
11640
  const stats = await Promise.all(
11199
11641
  namespaces.map(
11200
- (namespace) => readSpoolQueueStats(path4.join(spool.rootDir, namespace, installation, queueName))
11642
+ (namespace) => readSpoolQueueStats(path5.join(spool.rootDir, namespace, installation, queueName))
11201
11643
  )
11202
11644
  );
11203
11645
  return stats.length === 0 ? { batches: 0, bytes: 0, dropped: EMPTY_SPOOL_DROP_COUNTS } : sumSpoolStats(stats);
@@ -12142,7 +12584,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
12142
12584
  );
12143
12585
 
12144
12586
  // src/install/scopes.ts
12145
- import * as path5 from "path";
12587
+ import * as path6 from "path";
12146
12588
  var REGISTRATION_SCOPES = Object.freeze([
12147
12589
  "global",
12148
12590
  "project"
@@ -12210,15 +12652,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
12210
12652
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
12211
12653
  (entry) => entry.providerId === providerId && entry.scope === scope
12212
12654
  );
12213
- var resolveInstallPath = (location, roots) => path5.resolve(
12655
+ var resolveInstallPath = (location, roots) => path6.resolve(
12214
12656
  location.scope === "global" ? roots.homeDir : roots.projectDir,
12215
12657
  ...location.segments
12216
12658
  );
12217
12659
 
12218
12660
  // src/install/document.ts
12219
- import { randomBytes as randomBytes3 } from "crypto";
12220
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
12221
- 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";
12222
12664
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12223
12665
  indent: " ",
12224
12666
  eol: "\n",
@@ -12242,7 +12684,7 @@ var renderJsonDocument = (value, format) => {
12242
12684
  var readJsonDocument = async (filePath) => {
12243
12685
  let raw;
12244
12686
  try {
12245
- raw = await readFile4(filePath, "utf8");
12687
+ raw = await readFile5(filePath, "utf8");
12246
12688
  } catch (thrown) {
12247
12689
  if (isErrnoException3(thrown, "ENOENT")) {
12248
12690
  return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
@@ -12274,7 +12716,7 @@ var delay = (millis) => new Promise((resolve8) => {
12274
12716
  var renameWithRetry = async (from, to) => {
12275
12717
  for (let attempt = 0; ; attempt += 1) {
12276
12718
  try {
12277
- await rename3(from, to);
12719
+ await rename4(from, to);
12278
12720
  return;
12279
12721
  } catch (thrown) {
12280
12722
  const retryable = isErrnoException3(thrown, "EPERM", "EACCES", "EBUSY");
@@ -12289,15 +12731,15 @@ var renameWithRetry = async (from, to) => {
12289
12731
  var NEW_DOCUMENT_MODE = 384;
12290
12732
  var TEMPORARY_DOCUMENT_MODE = 384;
12291
12733
  var writeDocumentAtomically = async (filePath, contents) => {
12292
- const directory = path6.dirname(filePath);
12293
- await mkdir3(directory, { recursive: true });
12294
- const temporary = path6.join(
12734
+ const directory = path7.dirname(filePath);
12735
+ await mkdir4(directory, { recursive: true });
12736
+ const temporary = path7.join(
12295
12737
  directory,
12296
- `.${path6.basename(filePath)}.${randomBytes3(6).toString("hex")}.tmp`
12738
+ `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
12297
12739
  );
12298
12740
  let existingMode;
12299
12741
  try {
12300
- existingMode = (await stat3(filePath)).mode & 4095;
12742
+ existingMode = (await stat4(filePath)).mode & 4095;
12301
12743
  } catch (thrown) {
12302
12744
  if (!isErrnoException3(thrown, "ENOENT")) {
12303
12745
  throw thrown;
@@ -12305,7 +12747,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12305
12747
  }
12306
12748
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
12307
12749
  try {
12308
- const handle = await open2(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12750
+ const handle = await open3(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12309
12751
  try {
12310
12752
  await handle.writeFile(contents, "utf8");
12311
12753
  await handle.sync();
@@ -12315,19 +12757,19 @@ var writeDocumentAtomically = async (filePath, contents) => {
12315
12757
  }
12316
12758
  await renameWithRetry(temporary, filePath);
12317
12759
  } catch (thrown) {
12318
- await unlink3(temporary).catch(() => void 0);
12760
+ await unlink4(temporary).catch(() => void 0);
12319
12761
  throw thrown;
12320
12762
  }
12321
12763
  };
12322
12764
 
12323
12765
  // src/install/file-lock.ts
12324
- import { randomBytes as randomBytes4 } from "crypto";
12325
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12326
- 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";
12327
12769
  var FileLockTimeoutError = class extends Error {
12328
12770
  constructor(lockPath, timeoutMillis) {
12329
12771
  super(
12330
- `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)}`
12331
12773
  );
12332
12774
  this.name = "FileLockTimeoutError";
12333
12775
  }
@@ -12338,7 +12780,7 @@ var isErrnoException4 = (thrown, code) => thrown instanceof Error && thrown.code
12338
12780
  var readLockContents = async (lockPath) => {
12339
12781
  let raw;
12340
12782
  try {
12341
- raw = await readFile5(lockPath, "utf8");
12783
+ raw = await readFile6(lockPath, "utf8");
12342
12784
  } catch {
12343
12785
  return void 0;
12344
12786
  }
@@ -12352,18 +12794,18 @@ var readLockContents = async (lockPath) => {
12352
12794
  var releaseIfOwned = async (lockPath, token) => {
12353
12795
  const tombstone = `${lockPath}.${token}.releasing`;
12354
12796
  try {
12355
- await rename4(lockPath, tombstone);
12797
+ await rename5(lockPath, tombstone);
12356
12798
  } catch {
12357
12799
  return false;
12358
12800
  }
12359
12801
  const captured = await readLockContents(tombstone);
12360
12802
  if (captured !== void 0 && captured.token !== token) {
12361
- await rename4(tombstone, lockPath).catch(async () => {
12803
+ await rename5(tombstone, lockPath).catch(async () => {
12362
12804
  await Promise.resolve();
12363
12805
  });
12364
12806
  return false;
12365
12807
  }
12366
- await unlink4(tombstone).catch(() => void 0);
12808
+ await unlink5(tombstone).catch(() => void 0);
12367
12809
  return true;
12368
12810
  };
12369
12811
  var delay2 = (millis) => new Promise((resolve8) => {
@@ -12372,7 +12814,7 @@ var delay2 = (millis) => new Promise((resolve8) => {
12372
12814
  var isStale = async (lockPath, clock, staleMillis) => {
12373
12815
  let raw;
12374
12816
  try {
12375
- raw = await readFile5(lockPath, "utf8");
12817
+ raw = await readFile6(lockPath, "utf8");
12376
12818
  } catch (thrown) {
12377
12819
  return { stale: !isErrnoException4(thrown, "ENOENT") };
12378
12820
  }
@@ -12387,7 +12829,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12387
12829
  } catch {
12388
12830
  }
12389
12831
  try {
12390
- const stats = await stat4(lockPath);
12832
+ const stats = await stat5(lockPath);
12391
12833
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12392
12834
  } catch (thrown) {
12393
12835
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -12399,12 +12841,12 @@ var withFileLock = async (filePath, options, fn) => {
12399
12841
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
12400
12842
  const lockPath = lockPathFor(filePath);
12401
12843
  const startedAt = options.clock.monotonicMillis();
12402
- await mkdir4(path7.dirname(filePath), { recursive: true });
12844
+ await mkdir5(path8.dirname(filePath), { recursive: true });
12403
12845
  for (; ; ) {
12404
- const token = randomBytes4(16).toString("hex");
12846
+ const token = randomBytes5(16).toString("hex");
12405
12847
  let acquired = false;
12406
12848
  try {
12407
- const handle = await open3(lockPath, "wx", 384);
12849
+ const handle = await open4(lockPath, "wx", 384);
12408
12850
  try {
12409
12851
  const contents = {
12410
12852
  token,
@@ -12446,8 +12888,8 @@ var withFileLock = async (filePath, options, fn) => {
12446
12888
  };
12447
12889
 
12448
12890
  // src/install/lifecycle.ts
12449
- import { readFile as readFile6 } from "fs/promises";
12450
- import * as path8 from "path";
12891
+ import { readFile as readFile7 } from "fs/promises";
12892
+ import * as path9 from "path";
12451
12893
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
12452
12894
  var unsupportedOutcome = (providerId, scope, reason) => ({
12453
12895
  providerId,
@@ -12464,7 +12906,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
12464
12906
  var resolveTarget = (providerId, scope, request) => {
12465
12907
  if (request.configFile !== void 0) {
12466
12908
  return {
12467
- configPath: path8.resolve(request.configFile),
12909
+ configPath: path9.resolve(request.configFile),
12468
12910
  evidence: "path supplied by the caller with --settings-file"
12469
12911
  };
12470
12912
  }
@@ -12481,14 +12923,14 @@ var resolveTarget = (providerId, scope, request) => {
12481
12923
  };
12482
12924
  };
12483
12925
  var codexFeatureNote = async (configPath) => {
12484
- const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
12926
+ const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
12485
12927
  let raw;
12486
12928
  try {
12487
- raw = await readFile6(tomlPath, "utf8");
12929
+ raw = await readFile7(tomlPath, "utf8");
12488
12930
  } catch {
12489
12931
  return void 0;
12490
12932
  }
12491
- 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;
12492
12934
  };
12493
12935
  var readState = async (configPath) => {
12494
12936
  const read = await readJsonDocument(configPath);
@@ -12500,12 +12942,12 @@ var readState = async (configPath) => {
12500
12942
  case "unparseable":
12501
12943
  return {
12502
12944
  status: "blocked",
12503
- 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`
12504
12946
  };
12505
12947
  case "unreadable":
12506
12948
  return {
12507
12949
  status: "failed",
12508
- problem: `${path8.basename(configPath)} could not be read (${read.detail})`
12950
+ problem: `${path9.basename(configPath)} could not be read (${read.detail})`
12509
12951
  };
12510
12952
  }
12511
12953
  };
@@ -12617,7 +13059,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12617
13059
  missingEvents: [],
12618
13060
  notes,
12619
13061
  problems: planned.conflicts.map(
12620
- (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`
12621
13063
  )
12622
13064
  };
12623
13065
  }
@@ -12628,7 +13070,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12628
13070
  changed: false,
12629
13071
  registeredEvents: [],
12630
13072
  missingEvents: [],
12631
- notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
13073
+ notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
12632
13074
  problems: []
12633
13075
  };
12634
13076
  }
@@ -12671,7 +13113,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12671
13113
  missingEvents: [],
12672
13114
  notes,
12673
13115
  problems: [
12674
- `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})`
12675
13117
  ]
12676
13118
  };
12677
13119
  }
@@ -12698,7 +13140,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12698
13140
  missingEvents: [],
12699
13141
  notes,
12700
13142
  problems: [
12701
- 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`
12702
13144
  ]
12703
13145
  };
12704
13146
  }
@@ -12794,9 +13236,9 @@ var runProvidersCommand = (command, io) => {
12794
13236
 
12795
13237
  // src/cli/registration.ts
12796
13238
  import * as os2 from "os";
12797
- import * as path9 from "path";
12798
- var resolveProjectDir = (command, io) => path9.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
12799
- 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());
12800
13242
  var collectRegistrationReport = async (command, io) => runRegistrationLifecycle({
12801
13243
  action: command.name,
12802
13244
  // A bare `diagnose` sweeps the providers this tool can locate by itself.
@@ -12877,10 +13319,10 @@ var runRegistrationCommand = async (command, io) => {
12877
13319
  };
12878
13320
 
12879
13321
  // src/cli/run.ts
12880
- import * as path14 from "path";
13322
+ import * as path16 from "path";
12881
13323
 
12882
13324
  // src/lifecycle/dedup.ts
12883
- import { randomBytes as randomBytes5 } from "crypto";
13325
+ import { randomBytes as randomBytes6 } from "crypto";
12884
13326
 
12885
13327
  // src/lifecycle/keys.ts
12886
13328
  var LIFECYCLE_PREFIX = "lifecycle";
@@ -12934,7 +13376,7 @@ var ownerOf = (record) => {
12934
13376
  const owner = record.value.attributes.owner;
12935
13377
  return typeof owner === "string" && owner.length > 0 ? owner : void 0;
12936
13378
  };
12937
- var newOwnerToken = () => randomBytes5(12).toString("hex");
13379
+ var newOwnerToken = () => randomBytes6(12).toString("hex");
12938
13380
  var claimedAtOf = (record) => {
12939
13381
  if (record?.value.kind !== "attributes") {
12940
13382
  return void 0;
@@ -13077,12 +13519,12 @@ var createCallbackDeduplicator = (deps) => {
13077
13519
  };
13078
13520
 
13079
13521
  // src/lifecycle/metric-series.ts
13080
- import { createHash as createHash4 } from "crypto";
13522
+ import { createHash as createHash5 } from "crypto";
13081
13523
  var TURN_START_SEGMENT = "turn-start";
13082
13524
  var SHARED_SCOPE = "all";
13083
13525
  var SHARED_LOCK = "otelhook.metrics.shared";
13084
13526
  var sessionScope = (sessionId) => `s=${sessionId}`;
13085
- 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);
13086
13528
  var toStoredHistogram = (histogram) => ({
13087
13529
  count: histogram.count,
13088
13530
  sum: histogram.sum,
@@ -13310,6 +13752,7 @@ var encodeRecord = (record) => ({
13310
13752
  ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
13311
13753
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
13312
13754
  ...record.exported === true ? { exported: true } : {},
13755
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey },
13313
13756
  ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
13314
13757
  ...encodeAttributes(record.attributes)
13315
13758
  }
@@ -13333,6 +13776,7 @@ var decodeRecord = (attributes) => {
13333
13776
  return { kind: "corrupt" };
13334
13777
  }
13335
13778
  const exported = attributes["exported"] === true;
13779
+ const runKey = optionalString(attributes["runKey"]);
13336
13780
  const parentFamily = attributes["parentFamily"];
13337
13781
  const parentScopeKey = optionalString(attributes["parentScopeKey"]);
13338
13782
  const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
@@ -13347,6 +13791,7 @@ var decodeRecord = (attributes) => {
13347
13791
  ...endedAt === void 0 ? {} : { endedAt },
13348
13792
  ...parent === void 0 ? {} : { parent },
13349
13793
  ...exported ? { exported: true } : {},
13794
+ ...runKey === void 0 ? {} : { runKey },
13350
13795
  ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
13351
13796
  }
13352
13797
  };
@@ -13355,13 +13800,15 @@ var factsOf = (record) => ({
13355
13800
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
13356
13801
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
13357
13802
  ...record.parent === void 0 ? {} : { parent: record.parent },
13358
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
13803
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes },
13804
+ ...record.runKey === void 0 ? {} : { runKey: record.runKey }
13359
13805
  });
13360
13806
  var correlationTimesOf = (facts, options = { withStart: true }) => ({
13361
13807
  ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
13362
13808
  ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
13363
13809
  ...facts.parent === void 0 ? {} : { parent: facts.parent },
13364
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
13810
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
13811
+ ...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
13365
13812
  });
13366
13813
  var orphanClassificationOf = (reason) => {
13367
13814
  switch (reason) {
@@ -13421,10 +13868,12 @@ var createSpanCorrelator = (deps) => {
13421
13868
  return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
13422
13869
  }
13423
13870
  }
13871
+ const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
13424
13872
  const fresh = {
13425
13873
  providerId: input.providerId,
13426
13874
  startEventId: input.eventId,
13427
13875
  startedAt: input.occurredAt,
13876
+ ...previouslyExported ? { runKey: input.eventId } : {},
13428
13877
  ...input.parent === void 0 ? {} : { parent: input.parent },
13429
13878
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
13430
13879
  };
@@ -13762,9 +14211,9 @@ var createUsageAccumulator = (deps) => {
13762
14211
  };
13763
14212
 
13764
14213
  // src/providers/claude/transcript.ts
13765
- import { createHash as createHash5 } from "crypto";
13766
- import { open as open4, stat as stat5 } from "fs/promises";
13767
- 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";
13768
14217
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13769
14218
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
13770
14219
  var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
@@ -13785,7 +14234,7 @@ var clamp = (value, fallback, min, max) => {
13785
14234
  return Math.min(max, Math.max(min, Math.floor(value)));
13786
14235
  };
13787
14236
  var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13788
- 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";
13789
14238
  var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
13790
14239
  var assistantRecordOf = (line, agentId) => {
13791
14240
  if (!line.includes('"assistant"')) {
@@ -13856,7 +14305,7 @@ var withTimeout = async (work, timeoutMillis, onError) => {
13856
14305
  var withRegularFile = async (transcriptPath, body) => {
13857
14306
  let info;
13858
14307
  try {
13859
- info = await stat5(transcriptPath);
14308
+ info = await stat6(transcriptPath);
13860
14309
  } catch {
13861
14310
  return { status: "unavailable", reason: "unreadable" };
13862
14311
  }
@@ -13865,7 +14314,7 @@ var withRegularFile = async (transcriptPath, body) => {
13865
14314
  }
13866
14315
  let handle;
13867
14316
  try {
13868
- handle = await open4(transcriptPath, "r");
14317
+ handle = await open5(transcriptPath, "r");
13869
14318
  } catch {
13870
14319
  return { status: "unavailable", reason: "unreadable" };
13871
14320
  }
@@ -13985,7 +14434,7 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
13985
14434
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
13986
14435
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
13987
14436
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
13988
- 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);
13989
14438
  var SUBAGENT_STOP = "SubagentStop";
13990
14439
  var agentIdOf = (record) => {
13991
14440
  const agentId = record.agent_id ?? record.agentId;
@@ -13998,12 +14447,12 @@ var subagentCursorScope = (payload) => {
13998
14447
  return void 0;
13999
14448
  }
14000
14449
  const agentId = agentIdOf(record);
14001
- 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)}`;
14002
14451
  };
14003
14452
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
14004
14453
  const fileSize = async (transcriptPath) => {
14005
14454
  try {
14006
- const info = await stat5(transcriptPath);
14455
+ const info = await stat6(transcriptPath);
14007
14456
  return info.isFile() ? info.size : void 0;
14008
14457
  } catch (thrown) {
14009
14458
  return thrown?.code === "ENOENT" ? "absent" : void 0;
@@ -14100,6 +14549,283 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
14100
14549
  });
14101
14550
  };
14102
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
+
14103
14829
  // src/runtime/hook.ts
14104
14830
  import { z as z24 } from "zod";
14105
14831
 
@@ -14133,9 +14859,9 @@ var resolveDeliveryIdentity = (input) => {
14133
14859
  };
14134
14860
 
14135
14861
  // src/runtime/ids.ts
14136
- import { createHash as createHash6, randomUUID } from "crypto";
14862
+ import { createHash as createHash8, randomUUID } from "crypto";
14137
14863
  var digest2 = (namespace, parts) => {
14138
- const hash = createHash6("sha256");
14864
+ const hash = createHash8("sha256");
14139
14865
  hash.update(namespace);
14140
14866
  for (const part of parts) {
14141
14867
  hash.update("\0");
@@ -14174,16 +14900,16 @@ var createDeterministicIdGenerator = (options = {}) => {
14174
14900
  };
14175
14901
 
14176
14902
  // src/runtime/target-resolution.ts
14177
- import * as path11 from "path";
14903
+ import * as path13 from "path";
14178
14904
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
14179
14905
  var absolutePathsOf = (hint) => {
14180
- 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;
14181
14907
  const resolved = [];
14182
14908
  for (const candidate of hint.paths) {
14183
- if (path11.isAbsolute(candidate)) {
14184
- resolved.push(path11.resolve(candidate));
14909
+ if (path13.isAbsolute(candidate)) {
14910
+ resolved.push(path13.resolve(candidate));
14185
14911
  } else if (base !== void 0) {
14186
- resolved.push(path11.resolve(base, candidate));
14912
+ resolved.push(path13.resolve(base, candidate));
14187
14913
  } else {
14188
14914
  return void 0;
14189
14915
  }
@@ -14262,8 +14988,8 @@ var resolveEventTargets = async (input) => {
14262
14988
  };
14263
14989
 
14264
14990
  // src/runtime/session-context.ts
14265
- import { open as open5 } from "fs/promises";
14266
- import * as path12 from "path";
14991
+ import { open as open7 } from "fs/promises";
14992
+ import * as path14 from "path";
14267
14993
  import { z as z23 } from "zod";
14268
14994
  var SESSION_CONTEXT_FILE_VERSION = 1;
14269
14995
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
@@ -14281,10 +15007,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
14281
15007
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
14282
15008
  var sessionContextFilePath = (dir, providerId, sessionId) => {
14283
15009
  const tool = sessionContextAgentTool(providerId);
14284
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path12.isAbsolute(dir)) {
15010
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path14.isAbsolute(dir)) {
14285
15011
  return void 0;
14286
15012
  }
14287
- return path12.join(dir, tool, `${sessionId}.json`);
15013
+ return path14.join(dir, tool, `${sessionId}.json`);
14288
15014
  };
14289
15015
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
14290
15016
  "session.id",
@@ -14380,7 +15106,7 @@ var stampSessionContext = (events, segments) => events.map((event3) => {
14380
15106
  var readBounded = async (file, maxBytes) => {
14381
15107
  let handle;
14382
15108
  try {
14383
- handle = await open5(file, "r");
15109
+ handle = await open7(file, "r");
14384
15110
  } catch {
14385
15111
  return void 0;
14386
15112
  }
@@ -15333,8 +16059,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
15333
16059
  };
15334
16060
 
15335
16061
  // src/runtime/git-worktree.ts
15336
- import { lstat, open as open6, stat as stat6 } from "fs/promises";
15337
- import * as path13 from "path";
16062
+ import { lstat, open as open8, stat as stat8 } from "fs/promises";
16063
+ import * as path15 from "path";
15338
16064
  var MAX_WORKTREE_WALK_DEPTH = 128;
15339
16065
  var MAX_GIT_FILE_BYTES = 4096;
15340
16066
  var MAX_CACHE_ENTRIES = 1024;
@@ -15345,7 +16071,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
15345
16071
  var readBounded2 = async (filePath) => {
15346
16072
  let handle;
15347
16073
  try {
15348
- handle = await open6(filePath, "r");
16074
+ handle = await open8(filePath, "r");
15349
16075
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
15350
16076
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
15351
16077
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -15366,7 +16092,7 @@ var parseHeadBranch = (head) => {
15366
16092
  return branch;
15367
16093
  };
15368
16094
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
15369
- 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);
15370
16096
  var parseGitDirFile = (content, worktreeRoot) => {
15371
16097
  const line = firstLine(content);
15372
16098
  return resolveGitPath(
@@ -15386,26 +16112,26 @@ var isMissing = async (filePath) => {
15386
16112
  };
15387
16113
  var isDirectory = async (directory) => {
15388
16114
  try {
15389
- return (await stat6(directory)).isDirectory();
16115
+ return (await stat8(directory)).isDirectory();
15390
16116
  } catch {
15391
16117
  return false;
15392
16118
  }
15393
16119
  };
15394
16120
  var repositoryOf = async (worktreeRoot, gitDir) => {
15395
- const commonDirFile = path13.join(gitDir, "commondir");
16121
+ const commonDirFile = path15.join(gitDir, "commondir");
15396
16122
  const content = await readBounded2(commonDirFile);
15397
16123
  if (content === void 0) {
15398
16124
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
15399
16125
  }
15400
16126
  const commonDir = parseCommonDirFile(content, gitDir);
15401
- 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;
15402
16128
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
15403
16129
  };
15404
16130
  var probeDirectory = async (directory) => {
15405
- const dotGit = path13.join(directory, ".git");
16131
+ const dotGit = path15.join(directory, ".git");
15406
16132
  let info;
15407
16133
  try {
15408
- info = await stat6(dotGit);
16134
+ info = await stat8(dotGit);
15409
16135
  } catch {
15410
16136
  return ABSENT;
15411
16137
  }
@@ -15419,7 +16145,7 @@ var probeDirectory = async (directory) => {
15419
16145
  if (gitDir === void 0) {
15420
16146
  return INVALID;
15421
16147
  }
15422
- const head = await readBounded2(path13.join(gitDir, "HEAD"));
16148
+ const head = await readBounded2(path15.join(gitDir, "HEAD"));
15423
16149
  if (head === void 0) {
15424
16150
  return INVALID;
15425
16151
  }
@@ -15449,10 +16175,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15449
16175
  };
15450
16176
  const locate = async (absolutePath) => {
15451
16177
  try {
15452
- if (!path13.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16178
+ if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15453
16179
  return void 0;
15454
16180
  }
15455
- let directory = path13.resolve(absolutePath);
16181
+ let directory = path15.resolve(absolutePath);
15456
16182
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
15457
16183
  const probe = await cachedProbe(directory);
15458
16184
  if (probe.kind === "worktree") {
@@ -15461,7 +16187,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15461
16187
  if (probe.kind === "invalid") {
15462
16188
  return void 0;
15463
16189
  }
15464
- const parent = path13.dirname(directory);
16190
+ const parent = path15.dirname(directory);
15465
16191
  if (parent === directory) {
15466
16192
  return void 0;
15467
16193
  }
@@ -15587,7 +16313,14 @@ var createHookRuntime = (options) => {
15587
16313
  privacy,
15588
16314
  logger,
15589
16315
  installationId: options.installationId,
15590
- 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
+ ],
15591
16324
  ...(() => {
15592
16325
  if (options.sessionContextReader === null) {
15593
16326
  return {};
@@ -16129,6 +16862,14 @@ var readBoundedJson = async (stream, maxBytes) => {
16129
16862
  };
16130
16863
 
16131
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
+ };
16132
16873
  var MAX_LOGGED_DIAGNOSTICS = 16;
16133
16874
  var logDiagnostics = (logger, diagnostics) => {
16134
16875
  for (const info of diagnostics.slice(0, MAX_LOGGED_DIAGNOSTICS)) {
@@ -16263,13 +17004,13 @@ var runHookCommand = async (command, io) => {
16263
17004
  }
16264
17005
  const identityClaims = [];
16265
17006
  if (command.identity.identityFile !== void 0) {
16266
- const read = await readIdentityFile(path14.resolve(command.identity.identityFile));
17007
+ const read = await readIdentityFile(path16.resolve(command.identity.identityFile));
16267
17008
  if ("error" in read) {
16268
17009
  logDiagnostics(logger, [read.error]);
16269
17010
  } else {
16270
17011
  const fromFile = claimFromIdentityFile(
16271
17012
  read.value,
16272
- path14.basename(command.identity.identityFile)
17013
+ path16.basename(command.identity.identityFile)
16273
17014
  );
16274
17015
  logDiagnostics(logger, fromFile.errors);
16275
17016
  identityClaims.push(...fromFile.claims);
@@ -16279,6 +17020,7 @@ var runHookCommand = async (command, io) => {
16279
17020
  logDiagnostics(logger, fromFlags.errors);
16280
17021
  identityClaims.push(...fromFlags.claims);
16281
17022
  const headers = resolveCliExporterHeaders(command.policy, io);
17023
+ const codexSessions = codexSessionsRoot(io.env);
16282
17024
  const runtime = createHookRuntime({
16283
17025
  // Detection policy narrowed to the selected adapter; everything else is the
16284
17026
  // resolved configuration exactly as it stands.
@@ -16298,6 +17040,7 @@ var runHookCommand = async (command, io) => {
16298
17040
  privacy,
16299
17041
  ...command.policy.flushTimeoutMillis === void 0 ? {} : { flushTimeoutMillis: command.policy.flushTimeoutMillis },
16300
17042
  ...command.policy.spoolDisabled === true ? { enableSpool: false } : {},
17043
+ ...codexSessions === void 0 ? {} : { codexSessionsRoot: codexSessions },
16301
17044
  ...command.requireCallbackId === true ? { requireCallbackId: true } : {},
16302
17045
  ...command.noDeriveCallbackId === true ? { deriveDeliveryIdentity: false } : {}
16303
17046
  });