@osfactory/otel-hook 0.13.1 → 0.14.0

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 (41) hide show
  1. package/README.md +94 -3
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +1240 -200
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +32 -4
  6. package/dist/config.js +200 -14
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DvqsPulb.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-DUeQKr_C.d.ts → export-destinations-DvoH4QOe.d.ts} +135 -11
  10. package/dist/{hook-D5imE0Qc.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +11 -11
  12. package/dist/index.js +1262 -228
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/install.js +1 -0
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +16 -9
  18. package/dist/integration.js +1298 -205
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.js +1 -1
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{payload-CdDKeRpH.d.ts → payload-D4r71EL-.d.ts} +18 -2
  23. package/dist/privacy.d.ts +2 -2
  24. package/dist/privacy.js +42 -1
  25. package/dist/privacy.js.map +1 -1
  26. package/dist/providers.d.ts +94 -9
  27. package/dist/providers.js +300 -2
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-BKQhhIO3.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  30. package/dist/runtime.d.ts +5 -5
  31. package/dist/runtime.js +151 -5
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-SpFM6YQY.d.ts → schema-oRsbo7WO.d.ts} +77 -3
  34. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  35. package/dist/telemetry.d.ts +5 -4
  36. package/dist/telemetry.js +1076 -476
  37. package/dist/telemetry.js.map +1 -1
  38. package/dist/testing.d.ts +5 -5
  39. package/dist/testing.js +178 -21
  40. package/dist/testing.js.map +1 -1
  41. package/package.json +1 -1
@@ -153,6 +153,60 @@ var OTLP_HEADER_VARIABLES = Object.freeze({
153
153
  logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
154
154
  });
155
155
 
156
+ // src/config/repository-key.ts
157
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
158
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
159
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
160
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
161
+ var trimTrailingSlashes = (value) => {
162
+ let end = value.length;
163
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
164
+ return value.slice(0, end);
165
+ };
166
+ var keyOf = (host, pathname) => {
167
+ const withoutSlashes = trimTrailingSlashes(pathname);
168
+ const cleanedPath = trimTrailingSlashes(
169
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
170
+ );
171
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
172
+ return void 0;
173
+ }
174
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
175
+ return `${host}${withSlash}`.toLowerCase();
176
+ };
177
+ var normalizeRepositoryKey = (reference) => {
178
+ const trimmed = reference.trim();
179
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
180
+ return void 0;
181
+ }
182
+ if (SCHEME_PATTERN.test(trimmed)) {
183
+ let url;
184
+ try {
185
+ url = new URL(trimmed);
186
+ } catch {
187
+ return void 0;
188
+ }
189
+ if (url.protocol === "file:") {
190
+ return void 0;
191
+ }
192
+ return keyOf(url.hostname, url.pathname);
193
+ }
194
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
195
+ return void 0;
196
+ }
197
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
198
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
199
+ const [, host, pathPart] = scp;
200
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
201
+ }
202
+ try {
203
+ const url = new URL(`https://${trimmed}`);
204
+ return keyOf(url.hostname, url.pathname);
205
+ } catch {
206
+ return void 0;
207
+ }
208
+ };
209
+
156
210
  // src/config/destinations.ts
157
211
  var DEFAULT_DESTINATION_NAME = "default";
158
212
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
@@ -171,6 +225,30 @@ var headerValueSchema = z3.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
171
225
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
172
226
  );
173
227
  var endpointSchema = z3.string().url().max(2048);
228
+ var MAX_DESTINATION_SCOPES = 64;
229
+ var MAX_SCOPE_REPOSITORIES = 256;
230
+ var ALL_REPOSITORIES = "*";
231
+ var repositoryReferenceSchema = z3.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
232
+ (value) => normalizeRepositoryKey(value) !== void 0,
233
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
234
+ );
235
+ var destinationScopeSchema = z3.strictObject({
236
+ /**
237
+ * Repository URLs (any spelling of the remote; compared by host and path,
238
+ * case-insensitively, without `.git`), or `"*"` for every record that names
239
+ * a repository. A record that names none never matches a scope.
240
+ */
241
+ repositories: z3.union([
242
+ z3.literal(ALL_REPOSITORIES),
243
+ z3.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
244
+ ]),
245
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
246
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional(),
247
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
248
+ contentMode: contentModeSchema.optional(),
249
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
250
+ includeSessionId: z3.boolean().optional()
251
+ });
174
252
  var exportDestinationSchema = z3.strictObject({
175
253
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
176
254
  name: z3.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -204,7 +282,15 @@ var exportDestinationSchema = z3.strictObject({
204
282
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
205
283
  * default: a destination receives hook-derived metrics only when it lists them.
206
284
  */
207
- signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional()
285
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional(),
286
+ /**
287
+ * Per-repository filter. Absent: every record goes to this destination, as
288
+ * before scopes existed. Present: a record goes only when its repository
289
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
290
+ * decides its signals, content mode, and session id — and a record that
291
+ * names no repository is not sent here at all.
292
+ */
293
+ scopes: z3.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
208
294
  }).refine(
209
295
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
210
296
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -248,6 +334,32 @@ var effectiveSpoolPolicy = (exporter) => ({
248
334
  maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
249
335
  maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
250
336
  });
337
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
338
+ const listed = scope.signals ?? exportSignalSchema.options;
339
+ return {
340
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
341
+ scope.repositories.flatMap((reference) => {
342
+ const key = normalizeRepositoryKey(reference);
343
+ return key === void 0 ? [] : [key];
344
+ })
345
+ ),
346
+ signals: {
347
+ traces: destinationSignals.traces && listed.includes("traces"),
348
+ logs: destinationSignals.logs && listed.includes("logs"),
349
+ metrics: destinationSignals.metrics && listed.includes("metrics")
350
+ },
351
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
352
+ includeSessionId: scope.includeSessionId ?? true
353
+ };
354
+ });
355
+ var matchDestinationScope = (scopes, repositoryKey) => {
356
+ if (repositoryKey === void 0) {
357
+ return void 0;
358
+ }
359
+ return scopes.find(
360
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
361
+ );
362
+ };
251
363
  var legacyDestination = (exporter) => ({
252
364
  name: DEFAULT_DESTINATION_NAME,
253
365
  source: "exporter",
@@ -272,6 +384,11 @@ var resolveExportDestinations = (exporter) => {
272
384
  continue;
273
385
  }
274
386
  const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
387
+ const flags = {
388
+ traces: signals.includes("traces"),
389
+ logs: exporter.logs.enabled && signals.includes("logs"),
390
+ metrics: signals.includes("metrics")
391
+ };
275
392
  resolved.push({
276
393
  name: destination.name,
277
394
  source: "destinations",
@@ -280,12 +397,9 @@ var resolveExportDestinations = (exporter) => {
280
397
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
281
398
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
282
399
  ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
283
- signals: {
284
- traces: signals.includes("traces"),
285
- logs: exporter.logs.enabled && signals.includes("logs"),
286
- metrics: signals.includes("metrics")
287
- },
288
- headers: { ...destination.headers ?? {} }
400
+ signals: flags,
401
+ headers: { ...destination.headers ?? {} },
402
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
289
403
  });
290
404
  }
291
405
  return resolved;
@@ -476,8 +590,26 @@ var exporterPolicySchema = z5.strictObject({
476
590
  * Per-destination retry spool bounds, each optional and merged per leaf; any
477
591
  * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
478
592
  */
479
- spool: spoolPolicySchema.partial().optional()
593
+ spool: spoolPolicySchema.partial().optional(),
594
+ /**
595
+ * The most time one hook invocation spends trying to reach one endpoint, in
596
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
597
+ * included) and the exporter's own retries inside it. A batch that does not
598
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
599
+ * the host agent waits for its hooks, so a down collector must not stall it.
600
+ */
601
+ exportBudgetMillis: z5.number().int().min(50).max(6e5).optional(),
602
+ /**
603
+ * After an endpoint was unreachable (refused, timed out, or answered a
604
+ * retryable status), every hook spools for it without trying for this long,
605
+ * in milliseconds; then one hook probes it again. 0 disables the window.
606
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
607
+ */
608
+ endpointDownMillis: z5.number().int().min(0).max(36e5).optional()
480
609
  });
610
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
611
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
612
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
481
613
  var detectionPolicySchema = z5.strictObject({
482
614
  /** Detections below this confidence resolve to the unknown provider. */
483
615
  minimumConfidence: detectionConfidenceSchema,
@@ -494,6 +626,9 @@ var diagnosticsPolicySchema = z5.strictObject({
494
626
  var providersPolicySchema = z5.strictObject({
495
627
  claudeCode: z5.strictObject({
496
628
  readTranscriptUsage: z5.boolean()
629
+ }).optional(),
630
+ codex: z5.strictObject({
631
+ readRolloutUsage: z5.boolean()
497
632
  }).optional()
498
633
  });
499
634
  var sessionContextPolicySchema = z5.strictObject({
@@ -523,7 +658,8 @@ var otelHookConfigPatchSchema = z5.strictObject({
523
658
  detection: detectionPolicySchema.partial().optional(),
524
659
  diagnostics: diagnosticsPolicySchema.partial().optional(),
525
660
  providers: z5.strictObject({
526
- claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
661
+ claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional(),
662
+ codex: z5.strictObject({ readRolloutUsage: z5.boolean() }).partial().optional()
527
663
  }).partial().optional(),
528
664
  sessionContext: sessionContextPolicySchema.partial().optional()
529
665
  });
@@ -550,7 +686,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
550
686
  emitErrorEvents: true
551
687
  });
552
688
  var DEFAULT_PROVIDERS_POLICY = Object.freeze({
553
- claudeCode: Object.freeze({ readTranscriptUsage: false })
689
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
690
+ codex: Object.freeze({ readRolloutUsage: false })
554
691
  });
555
692
  var DEFAULT_CONFIG = Object.freeze({
556
693
  exporter: DEFAULT_EXPORTER_POLICY,
@@ -560,6 +697,7 @@ var DEFAULT_CONFIG = Object.freeze({
560
697
  providers: DEFAULT_PROVIDERS_POLICY
561
698
  });
562
699
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
700
+ var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
563
701
  var sessionContextDir = (config) => config.sessionContext?.dir;
564
702
  var effectiveMetricsPolicy = (exporter) => ({
565
703
  ...DEFAULT_METRICS_POLICY,
@@ -2419,7 +2557,7 @@ import {
2419
2557
  } from "@opentelemetry/semantic-conventions/incubating";
2420
2558
 
2421
2559
  // src/version.ts
2422
- var VERSION = "0.13.1";
2560
+ var VERSION = "0.14.0";
2423
2561
 
2424
2562
  // src/telemetry/semconv.ts
2425
2563
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -2902,6 +3040,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
2902
3040
  };
2903
3041
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
2904
3042
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
3043
+ var spanEndEdgesOf = (events) => {
3044
+ const layout = layoutBatch(events);
3045
+ const ends = /* @__PURE__ */ new Map();
3046
+ for (const [eventId, groupKey] of layout.groupOf) {
3047
+ const end = layout.groups.get(groupKey)?.end;
3048
+ if (end !== void 0) {
3049
+ ends.set(eventId, end);
3050
+ }
3051
+ }
3052
+ return ends;
3053
+ };
2905
3054
  var canonicalEventTraceIdentities = (events, options = {}) => {
2906
3055
  const layout = layoutBatch(events);
2907
3056
  const correlations = indexCorrelations(options.correlations);
@@ -3469,6 +3618,23 @@ var createUsageAccumulator = (deps) => {
3469
3618
 
3470
3619
  // src/privacy/service.ts
3471
3620
  import { createHash as createHash3 } from "crypto";
3621
+ var DISCLOSURE_RANK = Object.freeze({
3622
+ omitted: 0,
3623
+ masked: 1,
3624
+ redacted: 2,
3625
+ raw: 3
3626
+ });
3627
+ var WHITESPACE = /\s/u;
3628
+ var withoutTrailingToken = (text) => {
3629
+ let end = text.length;
3630
+ while (end > 0) {
3631
+ const low = text.charCodeAt(end - 1);
3632
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
3633
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
3634
+ end -= width;
3635
+ }
3636
+ return text.slice(0, end);
3637
+ };
3472
3638
  var compilePatterns = (sources, flags) => {
3473
3639
  const compiled = [];
3474
3640
  for (const source of sources) {
@@ -3686,11 +3852,11 @@ var createPrivacyService = (policyInput) => {
3686
3852
  };
3687
3853
  const flattenToAttributes = (value, prefix) => {
3688
3854
  const attributes = {};
3689
- const walk = (current, path7) => {
3855
+ const walk = (current, path9) => {
3690
3856
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3691
3857
  const primitive = toAttributePrimitive(current);
3692
3858
  if (primitive !== void 0) {
3693
- attributes[path7] = primitive;
3859
+ attributes[path9] = primitive;
3694
3860
  }
3695
3861
  return;
3696
3862
  }
@@ -3709,16 +3875,16 @@ var createPrivacyService = (policyInput) => {
3709
3875
  primitives.push(entryPrimitive);
3710
3876
  }
3711
3877
  if (uniform) {
3712
- attributes[path7] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3878
+ attributes[path9] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3713
3879
  return;
3714
3880
  }
3715
3881
  for (const [index, entry] of current.entries()) {
3716
- walk(entry, `${path7}.${index}`);
3882
+ walk(entry, `${path9}.${index}`);
3717
3883
  }
3718
3884
  return;
3719
3885
  }
3720
3886
  for (const [key, entry] of Object.entries(current)) {
3721
- walk(entry, path7 === "" ? key : `${path7}.${key}`);
3887
+ walk(entry, path9 === "" ? key : `${path9}.${key}`);
3722
3888
  }
3723
3889
  };
3724
3890
  walk(value, prefix);
@@ -3806,7 +3972,31 @@ var createPrivacyService = (policyInput) => {
3806
3972
  flattenToAttributes,
3807
3973
  sanitizeAttributes,
3808
3974
  sanitizeExtensions,
3809
- boundString
3975
+ boundString,
3976
+ restrictContent: (fact, mode) => {
3977
+ const target = CONTENT_MODE_DISCLOSURE[mode];
3978
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
3979
+ return fact;
3980
+ }
3981
+ const { text, ...rest } = fact;
3982
+ switch (target) {
3983
+ case "omitted":
3984
+ return { ...rest, disclosure: "omitted", truncated: false };
3985
+ case "masked":
3986
+ return { ...rest, disclosure: "masked", text: maskText(text) };
3987
+ case "redacted": {
3988
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
3989
+ return {
3990
+ ...rest,
3991
+ disclosure: "redacted",
3992
+ text: redacted.text,
3993
+ secretsRedacted: fact.secretsRedacted + redacted.count
3994
+ };
3995
+ }
3996
+ case "raw":
3997
+ return fact;
3998
+ }
3999
+ }
3810
4000
  };
3811
4001
  };
3812
4002
 
@@ -4616,6 +4806,419 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4616
4806
  });
4617
4807
  };
4618
4808
 
4809
+ // src/providers/codex/rollout-usage.ts
4810
+ import { createHash as createHash5 } from "crypto";
4811
+ import { open as open2, readdir, stat as stat2 } from "fs/promises";
4812
+ import path2 from "path";
4813
+
4814
+ // src/providers/codex/version.ts
4815
+ var CODEX_PROVIDER_ID = providerIdSchema.parse("codex");
4816
+
4817
+ // src/providers/codex/payload.ts
4818
+ import { z as z17 } from "zod";
4819
+ var permissionModeSchema = z17.enum([
4820
+ "default",
4821
+ "acceptEdits",
4822
+ "plan",
4823
+ "dontAsk",
4824
+ "bypassPermissions"
4825
+ ]);
4826
+ var codexUsageSchema = z17.object({
4827
+ input_tokens: z17.number().int().min(0).optional(),
4828
+ cached_input_tokens: z17.number().int().min(0).optional(),
4829
+ cache_write_input_tokens: z17.number().int().min(0).optional(),
4830
+ output_tokens: z17.number().int().min(0).optional(),
4831
+ reasoning_output_tokens: z17.number().int().min(0).optional(),
4832
+ total_tokens: z17.number().int().min(0).optional()
4833
+ });
4834
+ var baseFields = {
4835
+ session_id: z17.string().min(1).max(256),
4836
+ cwd: z17.string().min(1).max(4096).optional(),
4837
+ model: z17.string().min(1).max(256).optional(),
4838
+ permission_mode: permissionModeSchema.optional(),
4839
+ transcript_path: z17.string().min(1).max(4096).optional(),
4840
+ codex_version: z17.string().min(1).max(64).optional(),
4841
+ /** Not part of the documented protocol; lets tests and replay stay deterministic. */
4842
+ occurred_at: z17.number().int().min(0).optional()
4843
+ };
4844
+ var codexSessionStartPayloadSchema = z17.object({
4845
+ ...baseFields,
4846
+ hook_event_name: z17.literal("SessionStart"),
4847
+ source: z17.enum(["startup", "resume", "clear", "compact"]).optional()
4848
+ });
4849
+ var codexUserPromptSubmitPayloadSchema = z17.object({
4850
+ ...baseFields,
4851
+ hook_event_name: z17.literal("UserPromptSubmit"),
4852
+ turn_id: z17.string().min(1).max(256).optional(),
4853
+ prompt: z17.string().max(1e6).optional()
4854
+ });
4855
+ var codexPreToolUsePayloadSchema = z17.object({
4856
+ ...baseFields,
4857
+ hook_event_name: z17.literal("PreToolUse"),
4858
+ turn_id: z17.string().min(1).max(256).optional(),
4859
+ tool_name: z17.string().min(1).max(256),
4860
+ tool_call_id: z17.string().min(1).max(256).optional(),
4861
+ tool_input: z17.unknown().optional()
4862
+ });
4863
+ var codexPermissionRequestPayloadSchema = z17.object({
4864
+ ...baseFields,
4865
+ hook_event_name: z17.literal("PermissionRequest"),
4866
+ turn_id: z17.string().min(1).max(256).optional(),
4867
+ tool_name: z17.string().min(1).max(256).optional(),
4868
+ tool_call_id: z17.string().min(1).max(256).optional(),
4869
+ tool_input: z17.unknown().optional()
4870
+ });
4871
+ var codexPostToolUsePayloadSchema = z17.object({
4872
+ ...baseFields,
4873
+ hook_event_name: z17.literal("PostToolUse"),
4874
+ turn_id: z17.string().min(1).max(256).optional(),
4875
+ tool_name: z17.string().min(1).max(256),
4876
+ tool_call_id: z17.string().min(1).max(256).optional(),
4877
+ tool_input: z17.unknown().optional(),
4878
+ tool_response: z17.unknown().optional(),
4879
+ permission_decision: z17.enum(["allowed", "denied", "deferred"]).optional(),
4880
+ duration_ms: z17.number().min(0).optional()
4881
+ });
4882
+ var codexPreCompactPayloadSchema = z17.object({
4883
+ ...baseFields,
4884
+ hook_event_name: z17.literal("PreCompact"),
4885
+ trigger: z17.enum(["auto", "manual"]).optional(),
4886
+ context_tokens_before: z17.number().int().min(0).optional()
4887
+ });
4888
+ var codexPostCompactPayloadSchema = z17.object({
4889
+ ...baseFields,
4890
+ hook_event_name: z17.literal("PostCompact"),
4891
+ trigger: z17.enum(["auto", "manual"]).optional(),
4892
+ context_tokens_after: z17.number().int().min(0).optional(),
4893
+ dropped_message_count: z17.number().int().min(0).optional(),
4894
+ usage: codexUsageSchema.optional()
4895
+ });
4896
+ var codexSubagentStartPayloadSchema = z17.object({
4897
+ ...baseFields,
4898
+ hook_event_name: z17.literal("SubagentStart"),
4899
+ turn_id: z17.string().min(1).max(256).optional(),
4900
+ subagent_id: z17.string().min(1).max(256),
4901
+ subagent_type: z17.string().min(1).max(256).optional()
4902
+ });
4903
+ var codexSubagentStopPayloadSchema = z17.object({
4904
+ ...baseFields,
4905
+ hook_event_name: z17.literal("SubagentStop"),
4906
+ turn_id: z17.string().min(1).max(256).optional(),
4907
+ subagent_id: z17.string().min(1).max(256),
4908
+ status: z17.enum(["completed", "failed", "cancelled"]).optional(),
4909
+ usage: codexUsageSchema.optional()
4910
+ });
4911
+ var codexStopPayloadSchema = z17.object({
4912
+ ...baseFields,
4913
+ hook_event_name: z17.literal("Stop"),
4914
+ turn_id: z17.string().min(1).max(256).optional(),
4915
+ stop_reason: z17.string().min(1).max(256).optional(),
4916
+ usage: codexUsageSchema.optional(),
4917
+ duration_ms: z17.number().min(0).optional()
4918
+ });
4919
+ var CODEX_HOOK_EVENT_NAMES = [
4920
+ "SessionStart",
4921
+ "UserPromptSubmit",
4922
+ "PreToolUse",
4923
+ "PermissionRequest",
4924
+ "PostToolUse",
4925
+ "PreCompact",
4926
+ "PostCompact",
4927
+ "SubagentStart",
4928
+ "SubagentStop",
4929
+ "Stop"
4930
+ ];
4931
+ var codexHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
4932
+ codexSessionStartPayloadSchema,
4933
+ codexUserPromptSubmitPayloadSchema,
4934
+ codexPreToolUsePayloadSchema,
4935
+ codexPermissionRequestPayloadSchema,
4936
+ codexPostToolUsePayloadSchema,
4937
+ codexPreCompactPayloadSchema,
4938
+ codexPostCompactPayloadSchema,
4939
+ codexSubagentStartPayloadSchema,
4940
+ codexSubagentStopPayloadSchema,
4941
+ codexStopPayloadSchema
4942
+ ]);
4943
+ var codexHookEnvelopeSchema = z17.object({
4944
+ session_id: z17.string().min(1),
4945
+ hook_event_name: z17.enum(CODEX_HOOK_EVENT_NAMES)
4946
+ });
4947
+
4948
+ // src/providers/codex/rollout-usage.ts
4949
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
4950
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
4951
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
4952
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
4953
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
4954
+ var ROLLOUT_LOOKUP_DAYS = 7;
4955
+ var MIN_BYTES = 65536;
4956
+ var MAX_RANGE_BYTES2 = 67108864;
4957
+ var MAX_TAIL_BYTES2 = 16777216;
4958
+ var MIN_TIMEOUT_MILLIS2 = 10;
4959
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
4960
+ var MAX_SETTLE_MILLIS = 1e3;
4961
+ var MAX_MODEL_ID_LENGTH2 = 256;
4962
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
4963
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
4964
+ var clamp2 = (value, fallback, min, max) => {
4965
+ if (value === void 0 || !Number.isFinite(value)) {
4966
+ return fallback;
4967
+ }
4968
+ return Math.min(max, Math.max(min, Math.floor(value)));
4969
+ };
4970
+ var asRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4971
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path2.isAbsolute(value) && path2.extname(value) === ".jsonl";
4972
+ var sourceDigest2 = (rolloutPath) => createHash5("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
4973
+ var parseUsage = (value) => {
4974
+ const parsed = codexUsageSchema.safeParse(value);
4975
+ if (!parsed.success) {
4976
+ return void 0;
4977
+ }
4978
+ const usage = parsed.data;
4979
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
4980
+ };
4981
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
4982
+ var factsOf2 = (line) => {
4983
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
4984
+ const contextLine = line.includes('"turn_context"');
4985
+ if (!usageLine && !contextLine) {
4986
+ return void 0;
4987
+ }
4988
+ let parsed;
4989
+ try {
4990
+ parsed = JSON.parse(line);
4991
+ } catch {
4992
+ return void 0;
4993
+ }
4994
+ const record = asRecord3(parsed);
4995
+ const payload = asRecord3(record?.payload);
4996
+ if (record === void 0 || payload === void 0) {
4997
+ return void 0;
4998
+ }
4999
+ if (record.type === "turn_context") {
5000
+ const model = modelOf(payload.model);
5001
+ return model === void 0 ? void 0 : { model };
5002
+ }
5003
+ if (record.type === "event_msg" && payload.type === "token_count") {
5004
+ const info = asRecord3(payload.info) ?? payload;
5005
+ const usage = parseUsage(info.total_token_usage);
5006
+ return usage === void 0 ? void 0 : { usage };
5007
+ }
5008
+ if (record.type === "token_usage_record") {
5009
+ const usage = parseUsage(payload.thread_token_usage);
5010
+ return usage === void 0 ? void 0 : { usage };
5011
+ }
5012
+ return void 0;
5013
+ };
5014
+ var lastSnapshotIn = (lines) => {
5015
+ let usage;
5016
+ let model;
5017
+ for (const line of lines) {
5018
+ const facts = factsOf2(line.trim());
5019
+ if (facts === void 0) {
5020
+ continue;
5021
+ }
5022
+ if (facts.model !== void 0) {
5023
+ model = facts.model;
5024
+ }
5025
+ if (facts.usage !== void 0) {
5026
+ usage = facts.usage;
5027
+ }
5028
+ }
5029
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
5030
+ };
5031
+ var readBytes2 = async (handle, start, length) => {
5032
+ const buffer = Buffer.alloc(length);
5033
+ let filled = 0;
5034
+ while (filled < length) {
5035
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
5036
+ if (bytesRead === 0) {
5037
+ break;
5038
+ }
5039
+ filled += bytesRead;
5040
+ }
5041
+ return buffer.subarray(0, filled);
5042
+ };
5043
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
5044
+ let handle;
5045
+ try {
5046
+ const info = await stat2(rolloutPath);
5047
+ if (!info.isFile()) {
5048
+ return { status: "unavailable", reason: "not-a-file" };
5049
+ }
5050
+ handle = await open2(rolloutPath, "r");
5051
+ } catch {
5052
+ return { status: "unavailable", reason: "unreadable" };
5053
+ }
5054
+ try {
5055
+ const { size } = await handle.stat();
5056
+ let start;
5057
+ if (fromOffset === void 0) {
5058
+ start = Math.max(0, size - tailBytes);
5059
+ } else if (size < fromOffset) {
5060
+ return { status: "unavailable", reason: "truncated" };
5061
+ } else if (size - fromOffset > maxRangeBytes) {
5062
+ return { status: "unavailable", reason: "over-cap" };
5063
+ } else {
5064
+ start = fromOffset;
5065
+ }
5066
+ const bytes = await readBytes2(handle, start, size - start);
5067
+ const lastNewline = bytes.lastIndexOf(10);
5068
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
5069
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
5070
+ if (fromOffset === void 0 && start > 0) {
5071
+ lines.shift();
5072
+ }
5073
+ const snapshot = lastSnapshotIn(lines);
5074
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
5075
+ } catch {
5076
+ return { status: "unavailable", reason: "unreadable" };
5077
+ } finally {
5078
+ await handle.close().catch(() => void 0);
5079
+ }
5080
+ };
5081
+ var pad = (value) => String(value).padStart(2, "0");
5082
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
5083
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path2.isAbsolute(sessionsRoot)) {
5084
+ return void 0;
5085
+ }
5086
+ const suffix = `-${sessionId}.jsonl`;
5087
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
5088
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
5089
+ const dir = path2.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
5090
+ let names;
5091
+ try {
5092
+ names = await readdir(dir);
5093
+ } catch {
5094
+ continue;
5095
+ }
5096
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
5097
+ continue;
5098
+ }
5099
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
5100
+ if (match !== void 0) {
5101
+ return path2.join(dir, match);
5102
+ }
5103
+ }
5104
+ return void 0;
5105
+ };
5106
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
5107
+ var withTimeout2 = async (work, timeoutMillis) => {
5108
+ let timer;
5109
+ const timeout = new Promise((resolve3) => {
5110
+ timer = setTimeout(() => {
5111
+ resolve3(TIMED_OUT2);
5112
+ }, timeoutMillis);
5113
+ timer.unref();
5114
+ });
5115
+ try {
5116
+ return await Promise.race([work, timeout]);
5117
+ } finally {
5118
+ clearTimeout(timer);
5119
+ }
5120
+ };
5121
+ var sleep = (millis) => new Promise((resolve3) => {
5122
+ setTimeout(resolve3, millis).unref();
5123
+ });
5124
+ var hasUsage2 = (record) => record.usage !== void 0;
5125
+ var createCodexRolloutUsageEnricher = (options = {}) => {
5126
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
5127
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
5128
+ const timeoutMillis = clamp2(
5129
+ options.timeoutMillis,
5130
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
5131
+ MIN_TIMEOUT_MILLIS2,
5132
+ MAX_TIMEOUT_MILLIS2
5133
+ );
5134
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
5135
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
5136
+ const fileSize = async (rolloutPath) => {
5137
+ try {
5138
+ const info = await stat2(rolloutPath);
5139
+ return info.isFile() ? info.size : void 0;
5140
+ } catch (thrown) {
5141
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
5142
+ }
5143
+ };
5144
+ const resolveRollout = async (record) => {
5145
+ const named = record.transcript_path;
5146
+ if (named !== void 0 && named !== null) {
5147
+ return isRolloutPath(named) ? named : void 0;
5148
+ }
5149
+ const sessionId = record.session_id;
5150
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
5151
+ return void 0;
5152
+ }
5153
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
5154
+ };
5155
+ const enrichWithin = async (input) => {
5156
+ const unchanged = { payload: input.payload };
5157
+ const record = asRecord3(input.payload);
5158
+ const eventName = record?.hook_event_name;
5159
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
5160
+ return unchanged;
5161
+ }
5162
+ const rolloutPath = await resolveRollout(record);
5163
+ if (rolloutPath === void 0) {
5164
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
5165
+ }
5166
+ const source = sourceDigest2(rolloutPath);
5167
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
5168
+ if (eventName === "SessionStart") {
5169
+ if (cursor !== void 0) {
5170
+ return unchanged;
5171
+ }
5172
+ const size = await fileSize(rolloutPath);
5173
+ if (size === void 0) {
5174
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
5175
+ }
5176
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
5177
+ }
5178
+ if (hasUsage2(record)) {
5179
+ const size = await fileSize(rolloutPath);
5180
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
5181
+ }
5182
+ const attach = (snapshot) => ({
5183
+ ...record,
5184
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
5185
+ usage: snapshot.usage
5186
+ });
5187
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
5188
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
5189
+ await sleep(settleMillis);
5190
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
5191
+ }
5192
+ if (read.status === "unavailable") {
5193
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
5194
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
5195
+ }
5196
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
5197
+ if (read.status === "unavailable") {
5198
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
5199
+ }
5200
+ }
5201
+ const next = { source, offset: read.endOffset };
5202
+ if (read.snapshot === void 0) {
5203
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
5204
+ }
5205
+ return {
5206
+ payload: attach(read.snapshot),
5207
+ cursor: next,
5208
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
5209
+ };
5210
+ };
5211
+ const enrich = async (input) => {
5212
+ try {
5213
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
5214
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
5215
+ } catch {
5216
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
5217
+ }
5218
+ };
5219
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
5220
+ };
5221
+
4619
5222
  // src/runtime/clock.ts
4620
5223
  var createSystemClock = () => ({
4621
5224
  now: () => epochMillisSchema.parse(Date.now()),
@@ -4623,7 +5226,7 @@ var createSystemClock = () => ({
4623
5226
  });
4624
5227
 
4625
5228
  // src/runtime/hook.ts
4626
- import { z as z19 } from "zod";
5229
+ import { z as z20 } from "zod";
4627
5230
 
4628
5231
  // src/providers/registry.ts
4629
5232
  var createProviderRegistry = (adapters) => {
@@ -4778,9 +5381,9 @@ var resolveDeliveryIdentity = (input) => {
4778
5381
  };
4779
5382
 
4780
5383
  // src/runtime/ids.ts
4781
- import { createHash as createHash5, randomUUID } from "crypto";
5384
+ import { createHash as createHash6, randomUUID } from "crypto";
4782
5385
  var digest2 = (namespace, parts) => {
4783
- const hash = createHash5("sha256");
5386
+ const hash = createHash6("sha256");
4784
5387
  hash.update(namespace);
4785
5388
  for (const part of parts) {
4786
5389
  hash.update("\0");
@@ -4819,15 +5422,15 @@ var createDeterministicIdGenerator = (options = {}) => {
4819
5422
  };
4820
5423
 
4821
5424
  // 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}$/),
5425
+ import { z as z18 } from "zod";
5426
+ var appliedDeliverySchema = z18.strictObject({
5427
+ callbackId: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
4825
5428
  /** How many of that delivery's observations are folded in, counted from one. */
4826
- applications: z17.number().int().min(1).max(4096)
5429
+ applications: z18.number().int().min(1).max(4096)
4827
5430
  });
4828
- var stateValueSchema = z17.discriminatedUnion("kind", [
4829
- z17.strictObject({
4830
- kind: z17.literal("usage-cumulative"),
5431
+ var stateValueSchema = z18.discriminatedUnion("kind", [
5432
+ z18.strictObject({
5433
+ kind: z18.literal("usage-cumulative"),
4831
5434
  usage: canonicalUsageSchema,
4832
5435
  /**
4833
5436
  * Optional: absent on every record written before this field existed, which
@@ -4836,12 +5439,12 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4836
5439
  */
4837
5440
  appliedDelivery: appliedDeliverySchema.optional()
4838
5441
  }),
4839
- z17.strictObject({
4840
- kind: z17.literal("sequence"),
5442
+ z18.strictObject({
5443
+ kind: z18.literal("sequence"),
4841
5444
  next: sequenceNumberSchema
4842
5445
  }),
4843
- z17.strictObject({
4844
- kind: z17.literal("attributes"),
5446
+ z18.strictObject({
5447
+ kind: z18.literal("attributes"),
4845
5448
  attributes: attributesSchema
4846
5449
  }),
4847
5450
  /**
@@ -4850,8 +5453,8 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4850
5453
  * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
4851
5454
  * bounded canonical shape, never a payload fragment.
4852
5455
  */
4853
- z17.strictObject({
4854
- kind: z17.literal("session-model"),
5456
+ z18.strictObject({
5457
+ kind: z18.literal("session-model"),
4855
5458
  model: modelDescriptorSchema
4856
5459
  }),
4857
5460
  /**
@@ -4865,36 +5468,36 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4865
5468
  * a series digest only; the series' attributes are re-supplied by the caller
4866
5469
  * and never read back from disk.
4867
5470
  */
4868
- z17.strictObject({
4869
- kind: z17.literal("metric-series"),
5471
+ z18.strictObject({
5472
+ kind: z18.literal("metric-series"),
4870
5473
  /** Start of the cumulative interval. */
4871
5474
  startTimeMillis: epochMillisSchema,
4872
5475
  /** Counters: the running total. */
4873
- value: z17.number().finite().min(0).optional(),
5476
+ value: z18.number().finite().min(0).optional(),
4874
5477
  /** 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)
5478
+ histogram: z18.strictObject({
5479
+ count: z18.number().int().min(0),
5480
+ sum: z18.number().finite().min(0),
5481
+ min: z18.number().finite(),
5482
+ max: z18.number().finite(),
5483
+ bucketCounts: z18.array(z18.number().int().min(0)).max(64)
4881
5484
  }).optional(),
4882
5485
  /** 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()
5486
+ appliedDelivery: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
4884
5487
  }),
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)
5488
+ z18.strictObject({
5489
+ kind: z18.literal("read-cursor"),
5490
+ source: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
5491
+ offset: z18.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
4889
5492
  })
4890
5493
  ]);
4891
- var stateRecordSchema = z17.strictObject({
5494
+ var stateRecordSchema = z18.strictObject({
4892
5495
  /** Incremented on each write; lets callers detect lost updates. */
4893
- revision: z17.number().int().min(0),
5496
+ revision: z18.number().int().min(0),
4894
5497
  updatedAt: epochMillisSchema,
4895
5498
  value: stateValueSchema
4896
5499
  });
4897
- var logLevelSchema = z17.enum(["silent", "error", "warn", "info", "debug"]);
5500
+ var logLevelSchema = z18.enum(["silent", "error", "warn", "info", "debug"]);
4898
5501
  var LOG_LEVEL_RANK = Object.freeze({
4899
5502
  silent: 0,
4900
5503
  error: 1,
@@ -4912,7 +5515,7 @@ var createNullLogger = () => ({
4912
5515
  });
4913
5516
 
4914
5517
  // src/runtime/target-resolution.ts
4915
- import * as path2 from "path";
5518
+ import * as path3 from "path";
4916
5519
 
4917
5520
  // src/privacy/workspace.ts
4918
5521
  var canonicalizeGitRemote = (remoteUrl) => {
@@ -4964,13 +5567,13 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
4964
5567
  // src/runtime/target-resolution.ts
4965
5568
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
4966
5569
  var absolutePathsOf = (hint) => {
4967
- const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
5570
+ const base = hint.baseDirectory !== void 0 && path3.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
4968
5571
  const resolved = [];
4969
5572
  for (const candidate of hint.paths) {
4970
- if (path2.isAbsolute(candidate)) {
4971
- resolved.push(path2.resolve(candidate));
5573
+ if (path3.isAbsolute(candidate)) {
5574
+ resolved.push(path3.resolve(candidate));
4972
5575
  } else if (base !== void 0) {
4973
- resolved.push(path2.resolve(base, candidate));
5576
+ resolved.push(path3.resolve(base, candidate));
4974
5577
  } else {
4975
5578
  return void 0;
4976
5579
  }
@@ -5049,9 +5652,9 @@ var resolveEventTargets = async (input) => {
5049
5652
  };
5050
5653
 
5051
5654
  // 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";
5655
+ import { open as open3 } from "fs/promises";
5656
+ import * as path4 from "path";
5657
+ import { z as z19 } from "zod";
5055
5658
  var SESSION_CONTEXT_FILE_VERSION = 1;
5056
5659
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
5057
5660
  var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
@@ -5068,10 +5671,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
5068
5671
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
5069
5672
  var sessionContextFilePath = (dir, providerId, sessionId) => {
5070
5673
  const tool = sessionContextAgentTool(providerId);
5071
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
5674
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path4.isAbsolute(dir)) {
5072
5675
  return void 0;
5073
5676
  }
5074
- return path3.join(dir, tool, `${sessionId}.json`);
5677
+ return path4.join(dir, tool, `${sessionId}.json`);
5075
5678
  };
5076
5679
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
5077
5680
  "session.id",
@@ -5110,25 +5713,25 @@ var sanitizeSessionContextAttributes = (attributes) => {
5110
5713
  return kept;
5111
5714
  };
5112
5715
  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) => {
5716
+ var isoInstantSchema = z19.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
5114
5717
  const millis = Date.parse(value);
5115
5718
  if (!Number.isFinite(millis)) {
5116
5719
  ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
5117
- return z18.NEVER;
5720
+ return z19.NEVER;
5118
5721
  }
5119
5722
  return millis;
5120
5723
  });
5121
- var segmentSchema = z18.object({
5724
+ var segmentSchema = z19.object({
5122
5725
  from: isoInstantSchema,
5123
5726
  to: isoInstantSchema.nullable(),
5124
- reason: z18.string().max(256).optional(),
5125
- attributes: z18.record(z18.string(), z18.unknown())
5727
+ reason: z19.string().max(256).optional(),
5728
+ attributes: z19.record(z19.string(), z19.unknown())
5126
5729
  });
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)
5730
+ var sessionContextFileSchema = z19.object({
5731
+ version: z19.literal(SESSION_CONTEXT_FILE_VERSION),
5732
+ agentTool: z19.string().max(64).optional(),
5733
+ sessionId: z19.string().max(256).optional(),
5734
+ segments: z19.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
5132
5735
  });
5133
5736
  var parseSessionContextFile = (value, expected) => {
5134
5737
  const parsed = sessionContextFileSchema.safeParse(value);
@@ -5167,7 +5770,7 @@ var stampSessionContext = (events, segments) => events.map((event2) => {
5167
5770
  var readBounded = async (file, maxBytes) => {
5168
5771
  let handle;
5169
5772
  try {
5170
- handle = await open2(file, "r");
5773
+ handle = await open3(file, "r");
5171
5774
  } catch {
5172
5775
  return void 0;
5173
5776
  }
@@ -5241,7 +5844,7 @@ var createDirectorySessionContextReader = (options) => {
5241
5844
  };
5242
5845
 
5243
5846
  // src/runtime/hook.ts
5244
- var usageScopeSchema = z19.enum(["session", "generation", "subagent"]);
5847
+ var usageScopeSchema = z20.enum(["session", "generation", "subagent"]);
5245
5848
  var classifyDurability = (input) => {
5246
5849
  if (!input.attempted) {
5247
5850
  return "nothing-to-deliver";
@@ -6120,8 +6723,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
6120
6723
  };
6121
6724
 
6122
6725
  // src/runtime/git-worktree.ts
6123
- import { lstat, open as open3, stat as stat2 } from "fs/promises";
6124
- import * as path4 from "path";
6726
+ import { lstat, open as open4, stat as stat3 } from "fs/promises";
6727
+ import * as path5 from "path";
6125
6728
  var MAX_WORKTREE_WALK_DEPTH = 128;
6126
6729
  var MAX_GIT_FILE_BYTES = 4096;
6127
6730
  var MAX_CACHE_ENTRIES = 1024;
@@ -6132,7 +6735,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
6132
6735
  var readBounded2 = async (filePath) => {
6133
6736
  let handle;
6134
6737
  try {
6135
- handle = await open3(filePath, "r");
6738
+ handle = await open4(filePath, "r");
6136
6739
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
6137
6740
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
6138
6741
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -6153,7 +6756,7 @@ var parseHeadBranch = (head) => {
6153
6756
  return branch;
6154
6757
  };
6155
6758
  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);
6759
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path5.resolve(base, target);
6157
6760
  var parseGitDirFile = (content, worktreeRoot) => {
6158
6761
  const line = firstLine(content);
6159
6762
  return resolveGitPath(
@@ -6173,26 +6776,26 @@ var isMissing = async (filePath) => {
6173
6776
  };
6174
6777
  var isDirectory = async (directory) => {
6175
6778
  try {
6176
- return (await stat2(directory)).isDirectory();
6779
+ return (await stat3(directory)).isDirectory();
6177
6780
  } catch {
6178
6781
  return false;
6179
6782
  }
6180
6783
  };
6181
6784
  var repositoryOf = async (worktreeRoot, gitDir) => {
6182
- const commonDirFile = path4.join(gitDir, "commondir");
6785
+ const commonDirFile = path5.join(gitDir, "commondir");
6183
6786
  const content = await readBounded2(commonDirFile);
6184
6787
  if (content === void 0) {
6185
6788
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
6186
6789
  }
6187
6790
  const commonDir = parseCommonDirFile(content, gitDir);
6188
- const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
6791
+ const mainRoot = commonDir !== void 0 && path5.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path5.dirname(commonDir) : void 0;
6189
6792
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
6190
6793
  };
6191
6794
  var probeDirectory = async (directory) => {
6192
- const dotGit = path4.join(directory, ".git");
6795
+ const dotGit = path5.join(directory, ".git");
6193
6796
  let info;
6194
6797
  try {
6195
- info = await stat2(dotGit);
6798
+ info = await stat3(dotGit);
6196
6799
  } catch {
6197
6800
  return ABSENT;
6198
6801
  }
@@ -6206,7 +6809,7 @@ var probeDirectory = async (directory) => {
6206
6809
  if (gitDir === void 0) {
6207
6810
  return INVALID;
6208
6811
  }
6209
- const head = await readBounded2(path4.join(gitDir, "HEAD"));
6812
+ const head = await readBounded2(path5.join(gitDir, "HEAD"));
6210
6813
  if (head === void 0) {
6211
6814
  return INVALID;
6212
6815
  }
@@ -6236,10 +6839,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6236
6839
  };
6237
6840
  const locate = async (absolutePath) => {
6238
6841
  try {
6239
- if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6842
+ if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6240
6843
  return void 0;
6241
6844
  }
6242
- let directory = path4.resolve(absolutePath);
6845
+ let directory = path5.resolve(absolutePath);
6243
6846
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
6244
6847
  const probe = await cachedProbe(directory);
6245
6848
  if (probe.kind === "worktree") {
@@ -6248,7 +6851,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6248
6851
  if (probe.kind === "invalid") {
6249
6852
  return void 0;
6250
6853
  }
6251
- const parent = path4.dirname(directory);
6854
+ const parent = path5.dirname(directory);
6252
6855
  if (parent === directory) {
6253
6856
  return void 0;
6254
6857
  }
@@ -6264,28 +6867,28 @@ var createFilesystemWorktreeLocator = (options = {}) => {
6264
6867
 
6265
6868
  // src/state/filesystem-store.ts
6266
6869
  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";
6870
+ import { mkdir, open as open5, readFile, readdir as readdir2, rename, stat as stat4, unlink, writeFile } from "fs/promises";
6871
+ import * as path6 from "path";
6269
6872
 
6270
6873
  // src/state/keys.ts
6271
- import { createHash as createHash6 } from "crypto";
6874
+ import { createHash as createHash7 } from "crypto";
6272
6875
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
6273
6876
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
6274
6877
  var sanitizeSegment = (segment) => {
6275
6878
  if (isSafeSegment(segment)) {
6276
6879
  return segment;
6277
6880
  }
6278
- return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
6881
+ return `h_${createHash7("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
6279
6882
  };
6280
6883
  var namespaceSegments = (namespace) => [
6281
6884
  sanitizeSegment(namespace.providerId),
6282
6885
  sanitizeSegment(namespace.installationId)
6283
6886
  ];
6284
- var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
6887
+ var keyDigest = (key) => createHash7("sha256").update(key, "utf8").digest("hex");
6285
6888
 
6286
6889
  // src/state/filesystem-store.ts
6287
6890
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
6288
- var sleep = (millis) => new Promise((resolve3) => {
6891
+ var sleep2 = (millis) => new Promise((resolve3) => {
6289
6892
  setTimeout(resolve3, millis);
6290
6893
  });
6291
6894
  var wrapFsError = (thrown, operation) => {
@@ -6296,10 +6899,10 @@ var wrapFsError = (thrown, operation) => {
6296
6899
  };
6297
6900
  var createFilesystemStateStore = (options) => {
6298
6901
  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");
6902
+ const baseDir = path6.join(options.rootDir, providerSegment, installationSegment);
6903
+ const recordsDir = path6.join(baseDir, "records");
6904
+ const quarantineDir = path6.join(baseDir, "quarantine");
6905
+ const locksDir = path6.join(baseDir, "locks");
6303
6906
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
6304
6907
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
6305
6908
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -6323,11 +6926,11 @@ var createFilesystemStateStore = (options) => {
6323
6926
  throw wrapFsError(thrown, "ensure-dirs");
6324
6927
  }
6325
6928
  };
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`);
6929
+ const recordPath = (key) => path6.join(recordsDir, `${keyDigest(key)}.json`);
6930
+ const tempPath = (key) => path6.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6931
+ const lockPath = (sessionId) => path6.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6329
6932
  const quarantine = async (filePath, key, reason) => {
6330
- const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6933
+ const dest = path6.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6331
6934
  try {
6332
6935
  await rename(filePath, dest);
6333
6936
  } catch {
@@ -6391,7 +6994,7 @@ var createFilesystemStateStore = (options) => {
6391
6994
  const startedAt = options.clock.monotonicMillis();
6392
6995
  for (; ; ) {
6393
6996
  try {
6394
- const handle = await open4(filePath, "wx");
6997
+ const handle = await open5(filePath, "wx");
6395
6998
  try {
6396
6999
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
6397
7000
  } finally {
@@ -6420,7 +7023,7 @@ var createFilesystemStateStore = (options) => {
6420
7023
  } catch {
6421
7024
  }
6422
7025
  try {
6423
- const stats = await stat3(filePath);
7026
+ const stats = await stat4(filePath);
6424
7027
  return Date.now() - stats.mtimeMs > lockStaleMillis;
6425
7028
  } catch {
6426
7029
  return "gone";
@@ -6436,7 +7039,7 @@ var createFilesystemStateStore = (options) => {
6436
7039
  if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
6437
7040
  throw new StateLockTimeoutError(sessionId, timeoutMillis);
6438
7041
  }
6439
- await sleep(lockPollIntervalMillis);
7042
+ await sleep2(lockPollIntervalMillis);
6440
7043
  }
6441
7044
  };
6442
7045
  return {
@@ -6460,7 +7063,7 @@ var createFilesystemStateStore = (options) => {
6460
7063
  await ensureDirs();
6461
7064
  let entries;
6462
7065
  try {
6463
- entries = await readdir(recordsDir);
7066
+ entries = await readdir2(recordsDir);
6464
7067
  } catch (thrown) {
6465
7068
  if (isErrnoException(thrown, "ENOENT")) {
6466
7069
  return [];
@@ -6474,7 +7077,7 @@ var createFilesystemStateStore = (options) => {
6474
7077
  }
6475
7078
  let raw;
6476
7079
  try {
6477
- raw = await readFile(path5.join(recordsDir, entry), "utf8");
7080
+ raw = await readFile(path6.join(recordsDir, entry), "utf8");
6478
7081
  } catch {
6479
7082
  continue;
6480
7083
  }
@@ -6512,7 +7115,7 @@ var createFilesystemStateStore = (options) => {
6512
7115
  let scanned = 0;
6513
7116
  let entries;
6514
7117
  try {
6515
- entries = await readdir(recordsDir);
7118
+ entries = await readdir2(recordsDir);
6516
7119
  } catch (thrown) {
6517
7120
  if (!isErrnoException(thrown, "ENOENT")) {
6518
7121
  throw wrapFsError(thrown, "prune");
@@ -6527,7 +7130,7 @@ var createFilesystemStateStore = (options) => {
6527
7130
  continue;
6528
7131
  }
6529
7132
  scanned += 1;
6530
- const filePath = path5.join(recordsDir, entry);
7133
+ const filePath = path6.join(recordsDir, entry);
6531
7134
  try {
6532
7135
  const raw = await readFile(filePath, "utf8");
6533
7136
  const envelope = JSON.parse(raw);
@@ -6542,12 +7145,12 @@ var createFilesystemStateStore = (options) => {
6542
7145
  }
6543
7146
  let lockEntries;
6544
7147
  try {
6545
- lockEntries = await readdir(locksDir);
7148
+ lockEntries = await readdir2(locksDir);
6546
7149
  } catch {
6547
7150
  lockEntries = [];
6548
7151
  }
6549
7152
  for (const entry of lockEntries) {
6550
- const filePath = path5.join(locksDir, entry);
7153
+ const filePath = path6.join(locksDir, entry);
6551
7154
  try {
6552
7155
  const raw = await readFile(filePath, "utf8");
6553
7156
  const parsed = JSON.parse(raw);
@@ -6599,8 +7202,8 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6599
7202
 
6600
7203
  // src/telemetry/spool-queue.ts
6601
7204
  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";
7205
+ 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";
7206
+ import * as path7 from "path";
6604
7207
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
6605
7208
  total: 0,
6606
7209
  age: 0,
@@ -6616,7 +7219,7 @@ var enqueuedAtOf = (fileName) => {
6616
7219
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
6617
7220
  var readSpoolDropCounts = async (queueDir) => {
6618
7221
  try {
6619
- const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
7222
+ const parsed = JSON.parse(await readFile2(path7.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6620
7223
  if (typeof parsed !== "object" || parsed === null) {
6621
7224
  return EMPTY_SPOOL_DROP_COUNTS;
6622
7225
  }
@@ -6637,7 +7240,7 @@ var readSpoolDropCounts = async (queueDir) => {
6637
7240
  var readSpoolQueueStats = async (queueDir) => {
6638
7241
  let entries;
6639
7242
  try {
6640
- entries = await readdir2(queueDir);
7243
+ entries = await readdir3(queueDir);
6641
7244
  } catch {
6642
7245
  return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
6643
7246
  }
@@ -6645,7 +7248,7 @@ var readSpoolQueueStats = async (queueDir) => {
6645
7248
  let bytes = 0;
6646
7249
  for (const file of files) {
6647
7250
  try {
6648
- bytes += (await stat4(path6.join(queueDir, file))).size;
7251
+ bytes += (await stat5(path7.join(queueDir, file))).size;
6649
7252
  } catch {
6650
7253
  }
6651
7254
  }
@@ -6659,7 +7262,8 @@ var readSpoolQueueStats = async (queueDir) => {
6659
7262
  };
6660
7263
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
6661
7264
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
6662
- var CLAIM_MARKER = ".claimed-";
7265
+ var CLAIM_SUFFIX = ".claim";
7266
+ var RELEASING_SUFFIX = ".releasing";
6663
7267
  var isClaimOwnerAlive = (pid) => {
6664
7268
  if (!Number.isSafeInteger(pid) || pid <= 0) {
6665
7269
  return true;
@@ -6675,10 +7279,38 @@ var isClaimOwnerAlive = (pid) => {
6675
7279
  }
6676
7280
  };
6677
7281
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
7282
+ var readClaim = async (claimPath) => {
7283
+ try {
7284
+ const parsed = JSON.parse(await readFile2(claimPath, "utf8"));
7285
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
7286
+ } catch {
7287
+ return void 0;
7288
+ }
7289
+ };
7290
+ var releaseClaim = async (claimPath, token) => {
7291
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes3(4).toString("hex")}${RELEASING_SUFFIX}`;
7292
+ for (let attempt = 1; ; attempt += 1) {
7293
+ try {
7294
+ await rename2(claimPath, tombstone);
7295
+ break;
7296
+ } catch (thrown) {
7297
+ if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
7298
+ return;
7299
+ }
7300
+ await new Promise((resolve3) => setTimeout(resolve3, 10 * attempt));
7301
+ }
7302
+ }
7303
+ const captured = await readClaim(tombstone);
7304
+ if (captured !== void 0 && captured.token !== token) {
7305
+ await rename2(tombstone, claimPath).catch(() => void 0);
7306
+ return;
7307
+ }
7308
+ await unlink2(tombstone).catch(() => void 0);
7309
+ };
6678
7310
  var createSpoolQueue = (options) => {
6679
7311
  const [providerSegment, installationSegment] = namespaceSegments(options);
6680
- const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6681
- const corruptDir = path6.join(
7312
+ const queueDir = path7.join(options.rootDir, providerSegment, installationSegment, options.queueName);
7313
+ const corruptDir = path7.join(
6682
7314
  options.rootDir,
6683
7315
  providerSegment,
6684
7316
  installationSegment,
@@ -6704,7 +7336,7 @@ var createSpoolQueue = (options) => {
6704
7336
  const listSorted = async () => {
6705
7337
  let entries;
6706
7338
  try {
6707
- entries = await readdir2(queueDir);
7339
+ entries = await readdir3(queueDir);
6708
7340
  } catch (thrown) {
6709
7341
  if (isErrnoException2(thrown, "ENOENT")) {
6710
7342
  return [];
@@ -6725,9 +7357,9 @@ var createSpoolQueue = (options) => {
6725
7357
  [reason]: current[reason] + dropped,
6726
7358
  lastDroppedAt: options.clock.now()
6727
7359
  };
6728
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
7360
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6729
7361
  await writeFile2(tmp, JSON.stringify(next), "utf8");
6730
- await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
7362
+ await rename2(tmp, path7.join(queueDir, SPOOL_DROPS_FILE));
6731
7363
  } catch {
6732
7364
  }
6733
7365
  options.logger?.warn("durable spool dropped batches", {
@@ -6743,7 +7375,7 @@ var createSpoolQueue = (options) => {
6743
7375
  let bytes = 0;
6744
7376
  if (options.maxBytes !== void 0) {
6745
7377
  try {
6746
- bytes = (await stat4(path6.join(queueDir, name))).size;
7378
+ bytes = (await stat5(path7.join(queueDir, name))).size;
6747
7379
  } catch {
6748
7380
  continue;
6749
7381
  }
@@ -6757,7 +7389,7 @@ var createSpoolQueue = (options) => {
6757
7389
  let removed = 0;
6758
7390
  for (const file of files) {
6759
7391
  try {
6760
- await unlink2(path6.join(queueDir, file.name));
7392
+ await unlink2(path7.join(queueDir, file.name));
6761
7393
  removed += 1;
6762
7394
  } catch {
6763
7395
  }
@@ -6817,33 +7449,63 @@ var createSpoolQueue = (options) => {
6817
7449
  }
6818
7450
  }
6819
7451
  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`);
7452
+ const target = path7.join(queueDir, fileName);
7453
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6822
7454
  await writeFile2(tmp, serialized, "utf8");
6823
7455
  await rename2(tmp, target);
6824
7456
  return { spooled: true };
6825
7457
  };
7458
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
7459
+ const staleClaim = async (claimPath) => {
7460
+ const claim = await readClaim(claimPath);
7461
+ const now = Date.now();
7462
+ if (claim !== void 0) {
7463
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
7464
+ }
7465
+ try {
7466
+ return now - (await stat5(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
7467
+ } catch {
7468
+ return { stale: false };
7469
+ }
7470
+ };
6826
7471
  const releaseStaleClaims = async () => {
6827
7472
  let entries;
6828
7473
  try {
6829
- entries = await readdir2(queueDir);
7474
+ entries = await readdir3(queueDir);
6830
7475
  } catch {
6831
7476
  return;
6832
7477
  }
6833
7478
  const now = Date.now();
6834
7479
  for (const entry of entries) {
6835
- const marker = entry.lastIndexOf(CLAIM_MARKER);
6836
- if (marker <= 0) {
6837
- continue;
7480
+ const entryPath = path7.join(queueDir, entry);
7481
+ if (entry.endsWith(CLAIM_SUFFIX)) {
7482
+ const staleness = await staleClaim(entryPath);
7483
+ if (staleness.stale) {
7484
+ await releaseClaim(entryPath, staleness.token);
7485
+ }
7486
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
7487
+ try {
7488
+ if (now - (await stat5(entryPath)).mtimeMs > claimStaleMillis) {
7489
+ await unlink2(entryPath);
7490
+ }
7491
+ } catch {
7492
+ }
6838
7493
  }
6839
- const claimPath = path6.join(queueDir, entry);
6840
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
7494
+ }
7495
+ };
7496
+ const claimBatch = async (claimPath) => {
7497
+ const token = randomBytes3(16).toString("hex");
7498
+ try {
7499
+ const handle = await open6(claimPath, "wx");
6841
7500
  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 {
7501
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
7502
+ await handle.writeFile(JSON.stringify(contents), "utf8");
7503
+ } finally {
7504
+ await handle.close();
6846
7505
  }
7506
+ return token;
7507
+ } catch {
7508
+ return void 0;
6847
7509
  }
6848
7510
  };
6849
7511
  const drain = async (send, drainOptions) => {
@@ -6867,21 +7529,7 @@ var createSpoolQueue = (options) => {
6867
7529
  let failed = 0;
6868
7530
  let quarantined = 0;
6869
7531
  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
- }
7532
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
6885
7533
  const quarantine = async (rejection) => {
6886
7534
  quarantined += 1;
6887
7535
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6890,7 +7538,7 @@ var createSpoolQueue = (options) => {
6890
7538
  "spool.queue": options.queueName
6891
7539
  });
6892
7540
  try {
6893
- await rename2(filePath, path6.join(corruptDir, fileName));
7541
+ await rename2(filePath, path7.join(corruptDir, fileName));
6894
7542
  } catch {
6895
7543
  await unlink2(filePath).catch(() => void 0);
6896
7544
  }
@@ -6900,17 +7548,17 @@ var createSpoolQueue = (options) => {
6900
7548
  text = await readFile2(filePath, "utf8");
6901
7549
  } catch (thrown) {
6902
7550
  if (thrown?.code === "ENOENT") {
6903
- continue;
7551
+ return "next";
6904
7552
  }
6905
7553
  await quarantine("unreadable");
6906
- continue;
7554
+ return "next";
6907
7555
  }
6908
7556
  let parsed;
6909
7557
  try {
6910
7558
  parsed = JSON.parse(text);
6911
7559
  } catch {
6912
7560
  await quarantine("unparseable-json");
6913
- continue;
7561
+ return "next";
6914
7562
  }
6915
7563
  const validation = options.validate(parsed, {
6916
7564
  providerId: options.providerId,
@@ -6918,7 +7566,10 @@ var createSpoolQueue = (options) => {
6918
7566
  });
6919
7567
  if ("rejection" in validation) {
6920
7568
  await quarantine(validation.rejection);
6921
- continue;
7569
+ return "next";
7570
+ }
7571
+ if ((await readClaim(claimPath))?.token !== token) {
7572
+ return "next";
6922
7573
  }
6923
7574
  let delivered;
6924
7575
  try {
@@ -6930,14 +7581,34 @@ var createSpoolQueue = (options) => {
6930
7581
  if (await unlink2(filePath).then(() => true, () => false)) {
6931
7582
  await recordDrops("rejected", 1);
6932
7583
  }
6933
- continue;
7584
+ return "next";
6934
7585
  }
6935
7586
  if (delivered) {
6936
7587
  await unlink2(filePath).catch(() => void 0);
6937
7588
  drained += 1;
6938
- } else {
6939
- await rename2(filePath, queuedPath).catch(() => void 0);
6940
- failed += 1;
7589
+ return "next";
7590
+ }
7591
+ failed += 1;
7592
+ return "stop";
7593
+ };
7594
+ for (; index < files.length && index < cap; index += 1) {
7595
+ const fileName = files[index];
7596
+ if (fileName === void 0) {
7597
+ break;
7598
+ }
7599
+ const filePath = path7.join(queueDir, fileName);
7600
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
7601
+ const token = await claimBatch(claimPath);
7602
+ if (token === void 0) {
7603
+ continue;
7604
+ }
7605
+ let outcome;
7606
+ try {
7607
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
7608
+ } finally {
7609
+ await releaseClaim(claimPath, token);
7610
+ }
7611
+ if (outcome === "stop") {
6941
7612
  break;
6942
7613
  }
6943
7614
  }
@@ -7231,9 +7902,220 @@ var createFileDurableSpool = (options) => createSpoolQueue({
7231
7902
  validate: validateSpoolBatch
7232
7903
  });
7233
7904
 
7905
+ // src/telemetry/endpoint-health.ts
7906
+ import { createHash as createHash8, randomBytes as randomBytes4 } from "crypto";
7907
+ import { mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
7908
+ import * as http from "http";
7909
+ import * as https from "https";
7910
+ import path8 from "path";
7911
+ import { ExportResultCode } from "@opentelemetry/core";
7912
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
7913
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
7914
+ "ECONNREFUSED",
7915
+ "ECONNRESET",
7916
+ "ETIMEDOUT",
7917
+ "EPIPE",
7918
+ "EHOSTUNREACH",
7919
+ "ENETUNREACH",
7920
+ "EHOSTDOWN",
7921
+ "ENETDOWN",
7922
+ "EAI_AGAIN",
7923
+ "ENOTFOUND",
7924
+ ENDPOINT_DOWN_ERROR_CODE
7925
+ ]);
7926
+ var isUnreachableExportFailure = (result) => {
7927
+ if (result.code === ExportResultCode.SUCCESS) {
7928
+ return false;
7929
+ }
7930
+ const error = result.error;
7931
+ const code = error?.code;
7932
+ if (typeof code === "string") {
7933
+ return UNREACHABLE_NETWORK_CODES.has(code);
7934
+ }
7935
+ if (code !== void 0) {
7936
+ return false;
7937
+ }
7938
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
7939
+ };
7940
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
7941
+ const target = agent;
7942
+ const original = target.createConnection.bind(agent);
7943
+ target.createConnection = (options, callback) => {
7944
+ const socket = original(options, callback);
7945
+ if (socket !== void 0 && socket.connecting) {
7946
+ const timer = setTimeout(() => {
7947
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
7948
+ socket.destroy(error);
7949
+ }, connectTimeoutMillis);
7950
+ timer.unref();
7951
+ const clear = () => {
7952
+ clearTimeout(timer);
7953
+ };
7954
+ socket.once("connect", clear);
7955
+ socket.once("close", clear);
7956
+ }
7957
+ return socket;
7958
+ };
7959
+ return agent;
7960
+ };
7961
+ var boundedExporterOptions = (exporter) => {
7962
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
7963
+ let agents = {};
7964
+ return {
7965
+ timeoutMillis,
7966
+ httpAgentOptions: (protocol) => {
7967
+ if (protocol === "https:") {
7968
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
7969
+ return agents.https;
7970
+ }
7971
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
7972
+ return agents.http;
7973
+ }
7974
+ };
7975
+ };
7976
+ var parseMark = (raw) => {
7977
+ try {
7978
+ const parsed = JSON.parse(raw);
7979
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
7980
+ downUntil: parsed.downUntil,
7981
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
7982
+ } : void 0;
7983
+ } catch {
7984
+ return void 0;
7985
+ }
7986
+ };
7987
+ var originOf = (url) => {
7988
+ if (url === void 0) {
7989
+ return void 0;
7990
+ }
7991
+ try {
7992
+ return new URL(url).origin;
7993
+ } catch {
7994
+ return void 0;
7995
+ }
7996
+ };
7997
+ var createEndpointHealth = (options) => {
7998
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
7999
+ const gates = /* @__PURE__ */ new Map();
8000
+ const createGate = (origin) => {
8001
+ const digest3 = createHash8("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
8002
+ const dir = options.rootDir === void 0 ? void 0 : path8.join(options.rootDir, "endpoint-health");
8003
+ const file = dir === void 0 ? void 0 : path8.join(dir, `${digest3}.json`);
8004
+ let downUntil = 0;
8005
+ let failures = 0;
8006
+ let marked = false;
8007
+ let loaded;
8008
+ let warned = false;
8009
+ const write = async (mark) => {
8010
+ if (file === void 0 || dir === void 0) {
8011
+ return;
8012
+ }
8013
+ try {
8014
+ await mkdir3(dir, { recursive: true });
8015
+ const tmp = path8.join(dir, `.tmp-${randomBytes4(6).toString("hex")}.json`);
8016
+ await writeFile3(tmp, `${JSON.stringify(mark)}
8017
+ `);
8018
+ await rename3(tmp, file);
8019
+ marked = true;
8020
+ } catch {
8021
+ }
8022
+ };
8023
+ const load = () => {
8024
+ loaded ??= (async () => {
8025
+ if (file === void 0) {
8026
+ return;
8027
+ }
8028
+ let raw;
8029
+ try {
8030
+ raw = await readFile3(file, "utf8");
8031
+ } catch {
8032
+ return;
8033
+ }
8034
+ marked = true;
8035
+ const mark = parseMark(raw);
8036
+ if (mark === void 0) {
8037
+ return;
8038
+ }
8039
+ failures = mark.failures;
8040
+ const now = options.clock.now();
8041
+ if (mark.downUntil > now) {
8042
+ downUntil = mark.downUntil;
8043
+ return;
8044
+ }
8045
+ await write({ downUntil: now + options.probeMillis, failures });
8046
+ })();
8047
+ return loaded;
8048
+ };
8049
+ return {
8050
+ available: async () => {
8051
+ if (downMillis === 0) {
8052
+ return true;
8053
+ }
8054
+ await load();
8055
+ return options.clock.now() >= downUntil;
8056
+ },
8057
+ record: async (result) => {
8058
+ if (downMillis === 0) {
8059
+ return;
8060
+ }
8061
+ if (!isUnreachableExportFailure(result)) {
8062
+ if (!marked && downUntil === 0) {
8063
+ return;
8064
+ }
8065
+ downUntil = 0;
8066
+ failures = 0;
8067
+ marked = false;
8068
+ if (file !== void 0) {
8069
+ await unlink3(file).catch(() => void 0);
8070
+ }
8071
+ return;
8072
+ }
8073
+ failures += 1;
8074
+ downUntil = options.clock.now() + downMillis;
8075
+ if (!warned) {
8076
+ warned = true;
8077
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
8078
+ "export.endpoint_down_millis": downMillis,
8079
+ "export.endpoint_failures": failures
8080
+ });
8081
+ }
8082
+ await write({ downUntil, failures });
8083
+ }
8084
+ };
8085
+ };
8086
+ return {
8087
+ gateFor: (url) => {
8088
+ const origin = originOf(url);
8089
+ if (origin === void 0) {
8090
+ return void 0;
8091
+ }
8092
+ let gate = gates.get(origin);
8093
+ if (gate === void 0) {
8094
+ gate = createGate(origin);
8095
+ gates.set(origin, gate);
8096
+ }
8097
+ return gate;
8098
+ }
8099
+ };
8100
+ };
8101
+ var guardExport = async (gate, send) => {
8102
+ if (gate === void 0) {
8103
+ return send();
8104
+ }
8105
+ if (!await gate.available()) {
8106
+ return {
8107
+ code: ExportResultCode.FAILED,
8108
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
8109
+ };
8110
+ }
8111
+ const result = await send();
8112
+ await gate.record(result).catch(() => void 0);
8113
+ return result;
8114
+ };
8115
+
7234
8116
  // src/telemetry/otlp-log-sink.ts
7235
8117
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
7236
- import { ExportResultCode } from "@opentelemetry/core";
8118
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
7237
8119
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
7238
8120
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
7239
8121
 
@@ -7814,12 +8696,16 @@ var createOtlpLogSink = (options) => {
7814
8696
  const exporter = new OTLPLogExporter({
7815
8697
  url: deliverability.endpoint,
7816
8698
  headers: { ...options.headers },
7817
- timeoutMillis: options.exporter.timeoutMillis
8699
+ ...boundedExporterOptions(options.exporter)
7818
8700
  });
8701
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
7819
8702
  let shutdownCompleted = false;
7820
- const exportRecords = (records) => new Promise((resolve3) => {
7821
- exporter.export([...records], (result) => resolve3(result));
7822
- });
8703
+ const exportRecords = (records) => guardExport(
8704
+ gate,
8705
+ () => new Promise((resolve3) => {
8706
+ exporter.export([...records], (result) => resolve3(result));
8707
+ })
8708
+ );
7823
8709
  const toSpoolBatch = (records, batchResource) => ({
7824
8710
  providerId: options.providerId,
7825
8711
  installationId: options.installationId,
@@ -7837,7 +8723,7 @@ var createOtlpLogSink = (options) => {
7837
8723
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
7838
8724
  );
7839
8725
  const result = await exportRecords(records);
7840
- if (result.code === ExportResultCode.SUCCESS) {
8726
+ if (result.code === ExportResultCode2.SUCCESS) {
7841
8727
  return true;
7842
8728
  }
7843
8729
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -7883,11 +8769,11 @@ var createOtlpLogSink = (options) => {
7883
8769
  result = await exportRecords(batch);
7884
8770
  } catch (thrown) {
7885
8771
  result = {
7886
- code: ExportResultCode.FAILED,
8772
+ code: ExportResultCode2.FAILED,
7887
8773
  error: thrown instanceof Error ? thrown : new Error("export threw")
7888
8774
  };
7889
8775
  }
7890
- if (result.code === ExportResultCode.SUCCESS) {
8776
+ if (result.code === ExportResultCode2.SUCCESS) {
7891
8777
  accepted += batch.length;
7892
8778
  health.recordSuccess(batch.length, options.clock.now());
7893
8779
  continue;
@@ -7928,6 +8814,9 @@ var createOtlpLogSink = (options) => {
7928
8814
  if (options.spool === void 0) {
7929
8815
  return { drained: 0, remaining: 0, failed: 0 };
7930
8816
  }
8817
+ if (gate !== void 0 && !await gate.available()) {
8818
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
8819
+ }
7931
8820
  const result = await options.spool.drain(sendSerializedBatch, {
7932
8821
  ...maxBatches === void 0 ? {} : { maxBatches }
7933
8822
  });
@@ -7965,7 +8854,7 @@ var createOtlpLogSink = (options) => {
7965
8854
 
7966
8855
  // src/telemetry/otlp-metric-sink.ts
7967
8856
  import { ValueType } from "@opentelemetry/api";
7968
- import { ExportResultCode as ExportResultCode2, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
8857
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
7969
8858
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
7970
8859
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
7971
8860
  import {
@@ -8109,10 +8998,12 @@ var createOtlpMetricSink = (options) => {
8109
8998
  const exporter = new OTLPMetricExporter({
8110
8999
  url: deliverability.endpoint,
8111
9000
  headers: { ...options.headers },
8112
- timeoutMillis: options.exporter.timeoutMillis
9001
+ ...boundedExporterOptions(options.exporter)
8113
9002
  });
9003
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
8114
9004
  let shutdownCompleted = false;
8115
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
9005
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
9006
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
8116
9007
  const payload = {
8117
9008
  resource: batchResource,
8118
9009
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -8121,7 +9012,7 @@ var createOtlpMetricSink = (options) => {
8121
9012
  exporter.export(payload, (result) => resolve3(result));
8122
9013
  } catch (thrown) {
8123
9014
  resolve3({
8124
- code: ExportResultCode2.FAILED,
9015
+ code: ExportResultCode3.FAILED,
8125
9016
  error: thrown instanceof Error ? thrown : new Error("export threw")
8126
9017
  });
8127
9018
  }
@@ -8142,7 +9033,7 @@ var createOtlpMetricSink = (options) => {
8142
9033
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
8143
9034
  );
8144
9035
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
8145
- if (result.code === ExportResultCode2.SUCCESS) {
9036
+ if (result.code === ExportResultCode3.SUCCESS) {
8146
9037
  return true;
8147
9038
  }
8148
9039
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -8153,7 +9044,7 @@ var createOtlpMetricSink = (options) => {
8153
9044
  }
8154
9045
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
8155
9046
  const result = await exportResourceMetrics(points, batchResource, scope);
8156
- if (result.code === ExportResultCode2.SUCCESS) {
9047
+ if (result.code === ExportResultCode3.SUCCESS) {
8157
9048
  health.recordSuccess(points.length, options.clock.now());
8158
9049
  return { accepted: points.length, rejected: 0, errors: [] };
8159
9050
  }
@@ -8193,6 +9084,9 @@ var createOtlpMetricSink = (options) => {
8193
9084
  if (options.spool === void 0) {
8194
9085
  return { drained: 0, remaining: 0, failed: 0 };
8195
9086
  }
9087
+ if (gate !== void 0 && !await gate.available()) {
9088
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
9089
+ }
8196
9090
  const result = await options.spool.drain(sendSerializedBatch, {
8197
9091
  ...maxBatches === void 0 ? {} : { maxBatches }
8198
9092
  });
@@ -8230,7 +9124,7 @@ var createOtlpMetricSink = (options) => {
8230
9124
  };
8231
9125
 
8232
9126
  // src/telemetry/otlp-sink.ts
8233
- import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
9127
+ import { ExportResultCode as ExportResultCode4 } from "@opentelemetry/core";
8234
9128
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
8235
9129
  var chunk2 = (items, size) => {
8236
9130
  if (size <= 0 || items.length <= size) {
@@ -8308,12 +9202,16 @@ var createOtlpTraceSink = (options) => {
8308
9202
  const exporter = new OTLPTraceExporter({
8309
9203
  url: options.exporter.endpoint,
8310
9204
  headers: { ...options.headers },
8311
- timeoutMillis: options.exporter.timeoutMillis
9205
+ ...boundedExporterOptions(options.exporter)
8312
9206
  });
9207
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
8313
9208
  let shutdownCompleted = false;
8314
- const exportSpans = (spans) => new Promise((resolve3) => {
8315
- exporter.export([...spans], (result) => resolve3(result));
8316
- });
9209
+ const exportSpans = (spans) => guardExport(
9210
+ gate,
9211
+ () => new Promise((resolve3) => {
9212
+ exporter.export([...spans], (result) => resolve3(result));
9213
+ })
9214
+ );
8317
9215
  const toSpoolBatch = (spans, batchResource) => ({
8318
9216
  providerId: options.providerId,
8319
9217
  installationId: options.installationId,
@@ -8326,7 +9224,7 @@ var createOtlpTraceSink = (options) => {
8326
9224
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
8327
9225
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
8328
9226
  const result = await exportSpans(spans);
8329
- if (result.code === ExportResultCode3.SUCCESS) {
9227
+ if (result.code === ExportResultCode4.SUCCESS) {
8330
9228
  return true;
8331
9229
  }
8332
9230
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -8365,9 +9263,9 @@ var createOtlpTraceSink = (options) => {
8365
9263
  try {
8366
9264
  result = await exportSpans(batch);
8367
9265
  } catch (thrown) {
8368
- result = { code: ExportResultCode3.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
9266
+ result = { code: ExportResultCode4.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
8369
9267
  }
8370
- if (result.code === ExportResultCode3.SUCCESS) {
9268
+ if (result.code === ExportResultCode4.SUCCESS) {
8371
9269
  accepted += batch.length;
8372
9270
  health.recordSuccess(batch.length, options.clock.now());
8373
9271
  continue;
@@ -8404,6 +9302,9 @@ var createOtlpTraceSink = (options) => {
8404
9302
  if (options.spool === void 0) {
8405
9303
  return { drained: 0, remaining: 0, failed: 0 };
8406
9304
  }
9305
+ if (gate !== void 0 && !await gate.available()) {
9306
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
9307
+ }
8407
9308
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
8408
9309
  if (result.drained > 0) {
8409
9310
  health.recordSuccess(result.drained, options.clock.now());
@@ -8437,6 +9338,101 @@ var createOtlpTraceSink = (options) => {
8437
9338
  };
8438
9339
  };
8439
9340
 
9341
+ // src/telemetry/destination-scope.ts
9342
+ var DISCLOSURE_RANK2 = Object.freeze({
9343
+ omitted: 0,
9344
+ masked: 1,
9345
+ redacted: 2,
9346
+ raw: 3
9347
+ });
9348
+ var omitRestrictedContent = (fact, mode) => {
9349
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
9350
+ return fact;
9351
+ }
9352
+ const { text, ...rest } = fact;
9353
+ void text;
9354
+ return { ...rest, disclosure: "omitted", truncated: false };
9355
+ };
9356
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
9357
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
9358
+ var eventRepositoryKey = (event2, fallbackKey) => {
9359
+ const stamped = event2.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
9360
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
9361
+ };
9362
+ var pointRepositoryKey = (point, fallbackKey) => {
9363
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
9364
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
9365
+ };
9366
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
9367
+ var restrictEventContent = (event2, mode, restrict) => {
9368
+ switch (event2.type) {
9369
+ case "prompt.submitted":
9370
+ return event2.content === void 0 ? event2 : { ...event2, content: restrict(event2.content, mode) };
9371
+ case "generation.start": {
9372
+ const inputContent = restrictFacts(event2.inputContent, mode, restrict);
9373
+ return inputContent === void 0 ? event2 : { ...event2, inputContent };
9374
+ }
9375
+ case "generation.end": {
9376
+ const outputContent = restrictFacts(event2.outputContent, mode, restrict);
9377
+ return outputContent === void 0 ? event2 : { ...event2, outputContent };
9378
+ }
9379
+ case "tool.start":
9380
+ return event2.input === void 0 ? event2 : { ...event2, input: restrict(event2.input, mode) };
9381
+ case "tool.end":
9382
+ return event2.output === void 0 ? event2 : { ...event2, output: restrict(event2.output, mode) };
9383
+ case "error.raised":
9384
+ return event2.message === void 0 ? event2 : { ...event2, message: restrict(event2.message, mode) };
9385
+ default:
9386
+ return event2;
9387
+ }
9388
+ };
9389
+ var routeEventsToScopes = (events, scopes, options) => {
9390
+ const ends = spanEndEdgesOf(events);
9391
+ const traces = [];
9392
+ const logs = [];
9393
+ let unchanged = true;
9394
+ for (const event2 of events) {
9395
+ const anchor = ends.get(event2.eventId) ?? event2;
9396
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
9397
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
9398
+ unchanged = false;
9399
+ }
9400
+ if (scope === void 0) {
9401
+ continue;
9402
+ }
9403
+ const restricted = scope.contentMode === void 0 ? event2 : restrictEventContent(event2, scope.contentMode, options.restrict);
9404
+ if (restricted !== event2) {
9405
+ unchanged = false;
9406
+ }
9407
+ if (scope.signals.traces) {
9408
+ traces.push(restricted);
9409
+ }
9410
+ if (scope.signals.logs) {
9411
+ logs.push(restricted);
9412
+ }
9413
+ }
9414
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
9415
+ };
9416
+ var routePointsToScopes = (scopes, pointsFor, options) => {
9417
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
9418
+ const kept = [];
9419
+ for (const variant of [true, false]) {
9420
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
9421
+ continue;
9422
+ }
9423
+ for (const point of pointsFor(variant) ?? []) {
9424
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
9425
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
9426
+ kept.push(point);
9427
+ }
9428
+ }
9429
+ }
9430
+ return kept;
9431
+ };
9432
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
9433
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
9434
+ );
9435
+
8440
9436
  // src/telemetry/signal-fanout.ts
8441
9437
  var createSignalFanout = (options) => {
8442
9438
  const emit = async (events) => {
@@ -8469,14 +9465,20 @@ var createSignalFanout = (options) => {
8469
9465
  };
8470
9466
  var shareCorrelationPerBatch = (correlate) => {
8471
9467
  let pending;
8472
- return (events) => {
8473
- if (pending?.events === events) {
9468
+ const resolve3 = (events) => {
9469
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
8474
9470
  return pending.result;
8475
9471
  }
8476
9472
  const result = correlate(events);
8477
- pending = { events, result };
9473
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
8478
9474
  return result;
8479
9475
  };
9476
+ const alias = (subset, batch) => {
9477
+ if (pending?.events === batch && subset !== batch) {
9478
+ pending.aliases.add(subset);
9479
+ }
9480
+ };
9481
+ return Object.assign(resolve3, { alias });
8480
9482
  };
8481
9483
 
8482
9484
  // src/telemetry/export-destinations.ts
@@ -8538,6 +9540,15 @@ var createExportDestinationSinks = (options) => {
8538
9540
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
8539
9541
  const destinations = [];
8540
9542
  const skipped = [];
9543
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
9544
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
9545
+ clock: options.clock,
9546
+ ...options.logger === void 0 ? {} : { logger: options.logger },
9547
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
9548
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
9549
+ });
9550
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
9551
+ const restrict = options.restrictContent ?? omitRestrictedContent;
8541
9552
  for (const destination of resolveExportDestinations(options.exporter)) {
8542
9553
  let headers;
8543
9554
  let logHeaders;
@@ -8597,6 +9608,7 @@ var createExportDestinationSinks = (options) => {
8597
9608
  const sinkShared = {
8598
9609
  exporter: policy,
8599
9610
  ...shared,
9611
+ endpointHealth,
8600
9612
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
8601
9613
  ...label === void 0 ? {} : { destination: label }
8602
9614
  };
@@ -8614,6 +9626,7 @@ var createExportDestinationSinks = (options) => {
8614
9626
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
8615
9627
  exporter: policy,
8616
9628
  ...shared,
9629
+ endpointHealth,
8617
9630
  ...label === void 0 ? {} : { destination: label },
8618
9631
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
8619
9632
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -8625,17 +9638,51 @@ var createExportDestinationSinks = (options) => {
8625
9638
  metrics,
8626
9639
  ...spool === void 0 ? {} : { spool },
8627
9640
  ...logSpool === void 0 ? {} : { logSpool },
8628
- ...metricSpool === void 0 ? {} : { metricSpool }
9641
+ ...metricSpool === void 0 ? {} : { metricSpool },
9642
+ ...destination.scopes === void 0 ? {} : {
9643
+ scopes: destination.scopes,
9644
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
9645
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
9646
+ restrict
9647
+ })
9648
+ }
8629
9649
  });
8630
9650
  }
8631
9651
  return { destinations, skipped };
8632
9652
  };
8633
- var createDestinationFanout = (destinations) => {
9653
+ var createScopedFanout = (destination, correlate) => {
9654
+ const route = destination.route;
9655
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
9656
+ if (route === void 0) {
9657
+ return unscoped;
9658
+ }
9659
+ const none = { accepted: 0, rejected: 0, errors: [] };
9660
+ return {
9661
+ ...unscoped,
9662
+ emit: async (events) => {
9663
+ const batch = route(events);
9664
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
9665
+ await correlate(events);
9666
+ correlate.alias(batch.traces, events);
9667
+ correlate.alias(batch.logs, events);
9668
+ }
9669
+ const traces = batch.traces.length === 0 ? none : await destination.traces.emit(batch.traces);
9670
+ const logs = batch.logs.length === 0 ? none : await destination.logs.emit(batch.logs);
9671
+ return {
9672
+ accepted: traces.accepted + logs.accepted,
9673
+ rejected: traces.rejected + logs.rejected,
9674
+ errors: [...traces.errors, ...logs.errors]
9675
+ };
9676
+ }
9677
+ };
9678
+ };
9679
+ var createDestinationFanout = (destinations, options = {}) => {
8634
9680
  const fanouts = destinations.map((destination) => ({
8635
9681
  name: destination.name,
8636
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
9682
+ sink: createScopedFanout(destination, options.correlate)
8637
9683
  }));
8638
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
9684
+ const scoped = destinations.some((destination) => destination.route !== void 0);
9685
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
8639
9686
  if (only !== void 0) {
8640
9687
  return only.sink;
8641
9688
  }
@@ -8756,7 +9803,8 @@ var createHookRuntime = (options) => {
8756
9803
  // has always been governed by.
8757
9804
  allowRawContent: privacy.policy.allowRawContent
8758
9805
  },
8759
- correlate
9806
+ correlate,
9807
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
8760
9808
  });
8761
9809
  const primary = exportDestinations.destinations[0];
8762
9810
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -8773,7 +9821,7 @@ var createHookRuntime = (options) => {
8773
9821
  });
8774
9822
  const spool = primary?.spool;
8775
9823
  const logSpool = primary?.logSpool;
8776
- const sink = createDestinationFanout(exportDestinations.destinations);
9824
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
8777
9825
  const hookDeps = {
8778
9826
  stateStore,
8779
9827
  config: options.config,
@@ -8783,7 +9831,14 @@ var createHookRuntime = (options) => {
8783
9831
  privacy,
8784
9832
  logger,
8785
9833
  installationId: options.installationId,
8786
- payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
9834
+ payloadEnrichers: options.payloadEnrichers ?? [
9835
+ ...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
9836
+ ...readsCodexRolloutUsage(options.config) ? [
9837
+ createCodexRolloutUsageEnricher(
9838
+ options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
9839
+ )
9840
+ ] : []
9841
+ ],
8787
9842
  ...(() => {
8788
9843
  if (options.sessionContextReader === null) {
8789
9844
  return {};
@@ -8807,6 +9862,8 @@ var createHookRuntime = (options) => {
8807
9862
  (destination) => destination.metrics.enabled
8808
9863
  );
8809
9864
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
9865
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
9866
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
8810
9867
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
8811
9868
  if (deliveryRetentionMillis < staleClaimMillis) {
8812
9869
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -8872,28 +9929,63 @@ var createHookRuntime = (options) => {
8872
9929
  turnStarts.set(event2.sessionId, await metricSeries.readTurnStart(event2.sessionId));
8873
9930
  }
8874
9931
  }
8875
- const observations = deriveMetricObservations({
8876
- events: ingest.events,
8877
- usage: ingest.usageObservations,
8878
- resource: metricResource,
8879
- includeSessionId: metricsPolicy.includeSessionId,
8880
- ...generationStarts === void 0 ? {} : { generationStarts },
8881
- turnStart: (sessionId) => turnStarts.get(sessionId)
8882
- });
8883
- if (observations.length === 0) {
9932
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
9933
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
9934
+ const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
9935
+ (event2) => event2.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
9936
+ ...event2,
9937
+ contextAttributes: {
9938
+ ...event2.contextAttributes,
9939
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
9940
+ }
9941
+ } : event2
9942
+ );
9943
+ const pointsByVariant = /* @__PURE__ */ new Map();
9944
+ const variants = new Set(
9945
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
9946
+ );
9947
+ for (const destination of scopedMetricDestinations) {
9948
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
9949
+ variants.add(variant);
9950
+ }
9951
+ }
9952
+ for (const includeSessionId of variants) {
9953
+ const observations = deriveMetricObservations({
9954
+ events: metricEvents,
9955
+ usage: ingest.usageObservations,
9956
+ resource: metricResource,
9957
+ includeSessionId,
9958
+ ...generationStarts === void 0 ? {} : { generationStarts },
9959
+ turnStart: (sessionId) => turnStarts.get(sessionId)
9960
+ });
9961
+ if (observations.length === 0) {
9962
+ continue;
9963
+ }
9964
+ pointsByVariant.set(
9965
+ includeSessionId,
9966
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
9967
+ perSession: includeSessionId,
9968
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
9969
+ })
9970
+ );
9971
+ }
9972
+ if (pointsByVariant.size === 0) {
8884
9973
  return void 0;
8885
9974
  }
8886
- const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
8887
- perSession: metricsPolicy.includeSessionId,
8888
- ...deliveryToken === void 0 ? {} : { deliveryToken }
8889
- });
8890
9975
  const context = agreedContextAttributes(ingest.events);
8891
9976
  const results = await Promise.all(
8892
9977
  metricDestinations.map(async (destination) => {
8893
- const result = await destination.metrics.exportPoints(points, context).catch(
9978
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
9979
+ fallbackKey: scopedRepositoryFallback,
9980
+ includeSessionId: metricsPolicy.includeSessionId
9981
+ });
9982
+ if (points2.length === 0) {
9983
+ return { name: destination.name, accepted: 0, rejected: 0 };
9984
+ }
9985
+ const result = await destination.metrics.exportPoints(points2, context).catch(
8894
9986
  (thrown) => ({
8895
9987
  accepted: 0,
8896
- rejected: points.length,
9988
+ rejected: points2.length,
8897
9989
  errors: [
8898
9990
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
8899
9991
  ]
@@ -8903,7 +9995,8 @@ var createHookRuntime = (options) => {
8903
9995
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
8904
9996
  })
8905
9997
  );
8906
- return { points: points.length, destinations: results };
9998
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
9999
+ return { points, destinations: results };
8907
10000
  } catch (thrown) {
8908
10001
  diagnostics.push(stateDiagnostic(thrown));
8909
10002
  logger.warn("hook-derived metrics could not be recorded for this callback", {});