@osfactory/otel-hook 0.13.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -476,8 +476,26 @@ var exporterPolicySchema = z5.strictObject({
476
476
  * Per-destination retry spool bounds, each optional and merged per leaf; any
477
477
  * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
478
478
  */
479
- spool: spoolPolicySchema.partial().optional()
479
+ spool: spoolPolicySchema.partial().optional(),
480
+ /**
481
+ * The most time one hook invocation spends trying to reach one endpoint, in
482
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
483
+ * included) and the exporter's own retries inside it. A batch that does not
484
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
485
+ * the host agent waits for its hooks, so a down collector must not stall it.
486
+ */
487
+ exportBudgetMillis: z5.number().int().min(50).max(6e5).optional(),
488
+ /**
489
+ * After an endpoint was unreachable (refused, timed out, or answered a
490
+ * retryable status), every hook spools for it without trying for this long,
491
+ * in milliseconds; then one hook probes it again. 0 disables the window.
492
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
493
+ */
494
+ endpointDownMillis: z5.number().int().min(0).max(36e5).optional()
480
495
  });
496
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
497
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
498
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
481
499
  var detectionPolicySchema = z5.strictObject({
482
500
  /** Detections below this confidence resolve to the unknown provider. */
483
501
  minimumConfidence: detectionConfidenceSchema,
@@ -494,6 +512,9 @@ var diagnosticsPolicySchema = z5.strictObject({
494
512
  var providersPolicySchema = z5.strictObject({
495
513
  claudeCode: z5.strictObject({
496
514
  readTranscriptUsage: z5.boolean()
515
+ }).optional(),
516
+ codex: z5.strictObject({
517
+ readRolloutUsage: z5.boolean()
497
518
  }).optional()
498
519
  });
499
520
  var sessionContextPolicySchema = z5.strictObject({
@@ -523,7 +544,8 @@ var otelHookConfigPatchSchema = z5.strictObject({
523
544
  detection: detectionPolicySchema.partial().optional(),
524
545
  diagnostics: diagnosticsPolicySchema.partial().optional(),
525
546
  providers: z5.strictObject({
526
- claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
547
+ claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional(),
548
+ codex: z5.strictObject({ readRolloutUsage: z5.boolean() }).partial().optional()
527
549
  }).partial().optional(),
528
550
  sessionContext: sessionContextPolicySchema.partial().optional()
529
551
  });
@@ -550,7 +572,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
550
572
  emitErrorEvents: true
551
573
  });
552
574
  var DEFAULT_PROVIDERS_POLICY = Object.freeze({
553
- claudeCode: Object.freeze({ readTranscriptUsage: false })
575
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
576
+ codex: Object.freeze({ readRolloutUsage: false })
554
577
  });
555
578
  var DEFAULT_CONFIG = Object.freeze({
556
579
  exporter: DEFAULT_EXPORTER_POLICY,
@@ -560,6 +583,7 @@ var DEFAULT_CONFIG = Object.freeze({
560
583
  providers: DEFAULT_PROVIDERS_POLICY
561
584
  });
562
585
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
586
+ var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
563
587
  var sessionContextDir = (config) => config.sessionContext?.dir;
564
588
  var effectiveMetricsPolicy = (exporter) => ({
565
589
  ...DEFAULT_METRICS_POLICY,
@@ -2419,7 +2443,7 @@ import {
2419
2443
  } from "@opentelemetry/semantic-conventions/incubating";
2420
2444
 
2421
2445
  // src/version.ts
2422
- var VERSION = "0.13.1";
2446
+ var VERSION = "0.13.2";
2423
2447
 
2424
2448
  // src/telemetry/semconv.ts
2425
2449
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -3686,11 +3710,11 @@ var createPrivacyService = (policyInput) => {
3686
3710
  };
3687
3711
  const flattenToAttributes = (value, prefix) => {
3688
3712
  const attributes = {};
3689
- const walk = (current, path7) => {
3713
+ const walk = (current, path9) => {
3690
3714
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3691
3715
  const primitive = toAttributePrimitive(current);
3692
3716
  if (primitive !== void 0) {
3693
- attributes[path7] = primitive;
3717
+ attributes[path9] = primitive;
3694
3718
  }
3695
3719
  return;
3696
3720
  }
@@ -3709,16 +3733,16 @@ var createPrivacyService = (policyInput) => {
3709
3733
  primitives.push(entryPrimitive);
3710
3734
  }
3711
3735
  if (uniform) {
3712
- attributes[path7] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3736
+ attributes[path9] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3713
3737
  return;
3714
3738
  }
3715
3739
  for (const [index, entry] of current.entries()) {
3716
- walk(entry, `${path7}.${index}`);
3740
+ walk(entry, `${path9}.${index}`);
3717
3741
  }
3718
3742
  return;
3719
3743
  }
3720
3744
  for (const [key, entry] of Object.entries(current)) {
3721
- walk(entry, path7 === "" ? key : `${path7}.${key}`);
3745
+ walk(entry, path9 === "" ? key : `${path9}.${key}`);
3722
3746
  }
3723
3747
  };
3724
3748
  walk(value, prefix);
@@ -4616,6 +4640,419 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4616
4640
  });
4617
4641
  };
4618
4642
 
4643
+ // src/providers/codex/rollout-usage.ts
4644
+ import { createHash as createHash5 } from "crypto";
4645
+ import { open as open2, readdir, stat as stat2 } from "fs/promises";
4646
+ import path2 from "path";
4647
+
4648
+ // src/providers/codex/version.ts
4649
+ var CODEX_PROVIDER_ID = providerIdSchema.parse("codex");
4650
+
4651
+ // src/providers/codex/payload.ts
4652
+ import { z as z17 } from "zod";
4653
+ var permissionModeSchema = z17.enum([
4654
+ "default",
4655
+ "acceptEdits",
4656
+ "plan",
4657
+ "dontAsk",
4658
+ "bypassPermissions"
4659
+ ]);
4660
+ var codexUsageSchema = z17.object({
4661
+ input_tokens: z17.number().int().min(0).optional(),
4662
+ cached_input_tokens: z17.number().int().min(0).optional(),
4663
+ cache_write_input_tokens: z17.number().int().min(0).optional(),
4664
+ output_tokens: z17.number().int().min(0).optional(),
4665
+ reasoning_output_tokens: z17.number().int().min(0).optional(),
4666
+ total_tokens: z17.number().int().min(0).optional()
4667
+ });
4668
+ var baseFields = {
4669
+ session_id: z17.string().min(1).max(256),
4670
+ cwd: z17.string().min(1).max(4096).optional(),
4671
+ model: z17.string().min(1).max(256).optional(),
4672
+ permission_mode: permissionModeSchema.optional(),
4673
+ transcript_path: z17.string().min(1).max(4096).optional(),
4674
+ codex_version: z17.string().min(1).max(64).optional(),
4675
+ /** Not part of the documented protocol; lets tests and replay stay deterministic. */
4676
+ occurred_at: z17.number().int().min(0).optional()
4677
+ };
4678
+ var codexSessionStartPayloadSchema = z17.object({
4679
+ ...baseFields,
4680
+ hook_event_name: z17.literal("SessionStart"),
4681
+ source: z17.enum(["startup", "resume", "clear", "compact"]).optional()
4682
+ });
4683
+ var codexUserPromptSubmitPayloadSchema = z17.object({
4684
+ ...baseFields,
4685
+ hook_event_name: z17.literal("UserPromptSubmit"),
4686
+ turn_id: z17.string().min(1).max(256).optional(),
4687
+ prompt: z17.string().max(1e6).optional()
4688
+ });
4689
+ var codexPreToolUsePayloadSchema = z17.object({
4690
+ ...baseFields,
4691
+ hook_event_name: z17.literal("PreToolUse"),
4692
+ turn_id: z17.string().min(1).max(256).optional(),
4693
+ tool_name: z17.string().min(1).max(256),
4694
+ tool_call_id: z17.string().min(1).max(256).optional(),
4695
+ tool_input: z17.unknown().optional()
4696
+ });
4697
+ var codexPermissionRequestPayloadSchema = z17.object({
4698
+ ...baseFields,
4699
+ hook_event_name: z17.literal("PermissionRequest"),
4700
+ turn_id: z17.string().min(1).max(256).optional(),
4701
+ tool_name: z17.string().min(1).max(256).optional(),
4702
+ tool_call_id: z17.string().min(1).max(256).optional(),
4703
+ tool_input: z17.unknown().optional()
4704
+ });
4705
+ var codexPostToolUsePayloadSchema = z17.object({
4706
+ ...baseFields,
4707
+ hook_event_name: z17.literal("PostToolUse"),
4708
+ turn_id: z17.string().min(1).max(256).optional(),
4709
+ tool_name: z17.string().min(1).max(256),
4710
+ tool_call_id: z17.string().min(1).max(256).optional(),
4711
+ tool_input: z17.unknown().optional(),
4712
+ tool_response: z17.unknown().optional(),
4713
+ permission_decision: z17.enum(["allowed", "denied", "deferred"]).optional(),
4714
+ duration_ms: z17.number().min(0).optional()
4715
+ });
4716
+ var codexPreCompactPayloadSchema = z17.object({
4717
+ ...baseFields,
4718
+ hook_event_name: z17.literal("PreCompact"),
4719
+ trigger: z17.enum(["auto", "manual"]).optional(),
4720
+ context_tokens_before: z17.number().int().min(0).optional()
4721
+ });
4722
+ var codexPostCompactPayloadSchema = z17.object({
4723
+ ...baseFields,
4724
+ hook_event_name: z17.literal("PostCompact"),
4725
+ trigger: z17.enum(["auto", "manual"]).optional(),
4726
+ context_tokens_after: z17.number().int().min(0).optional(),
4727
+ dropped_message_count: z17.number().int().min(0).optional(),
4728
+ usage: codexUsageSchema.optional()
4729
+ });
4730
+ var codexSubagentStartPayloadSchema = z17.object({
4731
+ ...baseFields,
4732
+ hook_event_name: z17.literal("SubagentStart"),
4733
+ turn_id: z17.string().min(1).max(256).optional(),
4734
+ subagent_id: z17.string().min(1).max(256),
4735
+ subagent_type: z17.string().min(1).max(256).optional()
4736
+ });
4737
+ var codexSubagentStopPayloadSchema = z17.object({
4738
+ ...baseFields,
4739
+ hook_event_name: z17.literal("SubagentStop"),
4740
+ turn_id: z17.string().min(1).max(256).optional(),
4741
+ subagent_id: z17.string().min(1).max(256),
4742
+ status: z17.enum(["completed", "failed", "cancelled"]).optional(),
4743
+ usage: codexUsageSchema.optional()
4744
+ });
4745
+ var codexStopPayloadSchema = z17.object({
4746
+ ...baseFields,
4747
+ hook_event_name: z17.literal("Stop"),
4748
+ turn_id: z17.string().min(1).max(256).optional(),
4749
+ stop_reason: z17.string().min(1).max(256).optional(),
4750
+ usage: codexUsageSchema.optional(),
4751
+ duration_ms: z17.number().min(0).optional()
4752
+ });
4753
+ var CODEX_HOOK_EVENT_NAMES = [
4754
+ "SessionStart",
4755
+ "UserPromptSubmit",
4756
+ "PreToolUse",
4757
+ "PermissionRequest",
4758
+ "PostToolUse",
4759
+ "PreCompact",
4760
+ "PostCompact",
4761
+ "SubagentStart",
4762
+ "SubagentStop",
4763
+ "Stop"
4764
+ ];
4765
+ var codexHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
4766
+ codexSessionStartPayloadSchema,
4767
+ codexUserPromptSubmitPayloadSchema,
4768
+ codexPreToolUsePayloadSchema,
4769
+ codexPermissionRequestPayloadSchema,
4770
+ codexPostToolUsePayloadSchema,
4771
+ codexPreCompactPayloadSchema,
4772
+ codexPostCompactPayloadSchema,
4773
+ codexSubagentStartPayloadSchema,
4774
+ codexSubagentStopPayloadSchema,
4775
+ codexStopPayloadSchema
4776
+ ]);
4777
+ var codexHookEnvelopeSchema = z17.object({
4778
+ session_id: z17.string().min(1),
4779
+ hook_event_name: z17.enum(CODEX_HOOK_EVENT_NAMES)
4780
+ });
4781
+
4782
+ // src/providers/codex/rollout-usage.ts
4783
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
4784
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
4785
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
4786
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
4787
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
4788
+ var ROLLOUT_LOOKUP_DAYS = 7;
4789
+ var MIN_BYTES = 65536;
4790
+ var MAX_RANGE_BYTES2 = 67108864;
4791
+ var MAX_TAIL_BYTES2 = 16777216;
4792
+ var MIN_TIMEOUT_MILLIS2 = 10;
4793
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
4794
+ var MAX_SETTLE_MILLIS = 1e3;
4795
+ var MAX_MODEL_ID_LENGTH2 = 256;
4796
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
4797
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
4798
+ var clamp2 = (value, fallback, min, max) => {
4799
+ if (value === void 0 || !Number.isFinite(value)) {
4800
+ return fallback;
4801
+ }
4802
+ return Math.min(max, Math.max(min, Math.floor(value)));
4803
+ };
4804
+ var asRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4805
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path2.isAbsolute(value) && path2.extname(value) === ".jsonl";
4806
+ var sourceDigest2 = (rolloutPath) => createHash5("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
4807
+ var parseUsage = (value) => {
4808
+ const parsed = codexUsageSchema.safeParse(value);
4809
+ if (!parsed.success) {
4810
+ return void 0;
4811
+ }
4812
+ const usage = parsed.data;
4813
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
4814
+ };
4815
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
4816
+ var factsOf2 = (line) => {
4817
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
4818
+ const contextLine = line.includes('"turn_context"');
4819
+ if (!usageLine && !contextLine) {
4820
+ return void 0;
4821
+ }
4822
+ let parsed;
4823
+ try {
4824
+ parsed = JSON.parse(line);
4825
+ } catch {
4826
+ return void 0;
4827
+ }
4828
+ const record = asRecord3(parsed);
4829
+ const payload = asRecord3(record?.payload);
4830
+ if (record === void 0 || payload === void 0) {
4831
+ return void 0;
4832
+ }
4833
+ if (record.type === "turn_context") {
4834
+ const model = modelOf(payload.model);
4835
+ return model === void 0 ? void 0 : { model };
4836
+ }
4837
+ if (record.type === "event_msg" && payload.type === "token_count") {
4838
+ const info = asRecord3(payload.info) ?? payload;
4839
+ const usage = parseUsage(info.total_token_usage);
4840
+ return usage === void 0 ? void 0 : { usage };
4841
+ }
4842
+ if (record.type === "token_usage_record") {
4843
+ const usage = parseUsage(payload.thread_token_usage);
4844
+ return usage === void 0 ? void 0 : { usage };
4845
+ }
4846
+ return void 0;
4847
+ };
4848
+ var lastSnapshotIn = (lines) => {
4849
+ let usage;
4850
+ let model;
4851
+ for (const line of lines) {
4852
+ const facts = factsOf2(line.trim());
4853
+ if (facts === void 0) {
4854
+ continue;
4855
+ }
4856
+ if (facts.model !== void 0) {
4857
+ model = facts.model;
4858
+ }
4859
+ if (facts.usage !== void 0) {
4860
+ usage = facts.usage;
4861
+ }
4862
+ }
4863
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
4864
+ };
4865
+ var readBytes2 = async (handle, start, length) => {
4866
+ const buffer = Buffer.alloc(length);
4867
+ let filled = 0;
4868
+ while (filled < length) {
4869
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
4870
+ if (bytesRead === 0) {
4871
+ break;
4872
+ }
4873
+ filled += bytesRead;
4874
+ }
4875
+ return buffer.subarray(0, filled);
4876
+ };
4877
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
4878
+ let handle;
4879
+ try {
4880
+ const info = await stat2(rolloutPath);
4881
+ if (!info.isFile()) {
4882
+ return { status: "unavailable", reason: "not-a-file" };
4883
+ }
4884
+ handle = await open2(rolloutPath, "r");
4885
+ } catch {
4886
+ return { status: "unavailable", reason: "unreadable" };
4887
+ }
4888
+ try {
4889
+ const { size } = await handle.stat();
4890
+ let start;
4891
+ if (fromOffset === void 0) {
4892
+ start = Math.max(0, size - tailBytes);
4893
+ } else if (size < fromOffset) {
4894
+ return { status: "unavailable", reason: "truncated" };
4895
+ } else if (size - fromOffset > maxRangeBytes) {
4896
+ return { status: "unavailable", reason: "over-cap" };
4897
+ } else {
4898
+ start = fromOffset;
4899
+ }
4900
+ const bytes = await readBytes2(handle, start, size - start);
4901
+ const lastNewline = bytes.lastIndexOf(10);
4902
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
4903
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
4904
+ if (fromOffset === void 0 && start > 0) {
4905
+ lines.shift();
4906
+ }
4907
+ const snapshot = lastSnapshotIn(lines);
4908
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
4909
+ } catch {
4910
+ return { status: "unavailable", reason: "unreadable" };
4911
+ } finally {
4912
+ await handle.close().catch(() => void 0);
4913
+ }
4914
+ };
4915
+ var pad = (value) => String(value).padStart(2, "0");
4916
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
4917
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path2.isAbsolute(sessionsRoot)) {
4918
+ return void 0;
4919
+ }
4920
+ const suffix = `-${sessionId}.jsonl`;
4921
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
4922
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
4923
+ const dir = path2.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
4924
+ let names;
4925
+ try {
4926
+ names = await readdir(dir);
4927
+ } catch {
4928
+ continue;
4929
+ }
4930
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
4931
+ continue;
4932
+ }
4933
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
4934
+ if (match !== void 0) {
4935
+ return path2.join(dir, match);
4936
+ }
4937
+ }
4938
+ return void 0;
4939
+ };
4940
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
4941
+ var withTimeout2 = async (work, timeoutMillis) => {
4942
+ let timer;
4943
+ const timeout = new Promise((resolve3) => {
4944
+ timer = setTimeout(() => {
4945
+ resolve3(TIMED_OUT2);
4946
+ }, timeoutMillis);
4947
+ timer.unref();
4948
+ });
4949
+ try {
4950
+ return await Promise.race([work, timeout]);
4951
+ } finally {
4952
+ clearTimeout(timer);
4953
+ }
4954
+ };
4955
+ var sleep = (millis) => new Promise((resolve3) => {
4956
+ setTimeout(resolve3, millis).unref();
4957
+ });
4958
+ var hasUsage2 = (record) => record.usage !== void 0;
4959
+ var createCodexRolloutUsageEnricher = (options = {}) => {
4960
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
4961
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
4962
+ const timeoutMillis = clamp2(
4963
+ options.timeoutMillis,
4964
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
4965
+ MIN_TIMEOUT_MILLIS2,
4966
+ MAX_TIMEOUT_MILLIS2
4967
+ );
4968
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
4969
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
4970
+ const fileSize = async (rolloutPath) => {
4971
+ try {
4972
+ const info = await stat2(rolloutPath);
4973
+ return info.isFile() ? info.size : void 0;
4974
+ } catch (thrown) {
4975
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
4976
+ }
4977
+ };
4978
+ const resolveRollout = async (record) => {
4979
+ const named = record.transcript_path;
4980
+ if (named !== void 0 && named !== null) {
4981
+ return isRolloutPath(named) ? named : void 0;
4982
+ }
4983
+ const sessionId = record.session_id;
4984
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
4985
+ return void 0;
4986
+ }
4987
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
4988
+ };
4989
+ const enrichWithin = async (input) => {
4990
+ const unchanged = { payload: input.payload };
4991
+ const record = asRecord3(input.payload);
4992
+ const eventName = record?.hook_event_name;
4993
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
4994
+ return unchanged;
4995
+ }
4996
+ const rolloutPath = await resolveRollout(record);
4997
+ if (rolloutPath === void 0) {
4998
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
4999
+ }
5000
+ const source = sourceDigest2(rolloutPath);
5001
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
5002
+ if (eventName === "SessionStart") {
5003
+ if (cursor !== void 0) {
5004
+ return unchanged;
5005
+ }
5006
+ const size = await fileSize(rolloutPath);
5007
+ if (size === void 0) {
5008
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
5009
+ }
5010
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
5011
+ }
5012
+ if (hasUsage2(record)) {
5013
+ const size = await fileSize(rolloutPath);
5014
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
5015
+ }
5016
+ const attach = (snapshot) => ({
5017
+ ...record,
5018
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
5019
+ usage: snapshot.usage
5020
+ });
5021
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
5022
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
5023
+ await sleep(settleMillis);
5024
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
5025
+ }
5026
+ if (read.status === "unavailable") {
5027
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
5028
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
5029
+ }
5030
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
5031
+ if (read.status === "unavailable") {
5032
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
5033
+ }
5034
+ }
5035
+ const next = { source, offset: read.endOffset };
5036
+ if (read.snapshot === void 0) {
5037
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
5038
+ }
5039
+ return {
5040
+ payload: attach(read.snapshot),
5041
+ cursor: next,
5042
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
5043
+ };
5044
+ };
5045
+ const enrich = async (input) => {
5046
+ try {
5047
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
5048
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
5049
+ } catch {
5050
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
5051
+ }
5052
+ };
5053
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
5054
+ };
5055
+
4619
5056
  // src/runtime/clock.ts
4620
5057
  var createSystemClock = () => ({
4621
5058
  now: () => epochMillisSchema.parse(Date.now()),
@@ -4623,7 +5060,7 @@ var createSystemClock = () => ({
4623
5060
  });
4624
5061
 
4625
5062
  // src/runtime/hook.ts
4626
- import { z as z19 } from "zod";
5063
+ import { z as z20 } from "zod";
4627
5064
 
4628
5065
  // src/providers/registry.ts
4629
5066
  var createProviderRegistry = (adapters) => {
@@ -4778,9 +5215,9 @@ var resolveDeliveryIdentity = (input) => {
4778
5215
  };
4779
5216
 
4780
5217
  // src/runtime/ids.ts
4781
- import { createHash as createHash5, randomUUID } from "crypto";
5218
+ import { createHash as createHash6, randomUUID } from "crypto";
4782
5219
  var digest2 = (namespace, parts) => {
4783
- const hash = createHash5("sha256");
5220
+ const hash = createHash6("sha256");
4784
5221
  hash.update(namespace);
4785
5222
  for (const part of parts) {
4786
5223
  hash.update("\0");
@@ -4819,15 +5256,15 @@ var createDeterministicIdGenerator = (options = {}) => {
4819
5256
  };
4820
5257
 
4821
5258
  // src/runtime/ports.ts
4822
- import { z as z17 } from "zod";
4823
- var appliedDeliverySchema = z17.strictObject({
4824
- callbackId: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
5259
+ import { z as z18 } from "zod";
5260
+ var appliedDeliverySchema = z18.strictObject({
5261
+ callbackId: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
4825
5262
  /** How many of that delivery's observations are folded in, counted from one. */
4826
- applications: z17.number().int().min(1).max(4096)
5263
+ applications: z18.number().int().min(1).max(4096)
4827
5264
  });
4828
- var stateValueSchema = z17.discriminatedUnion("kind", [
4829
- z17.strictObject({
4830
- kind: z17.literal("usage-cumulative"),
5265
+ var stateValueSchema = z18.discriminatedUnion("kind", [
5266
+ z18.strictObject({
5267
+ kind: z18.literal("usage-cumulative"),
4831
5268
  usage: canonicalUsageSchema,
4832
5269
  /**
4833
5270
  * Optional: absent on every record written before this field existed, which
@@ -4836,12 +5273,12 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4836
5273
  */
4837
5274
  appliedDelivery: appliedDeliverySchema.optional()
4838
5275
  }),
4839
- z17.strictObject({
4840
- kind: z17.literal("sequence"),
5276
+ z18.strictObject({
5277
+ kind: z18.literal("sequence"),
4841
5278
  next: sequenceNumberSchema
4842
5279
  }),
4843
- z17.strictObject({
4844
- kind: z17.literal("attributes"),
5280
+ z18.strictObject({
5281
+ kind: z18.literal("attributes"),
4845
5282
  attributes: attributesSchema
4846
5283
  }),
4847
5284
  /**
@@ -4850,8 +5287,8 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4850
5287
  * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
4851
5288
  * bounded canonical shape, never a payload fragment.
4852
5289
  */
4853
- z17.strictObject({
4854
- kind: z17.literal("session-model"),
5290
+ z18.strictObject({
5291
+ kind: z18.literal("session-model"),
4855
5292
  model: modelDescriptorSchema
4856
5293
  }),
4857
5294
  /**
@@ -4865,36 +5302,36 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4865
5302
  * a series digest only; the series' attributes are re-supplied by the caller
4866
5303
  * and never read back from disk.
4867
5304
  */
4868
- z17.strictObject({
4869
- kind: z17.literal("metric-series"),
5305
+ z18.strictObject({
5306
+ kind: z18.literal("metric-series"),
4870
5307
  /** Start of the cumulative interval. */
4871
5308
  startTimeMillis: epochMillisSchema,
4872
5309
  /** Counters: the running total. */
4873
- value: z17.number().finite().min(0).optional(),
5310
+ value: z18.number().finite().min(0).optional(),
4874
5311
  /** Histograms: the running aggregation. */
4875
- histogram: z17.strictObject({
4876
- count: z17.number().int().min(0),
4877
- sum: z17.number().finite().min(0),
4878
- min: z17.number().finite(),
4879
- max: z17.number().finite(),
4880
- bucketCounts: z17.array(z17.number().int().min(0)).max(64)
5312
+ histogram: z18.strictObject({
5313
+ count: z18.number().int().min(0),
5314
+ sum: z18.number().finite().min(0),
5315
+ min: z18.number().finite(),
5316
+ max: z18.number().finite(),
5317
+ bucketCounts: z18.array(z18.number().int().min(0)).max(64)
4881
5318
  }).optional(),
4882
5319
  /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
4883
- appliedDelivery: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
5320
+ appliedDelivery: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
4884
5321
  }),
4885
- z17.strictObject({
4886
- kind: z17.literal("read-cursor"),
4887
- source: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
4888
- offset: z17.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
5322
+ z18.strictObject({
5323
+ kind: z18.literal("read-cursor"),
5324
+ source: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
5325
+ offset: z18.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
4889
5326
  })
4890
5327
  ]);
4891
- var stateRecordSchema = z17.strictObject({
5328
+ var stateRecordSchema = z18.strictObject({
4892
5329
  /** Incremented on each write; lets callers detect lost updates. */
4893
- revision: z17.number().int().min(0),
5330
+ revision: z18.number().int().min(0),
4894
5331
  updatedAt: epochMillisSchema,
4895
5332
  value: stateValueSchema
4896
5333
  });
4897
- var logLevelSchema = z17.enum(["silent", "error", "warn", "info", "debug"]);
5334
+ var logLevelSchema = z18.enum(["silent", "error", "warn", "info", "debug"]);
4898
5335
  var LOG_LEVEL_RANK = Object.freeze({
4899
5336
  silent: 0,
4900
5337
  error: 1,
@@ -4912,7 +5349,7 @@ var createNullLogger = () => ({
4912
5349
  });
4913
5350
 
4914
5351
  // src/runtime/target-resolution.ts
4915
- import * as path2 from "path";
5352
+ import * as path3 from "path";
4916
5353
 
4917
5354
  // src/privacy/workspace.ts
4918
5355
  var canonicalizeGitRemote = (remoteUrl) => {
@@ -4964,13 +5401,13 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
4964
5401
  // src/runtime/target-resolution.ts
4965
5402
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
4966
5403
  var absolutePathsOf = (hint) => {
4967
- const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
5404
+ const base = hint.baseDirectory !== void 0 && path3.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
4968
5405
  const resolved = [];
4969
5406
  for (const candidate of hint.paths) {
4970
- if (path2.isAbsolute(candidate)) {
4971
- resolved.push(path2.resolve(candidate));
5407
+ if (path3.isAbsolute(candidate)) {
5408
+ resolved.push(path3.resolve(candidate));
4972
5409
  } else if (base !== void 0) {
4973
- resolved.push(path2.resolve(base, candidate));
5410
+ resolved.push(path3.resolve(base, candidate));
4974
5411
  } else {
4975
5412
  return void 0;
4976
5413
  }
@@ -5049,9 +5486,9 @@ var resolveEventTargets = async (input) => {
5049
5486
  };
5050
5487
 
5051
5488
  // src/runtime/session-context.ts
5052
- import { open as open2 } from "fs/promises";
5053
- import * as path3 from "path";
5054
- import { z as z18 } from "zod";
5489
+ import { open as open3 } from "fs/promises";
5490
+ import * as path4 from "path";
5491
+ import { z as z19 } from "zod";
5055
5492
  var SESSION_CONTEXT_FILE_VERSION = 1;
5056
5493
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
5057
5494
  var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
@@ -5068,10 +5505,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
5068
5505
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
5069
5506
  var sessionContextFilePath = (dir, providerId, sessionId) => {
5070
5507
  const tool = sessionContextAgentTool(providerId);
5071
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
5508
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path4.isAbsolute(dir)) {
5072
5509
  return void 0;
5073
5510
  }
5074
- return path3.join(dir, tool, `${sessionId}.json`);
5511
+ return path4.join(dir, tool, `${sessionId}.json`);
5075
5512
  };
5076
5513
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
5077
5514
  "session.id",
@@ -5110,25 +5547,25 @@ var sanitizeSessionContextAttributes = (attributes) => {
5110
5547
  return kept;
5111
5548
  };
5112
5549
  var ISO_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
5113
- var isoInstantSchema = z18.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
5550
+ var isoInstantSchema = z19.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
5114
5551
  const millis = Date.parse(value);
5115
5552
  if (!Number.isFinite(millis)) {
5116
5553
  ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
5117
- return z18.NEVER;
5554
+ return z19.NEVER;
5118
5555
  }
5119
5556
  return millis;
5120
5557
  });
5121
- var segmentSchema = z18.object({
5558
+ var segmentSchema = z19.object({
5122
5559
  from: isoInstantSchema,
5123
5560
  to: isoInstantSchema.nullable(),
5124
- reason: z18.string().max(256).optional(),
5125
- attributes: z18.record(z18.string(), z18.unknown())
5561
+ reason: z19.string().max(256).optional(),
5562
+ attributes: z19.record(z19.string(), z19.unknown())
5126
5563
  });
5127
- var sessionContextFileSchema = z18.object({
5128
- version: z18.literal(SESSION_CONTEXT_FILE_VERSION),
5129
- agentTool: z18.string().max(64).optional(),
5130
- sessionId: z18.string().max(256).optional(),
5131
- segments: z18.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
5564
+ var sessionContextFileSchema = z19.object({
5565
+ version: z19.literal(SESSION_CONTEXT_FILE_VERSION),
5566
+ agentTool: z19.string().max(64).optional(),
5567
+ sessionId: z19.string().max(256).optional(),
5568
+ segments: z19.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
5132
5569
  });
5133
5570
  var parseSessionContextFile = (value, expected) => {
5134
5571
  const parsed = sessionContextFileSchema.safeParse(value);
@@ -5167,7 +5604,7 @@ var stampSessionContext = (events, segments) => events.map((event2) => {
5167
5604
  var readBounded = async (file, maxBytes) => {
5168
5605
  let handle;
5169
5606
  try {
5170
- handle = await open2(file, "r");
5607
+ handle = await open3(file, "r");
5171
5608
  } catch {
5172
5609
  return void 0;
5173
5610
  }
@@ -5241,7 +5678,7 @@ var createDirectorySessionContextReader = (options) => {
5241
5678
  };
5242
5679
 
5243
5680
  // src/runtime/hook.ts
5244
- var usageScopeSchema = z19.enum(["session", "generation", "subagent"]);
5681
+ var usageScopeSchema = z20.enum(["session", "generation", "subagent"]);
5245
5682
  var classifyDurability = (input) => {
5246
5683
  if (!input.attempted) {
5247
5684
  return "nothing-to-deliver";
@@ -6120,8 +6557,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
6120
6557
  };
6121
6558
 
6122
6559
  // src/runtime/git-worktree.ts
6123
- import { lstat, open as open3, stat as stat2 } from "fs/promises";
6124
- import * as path4 from "path";
6560
+ import { lstat, open as open4, stat as stat3 } from "fs/promises";
6561
+ import * as path5 from "path";
6125
6562
  var MAX_WORKTREE_WALK_DEPTH = 128;
6126
6563
  var MAX_GIT_FILE_BYTES = 4096;
6127
6564
  var MAX_CACHE_ENTRIES = 1024;
@@ -6132,7 +6569,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
6132
6569
  var readBounded2 = async (filePath) => {
6133
6570
  let handle;
6134
6571
  try {
6135
- handle = await open3(filePath, "r");
6572
+ handle = await open4(filePath, "r");
6136
6573
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
6137
6574
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
6138
6575
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -6153,7 +6590,7 @@ var parseHeadBranch = (head) => {
6153
6590
  return branch;
6154
6591
  };
6155
6592
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
6156
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
6593
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path5.resolve(base, target);
6157
6594
  var parseGitDirFile = (content, worktreeRoot) => {
6158
6595
  const line = firstLine(content);
6159
6596
  return resolveGitPath(
@@ -6173,26 +6610,26 @@ var isMissing = async (filePath) => {
6173
6610
  };
6174
6611
  var isDirectory = async (directory) => {
6175
6612
  try {
6176
- return (await stat2(directory)).isDirectory();
6613
+ return (await stat3(directory)).isDirectory();
6177
6614
  } catch {
6178
6615
  return false;
6179
6616
  }
6180
6617
  };
6181
6618
  var repositoryOf = async (worktreeRoot, gitDir) => {
6182
- const commonDirFile = path4.join(gitDir, "commondir");
6619
+ const commonDirFile = path5.join(gitDir, "commondir");
6183
6620
  const content = await readBounded2(commonDirFile);
6184
6621
  if (content === void 0) {
6185
6622
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
6186
6623
  }
6187
6624
  const commonDir = parseCommonDirFile(content, gitDir);
6188
- const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
6625
+ const mainRoot = commonDir !== void 0 && path5.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path5.dirname(commonDir) : void 0;
6189
6626
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
6190
6627
  };
6191
6628
  var probeDirectory = async (directory) => {
6192
- const dotGit = path4.join(directory, ".git");
6629
+ const dotGit = path5.join(directory, ".git");
6193
6630
  let info;
6194
6631
  try {
6195
- info = await stat2(dotGit);
6632
+ info = await stat3(dotGit);
6196
6633
  } catch {
6197
6634
  return ABSENT;
6198
6635
  }
@@ -6206,7 +6643,7 @@ var probeDirectory = async (directory) => {
6206
6643
  if (gitDir === void 0) {
6207
6644
  return INVALID;
6208
6645
  }
6209
- const head = await readBounded2(path4.join(gitDir, "HEAD"));
6646
+ const head = await readBounded2(path5.join(gitDir, "HEAD"));
6210
6647
  if (head === void 0) {
6211
6648
  return INVALID;
6212
6649
  }
@@ -6236,10 +6673,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6236
6673
  };
6237
6674
  const locate = async (absolutePath) => {
6238
6675
  try {
6239
- if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6676
+ if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6240
6677
  return void 0;
6241
6678
  }
6242
- let directory = path4.resolve(absolutePath);
6679
+ let directory = path5.resolve(absolutePath);
6243
6680
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
6244
6681
  const probe = await cachedProbe(directory);
6245
6682
  if (probe.kind === "worktree") {
@@ -6248,7 +6685,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6248
6685
  if (probe.kind === "invalid") {
6249
6686
  return void 0;
6250
6687
  }
6251
- const parent = path4.dirname(directory);
6688
+ const parent = path5.dirname(directory);
6252
6689
  if (parent === directory) {
6253
6690
  return void 0;
6254
6691
  }
@@ -6264,28 +6701,28 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6264
6701
 
6265
6702
  // src/state/filesystem-store.ts
6266
6703
  import { randomBytes as randomBytes2 } from "crypto";
6267
- import { mkdir, open as open4, readFile, readdir, rename, stat as stat3, unlink, writeFile } from "fs/promises";
6268
- import * as path5 from "path";
6704
+ import { mkdir, open as open5, readFile, readdir as readdir2, rename, stat as stat4, unlink, writeFile } from "fs/promises";
6705
+ import * as path6 from "path";
6269
6706
 
6270
6707
  // src/state/keys.ts
6271
- import { createHash as createHash6 } from "crypto";
6708
+ import { createHash as createHash7 } from "crypto";
6272
6709
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
6273
6710
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
6274
6711
  var sanitizeSegment = (segment) => {
6275
6712
  if (isSafeSegment(segment)) {
6276
6713
  return segment;
6277
6714
  }
6278
- return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
6715
+ return `h_${createHash7("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
6279
6716
  };
6280
6717
  var namespaceSegments = (namespace) => [
6281
6718
  sanitizeSegment(namespace.providerId),
6282
6719
  sanitizeSegment(namespace.installationId)
6283
6720
  ];
6284
- var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
6721
+ var keyDigest = (key) => createHash7("sha256").update(key, "utf8").digest("hex");
6285
6722
 
6286
6723
  // src/state/filesystem-store.ts
6287
6724
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
6288
- var sleep = (millis) => new Promise((resolve3) => {
6725
+ var sleep2 = (millis) => new Promise((resolve3) => {
6289
6726
  setTimeout(resolve3, millis);
6290
6727
  });
6291
6728
  var wrapFsError = (thrown, operation) => {
@@ -6296,10 +6733,10 @@ var wrapFsError = (thrown, operation) => {
6296
6733
  };
6297
6734
  var createFilesystemStateStore = (options) => {
6298
6735
  const [providerSegment, installationSegment] = namespaceSegments(options);
6299
- const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
6300
- const recordsDir = path5.join(baseDir, "records");
6301
- const quarantineDir = path5.join(baseDir, "quarantine");
6302
- const locksDir = path5.join(baseDir, "locks");
6736
+ const baseDir = path6.join(options.rootDir, providerSegment, installationSegment);
6737
+ const recordsDir = path6.join(baseDir, "records");
6738
+ const quarantineDir = path6.join(baseDir, "quarantine");
6739
+ const locksDir = path6.join(baseDir, "locks");
6303
6740
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
6304
6741
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
6305
6742
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -6323,11 +6760,11 @@ var createFilesystemStateStore = (options) => {
6323
6760
  throw wrapFsError(thrown, "ensure-dirs");
6324
6761
  }
6325
6762
  };
6326
- const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
6327
- const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6328
- const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6763
+ const recordPath = (key) => path6.join(recordsDir, `${keyDigest(key)}.json`);
6764
+ const tempPath = (key) => path6.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6765
+ const lockPath = (sessionId) => path6.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6329
6766
  const quarantine = async (filePath, key, reason) => {
6330
- const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6767
+ const dest = path6.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6331
6768
  try {
6332
6769
  await rename(filePath, dest);
6333
6770
  } catch {
@@ -6391,7 +6828,7 @@ var createFilesystemStateStore = (options) => {
6391
6828
  const startedAt = options.clock.monotonicMillis();
6392
6829
  for (; ; ) {
6393
6830
  try {
6394
- const handle = await open4(filePath, "wx");
6831
+ const handle = await open5(filePath, "wx");
6395
6832
  try {
6396
6833
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
6397
6834
  } finally {
@@ -6420,7 +6857,7 @@ var createFilesystemStateStore = (options) => {
6420
6857
  } catch {
6421
6858
  }
6422
6859
  try {
6423
- const stats = await stat3(filePath);
6860
+ const stats = await stat4(filePath);
6424
6861
  return Date.now() - stats.mtimeMs > lockStaleMillis;
6425
6862
  } catch {
6426
6863
  return "gone";
@@ -6436,7 +6873,7 @@ var createFilesystemStateStore = (options) => {
6436
6873
  if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
6437
6874
  throw new StateLockTimeoutError(sessionId, timeoutMillis);
6438
6875
  }
6439
- await sleep(lockPollIntervalMillis);
6876
+ await sleep2(lockPollIntervalMillis);
6440
6877
  }
6441
6878
  };
6442
6879
  return {
@@ -6460,7 +6897,7 @@ var createFilesystemStateStore = (options) => {
6460
6897
  await ensureDirs();
6461
6898
  let entries;
6462
6899
  try {
6463
- entries = await readdir(recordsDir);
6900
+ entries = await readdir2(recordsDir);
6464
6901
  } catch (thrown) {
6465
6902
  if (isErrnoException(thrown, "ENOENT")) {
6466
6903
  return [];
@@ -6474,7 +6911,7 @@ var createFilesystemStateStore = (options) => {
6474
6911
  }
6475
6912
  let raw;
6476
6913
  try {
6477
- raw = await readFile(path5.join(recordsDir, entry), "utf8");
6914
+ raw = await readFile(path6.join(recordsDir, entry), "utf8");
6478
6915
  } catch {
6479
6916
  continue;
6480
6917
  }
@@ -6512,7 +6949,7 @@ var createFilesystemStateStore = (options) => {
6512
6949
  let scanned = 0;
6513
6950
  let entries;
6514
6951
  try {
6515
- entries = await readdir(recordsDir);
6952
+ entries = await readdir2(recordsDir);
6516
6953
  } catch (thrown) {
6517
6954
  if (!isErrnoException(thrown, "ENOENT")) {
6518
6955
  throw wrapFsError(thrown, "prune");
@@ -6527,7 +6964,7 @@ var createFilesystemStateStore = (options) => {
6527
6964
  continue;
6528
6965
  }
6529
6966
  scanned += 1;
6530
- const filePath = path5.join(recordsDir, entry);
6967
+ const filePath = path6.join(recordsDir, entry);
6531
6968
  try {
6532
6969
  const raw = await readFile(filePath, "utf8");
6533
6970
  const envelope = JSON.parse(raw);
@@ -6542,12 +6979,12 @@ var createFilesystemStateStore = (options) => {
6542
6979
  }
6543
6980
  let lockEntries;
6544
6981
  try {
6545
- lockEntries = await readdir(locksDir);
6982
+ lockEntries = await readdir2(locksDir);
6546
6983
  } catch {
6547
6984
  lockEntries = [];
6548
6985
  }
6549
6986
  for (const entry of lockEntries) {
6550
- const filePath = path5.join(locksDir, entry);
6987
+ const filePath = path6.join(locksDir, entry);
6551
6988
  try {
6552
6989
  const raw = await readFile(filePath, "utf8");
6553
6990
  const parsed = JSON.parse(raw);
@@ -6599,8 +7036,8 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6599
7036
 
6600
7037
  // src/telemetry/spool-queue.ts
6601
7038
  import { randomBytes as randomBytes3 } from "crypto";
6602
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
6603
- import * as path6 from "path";
7039
+ import { mkdir as mkdir2, open as open6, readFile as readFile2, readdir as readdir3, rename as rename2, stat as stat5, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
7040
+ import * as path7 from "path";
6604
7041
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
6605
7042
  total: 0,
6606
7043
  age: 0,
@@ -6616,7 +7053,7 @@ var enqueuedAtOf = (fileName) => {
6616
7053
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
6617
7054
  var readSpoolDropCounts = async (queueDir) => {
6618
7055
  try {
6619
- const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
7056
+ const parsed = JSON.parse(await readFile2(path7.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6620
7057
  if (typeof parsed !== "object" || parsed === null) {
6621
7058
  return EMPTY_SPOOL_DROP_COUNTS;
6622
7059
  }
@@ -6637,7 +7074,7 @@ var readSpoolDropCounts = async (queueDir) => {
6637
7074
  var readSpoolQueueStats = async (queueDir) => {
6638
7075
  let entries;
6639
7076
  try {
6640
- entries = await readdir2(queueDir);
7077
+ entries = await readdir3(queueDir);
6641
7078
  } catch {
6642
7079
  return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
6643
7080
  }
@@ -6645,7 +7082,7 @@ var readSpoolQueueStats = async (queueDir) => {
6645
7082
  let bytes = 0;
6646
7083
  for (const file of files) {
6647
7084
  try {
6648
- bytes += (await stat4(path6.join(queueDir, file))).size;
7085
+ bytes += (await stat5(path7.join(queueDir, file))).size;
6649
7086
  } catch {
6650
7087
  }
6651
7088
  }
@@ -6659,7 +7096,8 @@ var readSpoolQueueStats = async (queueDir) => {
6659
7096
  };
6660
7097
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
6661
7098
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
6662
- var CLAIM_MARKER = ".claimed-";
7099
+ var CLAIM_SUFFIX = ".claim";
7100
+ var RELEASING_SUFFIX = ".releasing";
6663
7101
  var isClaimOwnerAlive = (pid) => {
6664
7102
  if (!Number.isSafeInteger(pid) || pid <= 0) {
6665
7103
  return true;
@@ -6675,10 +7113,38 @@ var isClaimOwnerAlive = (pid) => {
6675
7113
  }
6676
7114
  };
6677
7115
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
7116
+ var readClaim = async (claimPath) => {
7117
+ try {
7118
+ const parsed = JSON.parse(await readFile2(claimPath, "utf8"));
7119
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
7120
+ } catch {
7121
+ return void 0;
7122
+ }
7123
+ };
7124
+ var releaseClaim = async (claimPath, token) => {
7125
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes3(4).toString("hex")}${RELEASING_SUFFIX}`;
7126
+ for (let attempt = 1; ; attempt += 1) {
7127
+ try {
7128
+ await rename2(claimPath, tombstone);
7129
+ break;
7130
+ } catch (thrown) {
7131
+ if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
7132
+ return;
7133
+ }
7134
+ await new Promise((resolve3) => setTimeout(resolve3, 10 * attempt));
7135
+ }
7136
+ }
7137
+ const captured = await readClaim(tombstone);
7138
+ if (captured !== void 0 && captured.token !== token) {
7139
+ await rename2(tombstone, claimPath).catch(() => void 0);
7140
+ return;
7141
+ }
7142
+ await unlink2(tombstone).catch(() => void 0);
7143
+ };
6678
7144
  var createSpoolQueue = (options) => {
6679
7145
  const [providerSegment, installationSegment] = namespaceSegments(options);
6680
- const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6681
- const corruptDir = path6.join(
7146
+ const queueDir = path7.join(options.rootDir, providerSegment, installationSegment, options.queueName);
7147
+ const corruptDir = path7.join(
6682
7148
  options.rootDir,
6683
7149
  providerSegment,
6684
7150
  installationSegment,
@@ -6704,7 +7170,7 @@ var createSpoolQueue = (options) => {
6704
7170
  const listSorted = async () => {
6705
7171
  let entries;
6706
7172
  try {
6707
- entries = await readdir2(queueDir);
7173
+ entries = await readdir3(queueDir);
6708
7174
  } catch (thrown) {
6709
7175
  if (isErrnoException2(thrown, "ENOENT")) {
6710
7176
  return [];
@@ -6725,9 +7191,9 @@ var createSpoolQueue = (options) => {
6725
7191
  [reason]: current[reason] + dropped,
6726
7192
  lastDroppedAt: options.clock.now()
6727
7193
  };
6728
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
7194
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6729
7195
  await writeFile2(tmp, JSON.stringify(next), "utf8");
6730
- await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
7196
+ await rename2(tmp, path7.join(queueDir, SPOOL_DROPS_FILE));
6731
7197
  } catch {
6732
7198
  }
6733
7199
  options.logger?.warn("durable spool dropped batches", {
@@ -6743,7 +7209,7 @@ var createSpoolQueue = (options) => {
6743
7209
  let bytes = 0;
6744
7210
  if (options.maxBytes !== void 0) {
6745
7211
  try {
6746
- bytes = (await stat4(path6.join(queueDir, name))).size;
7212
+ bytes = (await stat5(path7.join(queueDir, name))).size;
6747
7213
  } catch {
6748
7214
  continue;
6749
7215
  }
@@ -6757,7 +7223,7 @@ var createSpoolQueue = (options) => {
6757
7223
  let removed = 0;
6758
7224
  for (const file of files) {
6759
7225
  try {
6760
- await unlink2(path6.join(queueDir, file.name));
7226
+ await unlink2(path7.join(queueDir, file.name));
6761
7227
  removed += 1;
6762
7228
  } catch {
6763
7229
  }
@@ -6817,33 +7283,63 @@ var createSpoolQueue = (options) => {
6817
7283
  }
6818
7284
  }
6819
7285
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
6820
- const target = path6.join(queueDir, fileName);
6821
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
7286
+ const target = path7.join(queueDir, fileName);
7287
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6822
7288
  await writeFile2(tmp, serialized, "utf8");
6823
7289
  await rename2(tmp, target);
6824
7290
  return { spooled: true };
6825
7291
  };
7292
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
7293
+ const staleClaim = async (claimPath) => {
7294
+ const claim = await readClaim(claimPath);
7295
+ const now = Date.now();
7296
+ if (claim !== void 0) {
7297
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
7298
+ }
7299
+ try {
7300
+ return now - (await stat5(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
7301
+ } catch {
7302
+ return { stale: false };
7303
+ }
7304
+ };
6826
7305
  const releaseStaleClaims = async () => {
6827
7306
  let entries;
6828
7307
  try {
6829
- entries = await readdir2(queueDir);
7308
+ entries = await readdir3(queueDir);
6830
7309
  } catch {
6831
7310
  return;
6832
7311
  }
6833
7312
  const now = Date.now();
6834
7313
  for (const entry of entries) {
6835
- const marker = entry.lastIndexOf(CLAIM_MARKER);
6836
- if (marker <= 0) {
6837
- continue;
7314
+ const entryPath = path7.join(queueDir, entry);
7315
+ if (entry.endsWith(CLAIM_SUFFIX)) {
7316
+ const staleness = await staleClaim(entryPath);
7317
+ if (staleness.stale) {
7318
+ await releaseClaim(entryPath, staleness.token);
7319
+ }
7320
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
7321
+ try {
7322
+ if (now - (await stat5(entryPath)).mtimeMs > claimStaleMillis) {
7323
+ await unlink2(entryPath);
7324
+ }
7325
+ } catch {
7326
+ }
6838
7327
  }
6839
- const claimPath = path6.join(queueDir, entry);
6840
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
7328
+ }
7329
+ };
7330
+ const claimBatch = async (claimPath) => {
7331
+ const token = randomBytes3(16).toString("hex");
7332
+ try {
7333
+ const handle = await open6(claimPath, "wx");
6841
7334
  try {
6842
- if (!isClaimOwnerAlive(owner) || now - (await stat4(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
6843
- await rename2(claimPath, path6.join(queueDir, entry.slice(0, marker)));
6844
- }
6845
- } catch {
7335
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
7336
+ await handle.writeFile(JSON.stringify(contents), "utf8");
7337
+ } finally {
7338
+ await handle.close();
6846
7339
  }
7340
+ return token;
7341
+ } catch {
7342
+ return void 0;
6847
7343
  }
6848
7344
  };
6849
7345
  const drain = async (send, drainOptions) => {
@@ -6867,21 +7363,7 @@ var createSpoolQueue = (options) => {
6867
7363
  let failed = 0;
6868
7364
  let quarantined = 0;
6869
7365
  let index = 0;
6870
- for (; index < files.length && index < cap; index += 1) {
6871
- const fileName = files[index];
6872
- if (fileName === void 0) {
6873
- break;
6874
- }
6875
- const queuedPath = path6.join(queueDir, fileName);
6876
- const filePath = path6.join(
6877
- queueDir,
6878
- `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes3(4).toString("hex")}`
6879
- );
6880
- try {
6881
- await rename2(queuedPath, filePath);
6882
- } catch {
6883
- continue;
6884
- }
7366
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
6885
7367
  const quarantine = async (rejection) => {
6886
7368
  quarantined += 1;
6887
7369
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6890,7 +7372,7 @@ var createSpoolQueue = (options) => {
6890
7372
  "spool.queue": options.queueName
6891
7373
  });
6892
7374
  try {
6893
- await rename2(filePath, path6.join(corruptDir, fileName));
7375
+ await rename2(filePath, path7.join(corruptDir, fileName));
6894
7376
  } catch {
6895
7377
  await unlink2(filePath).catch(() => void 0);
6896
7378
  }
@@ -6900,17 +7382,17 @@ var createSpoolQueue = (options) => {
6900
7382
  text = await readFile2(filePath, "utf8");
6901
7383
  } catch (thrown) {
6902
7384
  if (thrown?.code === "ENOENT") {
6903
- continue;
7385
+ return "next";
6904
7386
  }
6905
7387
  await quarantine("unreadable");
6906
- continue;
7388
+ return "next";
6907
7389
  }
6908
7390
  let parsed;
6909
7391
  try {
6910
7392
  parsed = JSON.parse(text);
6911
7393
  } catch {
6912
7394
  await quarantine("unparseable-json");
6913
- continue;
7395
+ return "next";
6914
7396
  }
6915
7397
  const validation = options.validate(parsed, {
6916
7398
  providerId: options.providerId,
@@ -6918,7 +7400,10 @@ var createSpoolQueue = (options) => {
6918
7400
  });
6919
7401
  if ("rejection" in validation) {
6920
7402
  await quarantine(validation.rejection);
6921
- continue;
7403
+ return "next";
7404
+ }
7405
+ if ((await readClaim(claimPath))?.token !== token) {
7406
+ return "next";
6922
7407
  }
6923
7408
  let delivered;
6924
7409
  try {
@@ -6930,14 +7415,34 @@ var createSpoolQueue = (options) => {
6930
7415
  if (await unlink2(filePath).then(() => true, () => false)) {
6931
7416
  await recordDrops("rejected", 1);
6932
7417
  }
6933
- continue;
7418
+ return "next";
6934
7419
  }
6935
7420
  if (delivered) {
6936
7421
  await unlink2(filePath).catch(() => void 0);
6937
7422
  drained += 1;
6938
- } else {
6939
- await rename2(filePath, queuedPath).catch(() => void 0);
6940
- failed += 1;
7423
+ return "next";
7424
+ }
7425
+ failed += 1;
7426
+ return "stop";
7427
+ };
7428
+ for (; index < files.length && index < cap; index += 1) {
7429
+ const fileName = files[index];
7430
+ if (fileName === void 0) {
7431
+ break;
7432
+ }
7433
+ const filePath = path7.join(queueDir, fileName);
7434
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
7435
+ const token = await claimBatch(claimPath);
7436
+ if (token === void 0) {
7437
+ continue;
7438
+ }
7439
+ let outcome;
7440
+ try {
7441
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
7442
+ } finally {
7443
+ await releaseClaim(claimPath, token);
7444
+ }
7445
+ if (outcome === "stop") {
6941
7446
  break;
6942
7447
  }
6943
7448
  }
@@ -7231,9 +7736,220 @@ var createFileDurableSpool = (options) => createSpoolQueue({
7231
7736
  validate: validateSpoolBatch
7232
7737
  });
7233
7738
 
7739
+ // src/telemetry/endpoint-health.ts
7740
+ import { createHash as createHash8, randomBytes as randomBytes4 } from "crypto";
7741
+ import { mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
7742
+ import * as http from "http";
7743
+ import * as https from "https";
7744
+ import path8 from "path";
7745
+ import { ExportResultCode } from "@opentelemetry/core";
7746
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
7747
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
7748
+ "ECONNREFUSED",
7749
+ "ECONNRESET",
7750
+ "ETIMEDOUT",
7751
+ "EPIPE",
7752
+ "EHOSTUNREACH",
7753
+ "ENETUNREACH",
7754
+ "EHOSTDOWN",
7755
+ "ENETDOWN",
7756
+ "EAI_AGAIN",
7757
+ "ENOTFOUND",
7758
+ ENDPOINT_DOWN_ERROR_CODE
7759
+ ]);
7760
+ var isUnreachableExportFailure = (result) => {
7761
+ if (result.code === ExportResultCode.SUCCESS) {
7762
+ return false;
7763
+ }
7764
+ const error = result.error;
7765
+ const code = error?.code;
7766
+ if (typeof code === "string") {
7767
+ return UNREACHABLE_NETWORK_CODES.has(code);
7768
+ }
7769
+ if (code !== void 0) {
7770
+ return false;
7771
+ }
7772
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
7773
+ };
7774
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
7775
+ const target = agent;
7776
+ const original = target.createConnection.bind(agent);
7777
+ target.createConnection = (options, callback) => {
7778
+ const socket = original(options, callback);
7779
+ if (socket !== void 0 && socket.connecting) {
7780
+ const timer = setTimeout(() => {
7781
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
7782
+ socket.destroy(error);
7783
+ }, connectTimeoutMillis);
7784
+ timer.unref();
7785
+ const clear = () => {
7786
+ clearTimeout(timer);
7787
+ };
7788
+ socket.once("connect", clear);
7789
+ socket.once("close", clear);
7790
+ }
7791
+ return socket;
7792
+ };
7793
+ return agent;
7794
+ };
7795
+ var boundedExporterOptions = (exporter) => {
7796
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
7797
+ let agents = {};
7798
+ return {
7799
+ timeoutMillis,
7800
+ httpAgentOptions: (protocol) => {
7801
+ if (protocol === "https:") {
7802
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
7803
+ return agents.https;
7804
+ }
7805
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
7806
+ return agents.http;
7807
+ }
7808
+ };
7809
+ };
7810
+ var parseMark = (raw) => {
7811
+ try {
7812
+ const parsed = JSON.parse(raw);
7813
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
7814
+ downUntil: parsed.downUntil,
7815
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
7816
+ } : void 0;
7817
+ } catch {
7818
+ return void 0;
7819
+ }
7820
+ };
7821
+ var originOf = (url) => {
7822
+ if (url === void 0) {
7823
+ return void 0;
7824
+ }
7825
+ try {
7826
+ return new URL(url).origin;
7827
+ } catch {
7828
+ return void 0;
7829
+ }
7830
+ };
7831
+ var createEndpointHealth = (options) => {
7832
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
7833
+ const gates = /* @__PURE__ */ new Map();
7834
+ const createGate = (origin) => {
7835
+ const digest3 = createHash8("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
7836
+ const dir = options.rootDir === void 0 ? void 0 : path8.join(options.rootDir, "endpoint-health");
7837
+ const file = dir === void 0 ? void 0 : path8.join(dir, `${digest3}.json`);
7838
+ let downUntil = 0;
7839
+ let failures = 0;
7840
+ let marked = false;
7841
+ let loaded;
7842
+ let warned = false;
7843
+ const write = async (mark) => {
7844
+ if (file === void 0 || dir === void 0) {
7845
+ return;
7846
+ }
7847
+ try {
7848
+ await mkdir3(dir, { recursive: true });
7849
+ const tmp = path8.join(dir, `.tmp-${randomBytes4(6).toString("hex")}.json`);
7850
+ await writeFile3(tmp, `${JSON.stringify(mark)}
7851
+ `);
7852
+ await rename3(tmp, file);
7853
+ marked = true;
7854
+ } catch {
7855
+ }
7856
+ };
7857
+ const load = () => {
7858
+ loaded ??= (async () => {
7859
+ if (file === void 0) {
7860
+ return;
7861
+ }
7862
+ let raw;
7863
+ try {
7864
+ raw = await readFile3(file, "utf8");
7865
+ } catch {
7866
+ return;
7867
+ }
7868
+ marked = true;
7869
+ const mark = parseMark(raw);
7870
+ if (mark === void 0) {
7871
+ return;
7872
+ }
7873
+ failures = mark.failures;
7874
+ const now = options.clock.now();
7875
+ if (mark.downUntil > now) {
7876
+ downUntil = mark.downUntil;
7877
+ return;
7878
+ }
7879
+ await write({ downUntil: now + options.probeMillis, failures });
7880
+ })();
7881
+ return loaded;
7882
+ };
7883
+ return {
7884
+ available: async () => {
7885
+ if (downMillis === 0) {
7886
+ return true;
7887
+ }
7888
+ await load();
7889
+ return options.clock.now() >= downUntil;
7890
+ },
7891
+ record: async (result) => {
7892
+ if (downMillis === 0) {
7893
+ return;
7894
+ }
7895
+ if (!isUnreachableExportFailure(result)) {
7896
+ if (!marked && downUntil === 0) {
7897
+ return;
7898
+ }
7899
+ downUntil = 0;
7900
+ failures = 0;
7901
+ marked = false;
7902
+ if (file !== void 0) {
7903
+ await unlink3(file).catch(() => void 0);
7904
+ }
7905
+ return;
7906
+ }
7907
+ failures += 1;
7908
+ downUntil = options.clock.now() + downMillis;
7909
+ if (!warned) {
7910
+ warned = true;
7911
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
7912
+ "export.endpoint_down_millis": downMillis,
7913
+ "export.endpoint_failures": failures
7914
+ });
7915
+ }
7916
+ await write({ downUntil, failures });
7917
+ }
7918
+ };
7919
+ };
7920
+ return {
7921
+ gateFor: (url) => {
7922
+ const origin = originOf(url);
7923
+ if (origin === void 0) {
7924
+ return void 0;
7925
+ }
7926
+ let gate = gates.get(origin);
7927
+ if (gate === void 0) {
7928
+ gate = createGate(origin);
7929
+ gates.set(origin, gate);
7930
+ }
7931
+ return gate;
7932
+ }
7933
+ };
7934
+ };
7935
+ var guardExport = async (gate, send) => {
7936
+ if (gate === void 0) {
7937
+ return send();
7938
+ }
7939
+ if (!await gate.available()) {
7940
+ return {
7941
+ code: ExportResultCode.FAILED,
7942
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
7943
+ };
7944
+ }
7945
+ const result = await send();
7946
+ await gate.record(result).catch(() => void 0);
7947
+ return result;
7948
+ };
7949
+
7234
7950
  // src/telemetry/otlp-log-sink.ts
7235
7951
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
7236
- import { ExportResultCode } from "@opentelemetry/core";
7952
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
7237
7953
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
7238
7954
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
7239
7955
 
@@ -7814,12 +8530,16 @@ var createOtlpLogSink = (options) => {
7814
8530
  const exporter = new OTLPLogExporter({
7815
8531
  url: deliverability.endpoint,
7816
8532
  headers: { ...options.headers },
7817
- timeoutMillis: options.exporter.timeoutMillis
8533
+ ...boundedExporterOptions(options.exporter)
7818
8534
  });
8535
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
7819
8536
  let shutdownCompleted = false;
7820
- const exportRecords = (records) => new Promise((resolve3) => {
7821
- exporter.export([...records], (result) => resolve3(result));
7822
- });
8537
+ const exportRecords = (records) => guardExport(
8538
+ gate,
8539
+ () => new Promise((resolve3) => {
8540
+ exporter.export([...records], (result) => resolve3(result));
8541
+ })
8542
+ );
7823
8543
  const toSpoolBatch = (records, batchResource) => ({
7824
8544
  providerId: options.providerId,
7825
8545
  installationId: options.installationId,
@@ -7837,7 +8557,7 @@ var createOtlpLogSink = (options) => {
7837
8557
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
7838
8558
  );
7839
8559
  const result = await exportRecords(records);
7840
- if (result.code === ExportResultCode.SUCCESS) {
8560
+ if (result.code === ExportResultCode2.SUCCESS) {
7841
8561
  return true;
7842
8562
  }
7843
8563
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -7883,11 +8603,11 @@ var createOtlpLogSink = (options) => {
7883
8603
  result = await exportRecords(batch);
7884
8604
  } catch (thrown) {
7885
8605
  result = {
7886
- code: ExportResultCode.FAILED,
8606
+ code: ExportResultCode2.FAILED,
7887
8607
  error: thrown instanceof Error ? thrown : new Error("export threw")
7888
8608
  };
7889
8609
  }
7890
- if (result.code === ExportResultCode.SUCCESS) {
8610
+ if (result.code === ExportResultCode2.SUCCESS) {
7891
8611
  accepted += batch.length;
7892
8612
  health.recordSuccess(batch.length, options.clock.now());
7893
8613
  continue;
@@ -7928,6 +8648,9 @@ var createOtlpLogSink = (options) => {
7928
8648
  if (options.spool === void 0) {
7929
8649
  return { drained: 0, remaining: 0, failed: 0 };
7930
8650
  }
8651
+ if (gate !== void 0 && !await gate.available()) {
8652
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
8653
+ }
7931
8654
  const result = await options.spool.drain(sendSerializedBatch, {
7932
8655
  ...maxBatches === void 0 ? {} : { maxBatches }
7933
8656
  });
@@ -7965,7 +8688,7 @@ var createOtlpLogSink = (options) => {
7965
8688
 
7966
8689
  // src/telemetry/otlp-metric-sink.ts
7967
8690
  import { ValueType } from "@opentelemetry/api";
7968
- import { ExportResultCode as ExportResultCode2, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
8691
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
7969
8692
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
7970
8693
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
7971
8694
  import {
@@ -8109,10 +8832,12 @@ var createOtlpMetricSink = (options) => {
8109
8832
  const exporter = new OTLPMetricExporter({
8110
8833
  url: deliverability.endpoint,
8111
8834
  headers: { ...options.headers },
8112
- timeoutMillis: options.exporter.timeoutMillis
8835
+ ...boundedExporterOptions(options.exporter)
8113
8836
  });
8837
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
8114
8838
  let shutdownCompleted = false;
8115
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
8839
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
8840
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
8116
8841
  const payload = {
8117
8842
  resource: batchResource,
8118
8843
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -8121,7 +8846,7 @@ var createOtlpMetricSink = (options) => {
8121
8846
  exporter.export(payload, (result) => resolve3(result));
8122
8847
  } catch (thrown) {
8123
8848
  resolve3({
8124
- code: ExportResultCode2.FAILED,
8849
+ code: ExportResultCode3.FAILED,
8125
8850
  error: thrown instanceof Error ? thrown : new Error("export threw")
8126
8851
  });
8127
8852
  }
@@ -8142,7 +8867,7 @@ var createOtlpMetricSink = (options) => {
8142
8867
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
8143
8868
  );
8144
8869
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
8145
- if (result.code === ExportResultCode2.SUCCESS) {
8870
+ if (result.code === ExportResultCode3.SUCCESS) {
8146
8871
  return true;
8147
8872
  }
8148
8873
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -8153,7 +8878,7 @@ var createOtlpMetricSink = (options) => {
8153
8878
  }
8154
8879
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
8155
8880
  const result = await exportResourceMetrics(points, batchResource, scope);
8156
- if (result.code === ExportResultCode2.SUCCESS) {
8881
+ if (result.code === ExportResultCode3.SUCCESS) {
8157
8882
  health.recordSuccess(points.length, options.clock.now());
8158
8883
  return { accepted: points.length, rejected: 0, errors: [] };
8159
8884
  }
@@ -8193,6 +8918,9 @@ var createOtlpMetricSink = (options) => {
8193
8918
  if (options.spool === void 0) {
8194
8919
  return { drained: 0, remaining: 0, failed: 0 };
8195
8920
  }
8921
+ if (gate !== void 0 && !await gate.available()) {
8922
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
8923
+ }
8196
8924
  const result = await options.spool.drain(sendSerializedBatch, {
8197
8925
  ...maxBatches === void 0 ? {} : { maxBatches }
8198
8926
  });
@@ -8230,7 +8958,7 @@ var createOtlpMetricSink = (options) => {
8230
8958
  };
8231
8959
 
8232
8960
  // src/telemetry/otlp-sink.ts
8233
- import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
8961
+ import { ExportResultCode as ExportResultCode4 } from "@opentelemetry/core";
8234
8962
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
8235
8963
  var chunk2 = (items, size) => {
8236
8964
  if (size <= 0 || items.length <= size) {
@@ -8308,12 +9036,16 @@ var createOtlpTraceSink = (options) => {
8308
9036
  const exporter = new OTLPTraceExporter({
8309
9037
  url: options.exporter.endpoint,
8310
9038
  headers: { ...options.headers },
8311
- timeoutMillis: options.exporter.timeoutMillis
9039
+ ...boundedExporterOptions(options.exporter)
8312
9040
  });
9041
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
8313
9042
  let shutdownCompleted = false;
8314
- const exportSpans = (spans) => new Promise((resolve3) => {
8315
- exporter.export([...spans], (result) => resolve3(result));
8316
- });
9043
+ const exportSpans = (spans) => guardExport(
9044
+ gate,
9045
+ () => new Promise((resolve3) => {
9046
+ exporter.export([...spans], (result) => resolve3(result));
9047
+ })
9048
+ );
8317
9049
  const toSpoolBatch = (spans, batchResource) => ({
8318
9050
  providerId: options.providerId,
8319
9051
  installationId: options.installationId,
@@ -8326,7 +9058,7 @@ var createOtlpTraceSink = (options) => {
8326
9058
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
8327
9059
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
8328
9060
  const result = await exportSpans(spans);
8329
- if (result.code === ExportResultCode3.SUCCESS) {
9061
+ if (result.code === ExportResultCode4.SUCCESS) {
8330
9062
  return true;
8331
9063
  }
8332
9064
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -8365,9 +9097,9 @@ var createOtlpTraceSink = (options) => {
8365
9097
  try {
8366
9098
  result = await exportSpans(batch);
8367
9099
  } catch (thrown) {
8368
- result = { code: ExportResultCode3.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
9100
+ result = { code: ExportResultCode4.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
8369
9101
  }
8370
- if (result.code === ExportResultCode3.SUCCESS) {
9102
+ if (result.code === ExportResultCode4.SUCCESS) {
8371
9103
  accepted += batch.length;
8372
9104
  health.recordSuccess(batch.length, options.clock.now());
8373
9105
  continue;
@@ -8404,6 +9136,9 @@ var createOtlpTraceSink = (options) => {
8404
9136
  if (options.spool === void 0) {
8405
9137
  return { drained: 0, remaining: 0, failed: 0 };
8406
9138
  }
9139
+ if (gate !== void 0 && !await gate.available()) {
9140
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
9141
+ }
8407
9142
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
8408
9143
  if (result.drained > 0) {
8409
9144
  health.recordSuccess(result.drained, options.clock.now());
@@ -8538,6 +9273,13 @@ var createExportDestinationSinks = (options) => {
8538
9273
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
8539
9274
  const destinations = [];
8540
9275
  const skipped = [];
9276
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
9277
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
9278
+ clock: options.clock,
9279
+ ...options.logger === void 0 ? {} : { logger: options.logger },
9280
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
9281
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
9282
+ });
8541
9283
  for (const destination of resolveExportDestinations(options.exporter)) {
8542
9284
  let headers;
8543
9285
  let logHeaders;
@@ -8597,6 +9339,7 @@ var createExportDestinationSinks = (options) => {
8597
9339
  const sinkShared = {
8598
9340
  exporter: policy,
8599
9341
  ...shared,
9342
+ endpointHealth,
8600
9343
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
8601
9344
  ...label === void 0 ? {} : { destination: label }
8602
9345
  };
@@ -8614,6 +9357,7 @@ var createExportDestinationSinks = (options) => {
8614
9357
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
8615
9358
  exporter: policy,
8616
9359
  ...shared,
9360
+ endpointHealth,
8617
9361
  ...label === void 0 ? {} : { destination: label },
8618
9362
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
8619
9363
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -8783,7 +9527,14 @@ var createHookRuntime = (options) => {
8783
9527
  privacy,
8784
9528
  logger,
8785
9529
  installationId: options.installationId,
8786
- payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
9530
+ payloadEnrichers: options.payloadEnrichers ?? [
9531
+ ...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
9532
+ ...readsCodexRolloutUsage(options.config) ? [
9533
+ createCodexRolloutUsageEnricher(
9534
+ options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
9535
+ )
9536
+ ] : []
9537
+ ],
8787
9538
  ...(() => {
8788
9539
  if (options.sessionContextReader === null) {
8789
9540
  return {};